Harmonize parameter names in ecpg code.
[pgsql.git] / src / bin / pg_ctl / pg_ctl.c
blob9291c61d000feeb2443b49f8739809a433a7781d
1 /*-------------------------------------------------------------------------
3 * pg_ctl --- start/stops/restarts the PostgreSQL server
5 * Portions Copyright (c) 1996-2022, PostgreSQL Global Development Group
7 * src/bin/pg_ctl/pg_ctl.c
9 *-------------------------------------------------------------------------
12 #include "postgres_fe.h"
14 #include <fcntl.h>
15 #include <signal.h>
16 #include <time.h>
17 #include <sys/resource.h>
18 #include <sys/stat.h>
19 #include <sys/time.h>
20 #include <sys/wait.h>
21 #include <unistd.h>
24 #include "catalog/pg_control.h"
25 #include "common/controldata_utils.h"
26 #include "common/file_perm.h"
27 #include "common/logging.h"
28 #include "common/string.h"
29 #include "getopt_long.h"
30 #include "utils/pidfile.h"
32 #ifdef WIN32 /* on Unix, we don't need libpq */
33 #include "pqexpbuffer.h"
34 #endif
36 /* PID can be negative for standalone backend */
37 typedef long pgpid_t;
40 typedef enum
42 SMART_MODE,
43 FAST_MODE,
44 IMMEDIATE_MODE
45 } ShutdownMode;
47 typedef enum
49 POSTMASTER_READY,
50 POSTMASTER_STILL_STARTING,
51 POSTMASTER_FAILED
52 } WaitPMResult;
54 typedef enum
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 LOGROTATE_COMMAND,
65 KILL_COMMAND,
66 REGISTER_COMMAND,
67 UNREGISTER_COMMAND,
68 RUN_AS_SERVICE_COMMAND
69 } CtlCommand;
71 #define DEFAULT_WAIT 60
73 #define USEC_PER_SEC 1000000
75 #define WAITS_PER_SEC 10 /* should divide USEC_PER_SEC evenly */
77 static bool do_wait = true;
78 static int wait_seconds = DEFAULT_WAIT;
79 static bool wait_seconds_arg = false;
80 static bool silent_mode = false;
81 static ShutdownMode shutdown_mode = FAST_MODE;
82 static int sig = SIGINT; /* default */
83 static CtlCommand ctl_command = NO_COMMAND;
84 static char *pg_data = NULL;
85 static char *pg_config = NULL;
86 static char *pgdata_opt = NULL;
87 static char *post_opts = NULL;
88 static const char *progname;
89 static char *log_file = NULL;
90 static char *exec_path = NULL;
91 static char *event_source = NULL;
92 static char *register_servicename = "PostgreSQL"; /* FIXME: + version ID? */
93 static char *register_username = NULL;
94 static char *register_password = NULL;
95 static char *argv0 = NULL;
96 static bool allow_core_files = false;
97 static time_t start_time;
99 static char postopts_file[MAXPGPATH];
100 static char version_file[MAXPGPATH];
101 static char pid_file[MAXPGPATH];
102 static char backup_file[MAXPGPATH];
103 static char promote_file[MAXPGPATH];
104 static char logrotate_file[MAXPGPATH];
106 static volatile pgpid_t postmasterPID = -1;
108 #ifdef WIN32
109 static DWORD pgctl_start_type = SERVICE_AUTO_START;
110 static SERVICE_STATUS status;
111 static SERVICE_STATUS_HANDLE hStatus = (SERVICE_STATUS_HANDLE) 0;
112 static HANDLE shutdownHandles[2];
114 #define shutdownEvent shutdownHandles[0]
115 #define postmasterProcess shutdownHandles[1]
116 #endif
119 static void write_stderr(const char *fmt,...) pg_attribute_printf(1, 2);
120 static void do_advice(void);
121 static void do_help(void);
122 static void set_mode(char *modeopt);
123 static void set_sig(char *signame);
124 static void do_init(void);
125 static void do_start(void);
126 static void do_stop(void);
127 static void do_restart(void);
128 static void do_reload(void);
129 static void do_status(void);
130 static void do_promote(void);
131 static void do_logrotate(void);
132 static void do_kill(pgpid_t pid);
133 static void print_msg(const char *msg);
134 static void adjust_data_dir(void);
136 #ifdef WIN32
137 #include <versionhelpers.h>
138 static bool pgwin32_IsInstalled(SC_HANDLE);
139 static char *pgwin32_CommandLine(bool);
140 static void pgwin32_doRegister(void);
141 static void pgwin32_doUnregister(void);
142 static void pgwin32_SetServiceStatus(DWORD);
143 static void WINAPI pgwin32_ServiceHandler(DWORD);
144 static void WINAPI pgwin32_ServiceMain(DWORD, LPTSTR *);
145 static void pgwin32_doRunAsService(void);
146 static int CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo, bool as_service);
147 static PTOKEN_PRIVILEGES GetPrivilegesToDelete(HANDLE hToken);
148 #endif
150 static pgpid_t get_pgpid(bool is_status_request);
151 static char **readfile(const char *path, int *numlines);
152 static void free_readfile(char **optlines);
153 static pgpid_t start_postmaster(void);
154 static void read_post_opts(void);
156 static WaitPMResult wait_for_postmaster_start(pgpid_t pm_pid, bool do_checkpoint);
157 static bool wait_for_postmaster_stop(void);
158 static bool wait_for_postmaster_promote(void);
159 static bool postmaster_is_alive(pid_t pid);
161 #if defined(HAVE_GETRLIMIT)
162 static void unlimit_core_size(void);
163 #endif
165 static DBState get_control_dbstate(void);
168 #ifdef WIN32
169 static void
170 write_eventlog(int level, const char *line)
172 static HANDLE evtHandle = INVALID_HANDLE_VALUE;
174 if (silent_mode && level == EVENTLOG_INFORMATION_TYPE)
175 return;
177 if (evtHandle == INVALID_HANDLE_VALUE)
179 evtHandle = RegisterEventSource(NULL,
180 event_source ? event_source : DEFAULT_EVENT_SOURCE);
181 if (evtHandle == NULL)
183 evtHandle = INVALID_HANDLE_VALUE;
184 return;
188 ReportEvent(evtHandle,
189 level,
191 0, /* All events are Id 0 */
192 NULL,
195 &line,
196 NULL);
198 #endif
201 * Write errors to stderr (or by equal means when stderr is
202 * not available).
204 static void
205 write_stderr(const char *fmt,...)
207 va_list ap;
209 va_start(ap, fmt);
210 #ifndef WIN32
211 /* On Unix, we just fprintf to stderr */
212 vfprintf(stderr, fmt, ap);
213 #else
216 * On Win32, we print to stderr if running on a console, or write to
217 * eventlog if running as a service
219 if (pgwin32_is_service()) /* Running as a service */
221 char errbuf[2048]; /* Arbitrary size? */
223 vsnprintf(errbuf, sizeof(errbuf), fmt, ap);
225 write_eventlog(EVENTLOG_ERROR_TYPE, errbuf);
227 else
228 /* Not running as service, write to stderr */
229 vfprintf(stderr, fmt, ap);
230 #endif
231 va_end(ap);
235 * Given an already-localized string, print it to stdout unless the
236 * user has specified that no messages should be printed.
238 static void
239 print_msg(const char *msg)
241 if (!silent_mode)
243 fputs(msg, stdout);
244 fflush(stdout);
248 static pgpid_t
249 get_pgpid(bool is_status_request)
251 FILE *pidf;
252 long pid;
253 struct stat statbuf;
255 if (stat(pg_data, &statbuf) != 0)
257 if (errno == ENOENT)
258 write_stderr(_("%s: directory \"%s\" does not exist\n"), progname,
259 pg_data);
260 else
261 write_stderr(_("%s: could not access directory \"%s\": %s\n"), progname,
262 pg_data, strerror(errno));
265 * The Linux Standard Base Core Specification 3.1 says this should
266 * return '4, program or service status is unknown'
267 * https://refspecs.linuxbase.org/LSB_3.1.0/LSB-Core-generic/LSB-Core-generic/iniscrptact.html
269 exit(is_status_request ? 4 : 1);
272 if (stat(version_file, &statbuf) != 0 && errno == ENOENT)
274 write_stderr(_("%s: directory \"%s\" is not a database cluster directory\n"),
275 progname, pg_data);
276 exit(is_status_request ? 4 : 1);
279 pidf = fopen(pid_file, "r");
280 if (pidf == NULL)
282 /* No pid file, not an error on startup */
283 if (errno == ENOENT)
284 return 0;
285 else
287 write_stderr(_("%s: could not open PID file \"%s\": %s\n"),
288 progname, pid_file, strerror(errno));
289 exit(1);
292 if (fscanf(pidf, "%ld", &pid) != 1)
294 /* Is the file empty? */
295 if (ftell(pidf) == 0 && feof(pidf))
296 write_stderr(_("%s: the PID file \"%s\" is empty\n"),
297 progname, pid_file);
298 else
299 write_stderr(_("%s: invalid data in PID file \"%s\"\n"),
300 progname, pid_file);
301 exit(1);
303 fclose(pidf);
304 return (pgpid_t) pid;
309 * get the lines from a text file - return NULL if file can't be opened
311 * Trailing newlines are deleted from the lines (this is a change from pre-v10)
313 * *numlines is set to the number of line pointers returned; there is
314 * also an additional NULL pointer after the last real line.
316 static char **
317 readfile(const char *path, int *numlines)
319 int fd;
320 int nlines;
321 char **result;
322 char *buffer;
323 char *linebegin;
324 int i;
325 int n;
326 int len;
327 struct stat statbuf;
329 *numlines = 0; /* in case of failure or empty file */
332 * Slurp the file into memory.
334 * The file can change concurrently, so we read the whole file into memory
335 * with a single read() call. That's not guaranteed to get an atomic
336 * snapshot, but in practice, for a small file, it's close enough for the
337 * current use.
339 fd = open(path, O_RDONLY | PG_BINARY, 0);
340 if (fd < 0)
341 return NULL;
342 if (fstat(fd, &statbuf) < 0)
344 close(fd);
345 return NULL;
347 if (statbuf.st_size == 0)
349 /* empty file */
350 close(fd);
351 result = (char **) pg_malloc(sizeof(char *));
352 *result = NULL;
353 return result;
355 buffer = pg_malloc(statbuf.st_size + 1);
357 len = read(fd, buffer, statbuf.st_size + 1);
358 close(fd);
359 if (len != statbuf.st_size)
361 /* oops, the file size changed between fstat and read */
362 free(buffer);
363 return NULL;
367 * Count newlines. We expect there to be a newline after each full line,
368 * including one at the end of file. If there isn't a newline at the end,
369 * any characters after the last newline will be ignored.
371 nlines = 0;
372 for (i = 0; i < len; i++)
374 if (buffer[i] == '\n')
375 nlines++;
378 /* set up the result buffer */
379 result = (char **) pg_malloc((nlines + 1) * sizeof(char *));
380 *numlines = nlines;
382 /* now split the buffer into lines */
383 linebegin = buffer;
384 n = 0;
385 for (i = 0; i < len; i++)
387 if (buffer[i] == '\n')
389 int slen = &buffer[i] - linebegin;
390 char *linebuf = pg_malloc(slen + 1);
392 memcpy(linebuf, linebegin, slen);
393 /* we already dropped the \n, but get rid of any \r too */
394 if (slen > 0 && linebuf[slen - 1] == '\r')
395 slen--;
396 linebuf[slen] = '\0';
397 result[n++] = linebuf;
398 linebegin = &buffer[i + 1];
401 result[n] = NULL;
403 free(buffer);
405 return result;
410 * Free memory allocated for optlines through readfile()
412 static void
413 free_readfile(char **optlines)
415 char *curr_line = NULL;
416 int i = 0;
418 if (!optlines)
419 return;
421 while ((curr_line = optlines[i++]))
422 free(curr_line);
424 free(optlines);
428 * start/test/stop routines
432 * Start the postmaster and return its PID.
434 * Currently, on Windows what we return is the PID of the shell process
435 * that launched the postmaster (and, we trust, is waiting for it to exit).
436 * So the PID is usable for "is the postmaster still running" checks,
437 * but cannot be compared directly to postmaster.pid.
439 * On Windows, we also save aside a handle to the shell process in
440 * "postmasterProcess", which the caller should close when done with it.
442 static pgpid_t
443 start_postmaster(void)
445 char *cmd;
447 #ifndef WIN32
448 pgpid_t pm_pid;
450 /* Flush stdio channels just before fork, to avoid double-output problems */
451 fflush(NULL);
453 #ifdef EXEC_BACKEND
454 pg_disable_aslr();
455 #endif
457 pm_pid = fork();
458 if (pm_pid < 0)
460 /* fork failed */
461 write_stderr(_("%s: could not start server: %s\n"),
462 progname, strerror(errno));
463 exit(1);
465 if (pm_pid > 0)
467 /* fork succeeded, in parent */
468 return pm_pid;
471 /* fork succeeded, in child */
474 * If possible, detach the postmaster process from the launching process
475 * group and make it a group leader, so that it doesn't get signaled along
476 * with the current group that launched it.
478 #ifdef HAVE_SETSID
479 if (setsid() < 0)
481 write_stderr(_("%s: could not start server due to setsid() failure: %s\n"),
482 progname, strerror(errno));
483 exit(1);
485 #endif
488 * Since there might be quotes to handle here, it is easier simply to pass
489 * everything to a shell to process them. Use exec so that the postmaster
490 * has the same PID as the current child process.
492 if (log_file != NULL)
493 cmd = psprintf("exec \"%s\" %s%s < \"%s\" >> \"%s\" 2>&1",
494 exec_path, pgdata_opt, post_opts,
495 DEVNULL, log_file);
496 else
497 cmd = psprintf("exec \"%s\" %s%s < \"%s\" 2>&1",
498 exec_path, pgdata_opt, post_opts, DEVNULL);
500 (void) execl("/bin/sh", "/bin/sh", "-c", cmd, (char *) NULL);
502 /* exec failed */
503 write_stderr(_("%s: could not start server: %s\n"),
504 progname, strerror(errno));
505 exit(1);
507 return 0; /* keep dumb compilers quiet */
509 #else /* WIN32 */
512 * As with the Unix case, it's easiest to use the shell (CMD.EXE) to
513 * handle redirection etc. Unfortunately CMD.EXE lacks any equivalent of
514 * "exec", so we don't get to find out the postmaster's PID immediately.
516 PROCESS_INFORMATION pi;
517 const char *comspec;
519 /* Find CMD.EXE location using COMSPEC, if it's set */
520 comspec = getenv("COMSPEC");
521 if (comspec == NULL)
522 comspec = "CMD";
524 if (log_file != NULL)
527 * First, open the log file if it exists. The idea is that if the
528 * file is still locked by a previous postmaster run, we'll wait until
529 * it comes free, instead of failing with ERROR_SHARING_VIOLATION.
530 * (It'd be better to open the file in a sharing-friendly mode, but we
531 * can't use CMD.EXE to do that, so work around it. Note that the
532 * previous postmaster will still have the file open for a short time
533 * after removing postmaster.pid.)
535 * If the log file doesn't exist, we *must not* create it here. If we
536 * were launched with higher privileges than the restricted process
537 * will have, the log file might end up with permissions settings that
538 * prevent the postmaster from writing on it.
540 int fd = open(log_file, O_RDWR, 0);
542 if (fd == -1)
545 * ENOENT is expectable since we didn't use O_CREAT. Otherwise
546 * complain. We could just fall through and let CMD.EXE report
547 * the problem, but its error reporting is pretty miserable.
549 if (errno != ENOENT)
551 write_stderr(_("%s: could not open log file \"%s\": %s\n"),
552 progname, log_file, strerror(errno));
553 exit(1);
556 else
557 close(fd);
559 cmd = psprintf("\"%s\" /C \"\"%s\" %s%s < \"%s\" >> \"%s\" 2>&1\"",
560 comspec, exec_path, pgdata_opt, post_opts, DEVNULL, log_file);
562 else
563 cmd = psprintf("\"%s\" /C \"\"%s\" %s%s < \"%s\" 2>&1\"",
564 comspec, exec_path, pgdata_opt, post_opts, DEVNULL);
566 if (!CreateRestrictedProcess(cmd, &pi, false))
568 write_stderr(_("%s: could not start server: error code %lu\n"),
569 progname, (unsigned long) GetLastError());
570 exit(1);
572 /* Don't close command process handle here; caller must do so */
573 postmasterProcess = pi.hProcess;
574 CloseHandle(pi.hThread);
575 return pi.dwProcessId; /* Shell's PID, not postmaster's! */
576 #endif /* WIN32 */
582 * Wait for the postmaster to become ready.
584 * On Unix, pm_pid is the PID of the just-launched postmaster. On Windows,
585 * it may be the PID of an ancestor shell process, so we can't check the
586 * contents of postmaster.pid quite as carefully.
588 * On Windows, the static variable postmasterProcess is an implicit argument
589 * to this routine; it contains a handle to the postmaster process or an
590 * ancestor shell process thereof.
592 * Note that the checkpoint parameter enables a Windows service control
593 * manager checkpoint, it's got nothing to do with database checkpoints!!
595 static WaitPMResult
596 wait_for_postmaster_start(pgpid_t pm_pid, bool do_checkpoint)
598 int i;
600 for (i = 0; i < wait_seconds * WAITS_PER_SEC; i++)
602 char **optlines;
603 int numlines;
606 * Try to read the postmaster.pid file. If it's not valid, or if the
607 * status line isn't there yet, just keep waiting.
609 if ((optlines = readfile(pid_file, &numlines)) != NULL &&
610 numlines >= LOCK_FILE_LINE_PM_STATUS)
612 /* File is complete enough for us, parse it */
613 pgpid_t pmpid;
614 time_t pmstart;
617 * Make sanity checks. If it's for the wrong PID, or the recorded
618 * start time is before pg_ctl started, then either we are looking
619 * at the wrong data directory, or this is a pre-existing pidfile
620 * that hasn't (yet?) been overwritten by our child postmaster.
621 * Allow 2 seconds slop for possible cross-process clock skew.
623 pmpid = atol(optlines[LOCK_FILE_LINE_PID - 1]);
624 pmstart = atol(optlines[LOCK_FILE_LINE_START_TIME - 1]);
625 if (pmstart >= start_time - 2 &&
626 #ifndef WIN32
627 pmpid == pm_pid
628 #else
629 /* Windows can only reject standalone-backend PIDs */
630 pmpid > 0
631 #endif
635 * OK, seems to be a valid pidfile from our child. Check the
636 * status line (this assumes a v10 or later server).
638 char *pmstatus = optlines[LOCK_FILE_LINE_PM_STATUS - 1];
640 if (strcmp(pmstatus, PM_STATUS_READY) == 0 ||
641 strcmp(pmstatus, PM_STATUS_STANDBY) == 0)
643 /* postmaster is done starting up */
644 free_readfile(optlines);
645 return POSTMASTER_READY;
651 * Free the results of readfile.
653 * This is safe to call even if optlines is NULL.
655 free_readfile(optlines);
658 * Check whether the child postmaster process is still alive. This
659 * lets us exit early if the postmaster fails during startup.
661 * On Windows, we may be checking the postmaster's parent shell, but
662 * that's fine for this purpose.
664 #ifndef WIN32
666 int exitstatus;
668 if (waitpid((pid_t) pm_pid, &exitstatus, WNOHANG) == (pid_t) pm_pid)
669 return POSTMASTER_FAILED;
671 #else
672 if (WaitForSingleObject(postmasterProcess, 0) == WAIT_OBJECT_0)
673 return POSTMASTER_FAILED;
674 #endif
676 /* Startup still in process; wait, printing a dot once per second */
677 if (i % WAITS_PER_SEC == 0)
679 #ifdef WIN32
680 if (do_checkpoint)
683 * Increment the wait hint by 6 secs (connection timeout +
684 * sleep). We must do this to indicate to the SCM that our
685 * startup time is changing, otherwise it'll usually send a
686 * stop signal after 20 seconds, despite incrementing the
687 * checkpoint counter.
689 status.dwWaitHint += 6000;
690 status.dwCheckPoint++;
691 SetServiceStatus(hStatus, (LPSERVICE_STATUS) &status);
693 else
694 #endif
695 print_msg(".");
698 pg_usleep(USEC_PER_SEC / WAITS_PER_SEC);
701 /* out of patience; report that postmaster is still starting up */
702 return POSTMASTER_STILL_STARTING;
707 * Wait for the postmaster to stop.
709 * Returns true if the postmaster stopped cleanly (i.e., removed its pidfile).
710 * Returns false if the postmaster dies uncleanly, or if we time out.
712 static bool
713 wait_for_postmaster_stop(void)
715 int cnt;
717 for (cnt = 0; cnt < wait_seconds * WAITS_PER_SEC; cnt++)
719 pgpid_t pid;
721 if ((pid = get_pgpid(false)) == 0)
722 return true; /* pid file is gone */
724 if (kill((pid_t) pid, 0) != 0)
727 * Postmaster seems to have died. Check the pid file once more to
728 * avoid a race condition, but give up waiting.
730 if (get_pgpid(false) == 0)
731 return true; /* pid file is gone */
732 return false; /* postmaster died untimely */
735 if (cnt % WAITS_PER_SEC == 0)
736 print_msg(".");
737 pg_usleep(USEC_PER_SEC / WAITS_PER_SEC);
739 return false; /* timeout reached */
744 * Wait for the postmaster to promote.
746 * Returns true on success, else false.
747 * To avoid waiting uselessly, we check for postmaster death here too.
749 static bool
750 wait_for_postmaster_promote(void)
752 int cnt;
754 for (cnt = 0; cnt < wait_seconds * WAITS_PER_SEC; cnt++)
756 pgpid_t pid;
757 DBState state;
759 if ((pid = get_pgpid(false)) == 0)
760 return false; /* pid file is gone */
761 if (kill((pid_t) pid, 0) != 0)
762 return false; /* postmaster died */
764 state = get_control_dbstate();
765 if (state == DB_IN_PRODUCTION)
766 return true; /* successful promotion */
768 if (cnt % WAITS_PER_SEC == 0)
769 print_msg(".");
770 pg_usleep(USEC_PER_SEC / WAITS_PER_SEC);
772 return false; /* timeout reached */
776 #if defined(HAVE_GETRLIMIT)
777 static void
778 unlimit_core_size(void)
780 struct rlimit lim;
782 getrlimit(RLIMIT_CORE, &lim);
783 if (lim.rlim_max == 0)
785 write_stderr(_("%s: cannot set core file size limit; disallowed by hard limit\n"),
786 progname);
787 return;
789 else if (lim.rlim_max == RLIM_INFINITY || lim.rlim_cur < lim.rlim_max)
791 lim.rlim_cur = lim.rlim_max;
792 setrlimit(RLIMIT_CORE, &lim);
795 #endif
797 static void
798 read_post_opts(void)
800 if (post_opts == NULL)
802 post_opts = ""; /* default */
803 if (ctl_command == RESTART_COMMAND)
805 char **optlines;
806 int numlines;
808 optlines = readfile(postopts_file, &numlines);
809 if (optlines == NULL)
811 write_stderr(_("%s: could not read file \"%s\"\n"), progname, postopts_file);
812 exit(1);
814 else if (numlines != 1)
816 write_stderr(_("%s: option file \"%s\" must have exactly one line\n"),
817 progname, postopts_file);
818 exit(1);
820 else
822 char *optline;
823 char *arg1;
825 optline = optlines[0];
828 * Are we at the first option, as defined by space and
829 * double-quote?
831 if ((arg1 = strstr(optline, " \"")) != NULL)
833 *arg1 = '\0'; /* terminate so we get only program name */
834 post_opts = pg_strdup(arg1 + 1); /* point past whitespace */
836 if (exec_path == NULL)
837 exec_path = pg_strdup(optline);
840 /* Free the results of readfile. */
841 free_readfile(optlines);
847 * SIGINT signal handler used while waiting for postmaster to start up.
848 * Forwards the SIGINT to the postmaster process, asking it to shut down,
849 * before terminating pg_ctl itself. This way, if the user hits CTRL-C while
850 * waiting for the server to start up, the server launch is aborted.
852 static void
853 trap_sigint_during_startup(SIGNAL_ARGS)
855 if (postmasterPID != -1)
857 if (kill(postmasterPID, SIGINT) != 0)
858 write_stderr(_("%s: could not send stop signal (PID: %ld): %s\n"),
859 progname, (pgpid_t) postmasterPID, strerror(errno));
863 * Clear the signal handler, and send the signal again, to terminate the
864 * process as normal.
866 pqsignal(postgres_signal_arg, SIG_DFL);
867 raise(postgres_signal_arg);
870 static char *
871 find_other_exec_or_die(const char *argv0, const char *target, const char *versionstr)
873 int ret;
874 char *found_path;
876 found_path = pg_malloc(MAXPGPATH);
878 if ((ret = find_other_exec(argv0, target, versionstr, found_path)) < 0)
880 char full_path[MAXPGPATH];
882 if (find_my_exec(argv0, full_path) < 0)
883 strlcpy(full_path, progname, sizeof(full_path));
885 if (ret == -1)
886 write_stderr(_("program \"%s\" is needed by %s but was not found in the same directory as \"%s\"\n"),
887 target, progname, full_path);
888 else
889 write_stderr(_("program \"%s\" was found by \"%s\" but was not the same version as %s\n"),
890 target, full_path, progname);
891 exit(1);
894 return found_path;
897 static void
898 do_init(void)
900 char *cmd;
902 if (exec_path == NULL)
903 exec_path = find_other_exec_or_die(argv0, "initdb", "initdb (PostgreSQL) " PG_VERSION "\n");
905 if (pgdata_opt == NULL)
906 pgdata_opt = "";
908 if (post_opts == NULL)
909 post_opts = "";
911 if (!silent_mode)
912 cmd = psprintf("\"%s\" %s%s",
913 exec_path, pgdata_opt, post_opts);
914 else
915 cmd = psprintf("\"%s\" %s%s > \"%s\"",
916 exec_path, pgdata_opt, post_opts, DEVNULL);
918 fflush(NULL);
919 if (system(cmd) != 0)
921 write_stderr(_("%s: database system initialization failed\n"), progname);
922 exit(1);
926 static void
927 do_start(void)
929 pgpid_t old_pid = 0;
930 pgpid_t pm_pid;
932 if (ctl_command != RESTART_COMMAND)
934 old_pid = get_pgpid(false);
935 if (old_pid != 0)
936 write_stderr(_("%s: another server might be running; "
937 "trying to start server anyway\n"),
938 progname);
941 read_post_opts();
943 /* No -D or -D already added during server start */
944 if (ctl_command == RESTART_COMMAND || pgdata_opt == NULL)
945 pgdata_opt = "";
947 if (exec_path == NULL)
948 exec_path = find_other_exec_or_die(argv0, "postgres", PG_BACKEND_VERSIONSTR);
950 #if defined(HAVE_GETRLIMIT)
951 if (allow_core_files)
952 unlimit_core_size();
953 #endif
956 * If possible, tell the postmaster our parent shell's PID (see the
957 * comments in CreateLockFile() for motivation). Windows hasn't got
958 * getppid() unfortunately.
960 #ifndef WIN32
962 char env_var[32];
964 snprintf(env_var, sizeof(env_var), "%d", (int) getppid());
965 setenv("PG_GRANDPARENT_PID", env_var, 1);
967 #endif
969 pm_pid = start_postmaster();
971 if (do_wait)
974 * If the user interrupts the startup (e.g. with CTRL-C), we'd like to
975 * abort the server launch. Install a signal handler that will
976 * forward SIGINT to the postmaster process, while we wait.
978 * (We don't bother to reset the signal handler after the launch, as
979 * we're about to exit, anyway.)
981 postmasterPID = pm_pid;
982 pqsignal(SIGINT, trap_sigint_during_startup);
984 print_msg(_("waiting for server to start..."));
986 switch (wait_for_postmaster_start(pm_pid, false))
988 case POSTMASTER_READY:
989 print_msg(_(" done\n"));
990 print_msg(_("server started\n"));
991 break;
992 case POSTMASTER_STILL_STARTING:
993 print_msg(_(" stopped waiting\n"));
994 write_stderr(_("%s: server did not start in time\n"),
995 progname);
996 exit(1);
997 break;
998 case POSTMASTER_FAILED:
999 print_msg(_(" stopped waiting\n"));
1000 write_stderr(_("%s: could not start server\n"
1001 "Examine the log output.\n"),
1002 progname);
1003 exit(1);
1004 break;
1007 else
1008 print_msg(_("server starting\n"));
1010 #ifdef WIN32
1011 /* Now we don't need the handle to the shell process anymore */
1012 CloseHandle(postmasterProcess);
1013 postmasterProcess = INVALID_HANDLE_VALUE;
1014 #endif
1018 static void
1019 do_stop(void)
1021 pgpid_t pid;
1023 pid = get_pgpid(false);
1025 if (pid == 0) /* no pid file */
1027 write_stderr(_("%s: PID file \"%s\" does not exist\n"), progname, pid_file);
1028 write_stderr(_("Is server running?\n"));
1029 exit(1);
1031 else if (pid < 0) /* standalone backend, not postmaster */
1033 pid = -pid;
1034 write_stderr(_("%s: cannot stop server; "
1035 "single-user server is running (PID: %ld)\n"),
1036 progname, pid);
1037 exit(1);
1040 if (kill((pid_t) pid, sig) != 0)
1042 write_stderr(_("%s: could not send stop signal (PID: %ld): %s\n"), progname, pid,
1043 strerror(errno));
1044 exit(1);
1047 if (!do_wait)
1049 print_msg(_("server shutting down\n"));
1050 return;
1052 else
1054 print_msg(_("waiting for server to shut down..."));
1056 if (!wait_for_postmaster_stop())
1058 print_msg(_(" failed\n"));
1060 write_stderr(_("%s: server does not shut down\n"), progname);
1061 if (shutdown_mode == SMART_MODE)
1062 write_stderr(_("HINT: The \"-m fast\" option immediately disconnects sessions rather than\n"
1063 "waiting for session-initiated disconnection.\n"));
1064 exit(1);
1066 print_msg(_(" done\n"));
1068 print_msg(_("server stopped\n"));
1074 * restart/reload routines
1077 static void
1078 do_restart(void)
1080 pgpid_t pid;
1082 pid = get_pgpid(false);
1084 if (pid == 0) /* no pid file */
1086 write_stderr(_("%s: PID file \"%s\" does not exist\n"),
1087 progname, pid_file);
1088 write_stderr(_("Is server running?\n"));
1089 write_stderr(_("trying to start server anyway\n"));
1090 do_start();
1091 return;
1093 else if (pid < 0) /* standalone backend, not postmaster */
1095 pid = -pid;
1096 if (postmaster_is_alive((pid_t) pid))
1098 write_stderr(_("%s: cannot restart server; "
1099 "single-user server is running (PID: %ld)\n"),
1100 progname, pid);
1101 write_stderr(_("Please terminate the single-user server and try again.\n"));
1102 exit(1);
1106 if (postmaster_is_alive((pid_t) pid))
1108 if (kill((pid_t) pid, sig) != 0)
1110 write_stderr(_("%s: could not send stop signal (PID: %ld): %s\n"), progname, pid,
1111 strerror(errno));
1112 exit(1);
1115 print_msg(_("waiting for server to shut down..."));
1117 /* always wait for restart */
1118 if (!wait_for_postmaster_stop())
1120 print_msg(_(" failed\n"));
1122 write_stderr(_("%s: server does not shut down\n"), progname);
1123 if (shutdown_mode == SMART_MODE)
1124 write_stderr(_("HINT: The \"-m fast\" option immediately disconnects sessions rather than\n"
1125 "waiting for session-initiated disconnection.\n"));
1126 exit(1);
1129 print_msg(_(" done\n"));
1130 print_msg(_("server stopped\n"));
1132 else
1134 write_stderr(_("%s: old server process (PID: %ld) seems to be gone\n"),
1135 progname, pid);
1136 write_stderr(_("starting server anyway\n"));
1139 do_start();
1142 static void
1143 do_reload(void)
1145 pgpid_t pid;
1147 pid = get_pgpid(false);
1148 if (pid == 0) /* no pid file */
1150 write_stderr(_("%s: PID file \"%s\" does not exist\n"), progname, pid_file);
1151 write_stderr(_("Is server running?\n"));
1152 exit(1);
1154 else if (pid < 0) /* standalone backend, not postmaster */
1156 pid = -pid;
1157 write_stderr(_("%s: cannot reload server; "
1158 "single-user server is running (PID: %ld)\n"),
1159 progname, pid);
1160 write_stderr(_("Please terminate the single-user server and try again.\n"));
1161 exit(1);
1164 if (kill((pid_t) pid, sig) != 0)
1166 write_stderr(_("%s: could not send reload signal (PID: %ld): %s\n"),
1167 progname, pid, strerror(errno));
1168 exit(1);
1171 print_msg(_("server signaled\n"));
1176 * promote
1179 static void
1180 do_promote(void)
1182 FILE *prmfile;
1183 pgpid_t pid;
1185 pid = get_pgpid(false);
1187 if (pid == 0) /* no pid file */
1189 write_stderr(_("%s: PID file \"%s\" does not exist\n"), progname, pid_file);
1190 write_stderr(_("Is server running?\n"));
1191 exit(1);
1193 else if (pid < 0) /* standalone backend, not postmaster */
1195 pid = -pid;
1196 write_stderr(_("%s: cannot promote server; "
1197 "single-user server is running (PID: %ld)\n"),
1198 progname, pid);
1199 exit(1);
1202 if (get_control_dbstate() != DB_IN_ARCHIVE_RECOVERY)
1204 write_stderr(_("%s: cannot promote server; "
1205 "server is not in standby mode\n"),
1206 progname);
1207 exit(1);
1210 snprintf(promote_file, MAXPGPATH, "%s/promote", pg_data);
1212 if ((prmfile = fopen(promote_file, "w")) == NULL)
1214 write_stderr(_("%s: could not create promote signal file \"%s\": %s\n"),
1215 progname, promote_file, strerror(errno));
1216 exit(1);
1218 if (fclose(prmfile))
1220 write_stderr(_("%s: could not write promote signal file \"%s\": %s\n"),
1221 progname, promote_file, strerror(errno));
1222 exit(1);
1225 sig = SIGUSR1;
1226 if (kill((pid_t) pid, sig) != 0)
1228 write_stderr(_("%s: could not send promote signal (PID: %ld): %s\n"),
1229 progname, pid, strerror(errno));
1230 if (unlink(promote_file) != 0)
1231 write_stderr(_("%s: could not remove promote signal file \"%s\": %s\n"),
1232 progname, promote_file, strerror(errno));
1233 exit(1);
1236 if (do_wait)
1238 print_msg(_("waiting for server to promote..."));
1239 if (wait_for_postmaster_promote())
1241 print_msg(_(" done\n"));
1242 print_msg(_("server promoted\n"));
1244 else
1246 print_msg(_(" stopped waiting\n"));
1247 write_stderr(_("%s: server did not promote in time\n"),
1248 progname);
1249 exit(1);
1252 else
1253 print_msg(_("server promoting\n"));
1257 * log rotate
1260 static void
1261 do_logrotate(void)
1263 FILE *logrotatefile;
1264 pgpid_t pid;
1266 pid = get_pgpid(false);
1268 if (pid == 0) /* no pid file */
1270 write_stderr(_("%s: PID file \"%s\" does not exist\n"), progname, pid_file);
1271 write_stderr(_("Is server running?\n"));
1272 exit(1);
1274 else if (pid < 0) /* standalone backend, not postmaster */
1276 pid = -pid;
1277 write_stderr(_("%s: cannot rotate log file; "
1278 "single-user server is running (PID: %ld)\n"),
1279 progname, pid);
1280 exit(1);
1283 snprintf(logrotate_file, MAXPGPATH, "%s/logrotate", pg_data);
1285 if ((logrotatefile = fopen(logrotate_file, "w")) == NULL)
1287 write_stderr(_("%s: could not create log rotation signal file \"%s\": %s\n"),
1288 progname, logrotate_file, strerror(errno));
1289 exit(1);
1291 if (fclose(logrotatefile))
1293 write_stderr(_("%s: could not write log rotation signal file \"%s\": %s\n"),
1294 progname, logrotate_file, strerror(errno));
1295 exit(1);
1298 sig = SIGUSR1;
1299 if (kill((pid_t) pid, sig) != 0)
1301 write_stderr(_("%s: could not send log rotation signal (PID: %ld): %s\n"),
1302 progname, pid, strerror(errno));
1303 if (unlink(logrotate_file) != 0)
1304 write_stderr(_("%s: could not remove log rotation signal file \"%s\": %s\n"),
1305 progname, logrotate_file, strerror(errno));
1306 exit(1);
1309 print_msg(_("server signaled to rotate log file\n"));
1314 * utility routines
1317 static bool
1318 postmaster_is_alive(pid_t pid)
1321 * Test to see if the process is still there. Note that we do not
1322 * consider an EPERM failure to mean that the process is still there;
1323 * EPERM must mean that the given PID belongs to some other userid, and
1324 * considering the permissions on $PGDATA, that means it's not the
1325 * postmaster we are after.
1327 * Don't believe that our own PID or parent shell's PID is the postmaster,
1328 * either. (Windows hasn't got getppid(), though.)
1330 if (pid == getpid())
1331 return false;
1332 #ifndef WIN32
1333 if (pid == getppid())
1334 return false;
1335 #endif
1336 if (kill(pid, 0) == 0)
1337 return true;
1338 return false;
1341 static void
1342 do_status(void)
1344 pgpid_t pid;
1346 pid = get_pgpid(true);
1347 /* Is there a pid file? */
1348 if (pid != 0)
1350 /* standalone backend? */
1351 if (pid < 0)
1353 pid = -pid;
1354 if (postmaster_is_alive((pid_t) pid))
1356 printf(_("%s: single-user server is running (PID: %ld)\n"),
1357 progname, pid);
1358 return;
1361 else
1362 /* must be a postmaster */
1364 if (postmaster_is_alive((pid_t) pid))
1366 char **optlines;
1367 char **curr_line;
1368 int numlines;
1370 printf(_("%s: server is running (PID: %ld)\n"),
1371 progname, pid);
1373 optlines = readfile(postopts_file, &numlines);
1374 if (optlines != NULL)
1376 for (curr_line = optlines; *curr_line != NULL; curr_line++)
1377 puts(*curr_line);
1379 /* Free the results of readfile */
1380 free_readfile(optlines);
1382 return;
1386 printf(_("%s: no server running\n"), progname);
1389 * The Linux Standard Base Core Specification 3.1 says this should return
1390 * '3, program is not running'
1391 * https://refspecs.linuxbase.org/LSB_3.1.0/LSB-Core-generic/LSB-Core-generic/iniscrptact.html
1393 exit(3);
1398 static void
1399 do_kill(pgpid_t pid)
1401 if (kill((pid_t) pid, sig) != 0)
1403 write_stderr(_("%s: could not send signal %d (PID: %ld): %s\n"),
1404 progname, sig, pid, strerror(errno));
1405 exit(1);
1409 #ifdef WIN32
1411 static bool
1412 pgwin32_IsInstalled(SC_HANDLE hSCM)
1414 SC_HANDLE hService = OpenService(hSCM, register_servicename, SERVICE_QUERY_CONFIG);
1415 bool bResult = (hService != NULL);
1417 if (bResult)
1418 CloseServiceHandle(hService);
1419 return bResult;
1422 static char *
1423 pgwin32_CommandLine(bool registration)
1425 PQExpBuffer cmdLine = createPQExpBuffer();
1426 char cmdPath[MAXPGPATH];
1427 int ret;
1429 if (registration)
1431 ret = find_my_exec(argv0, cmdPath);
1432 if (ret != 0)
1434 write_stderr(_("%s: could not find own program executable\n"), progname);
1435 exit(1);
1438 else
1440 ret = find_other_exec(argv0, "postgres", PG_BACKEND_VERSIONSTR,
1441 cmdPath);
1442 if (ret != 0)
1444 write_stderr(_("%s: could not find postgres program executable\n"), progname);
1445 exit(1);
1449 /* if path does not end in .exe, append it */
1450 if (strlen(cmdPath) < 4 ||
1451 pg_strcasecmp(cmdPath + strlen(cmdPath) - 4, ".exe") != 0)
1452 snprintf(cmdPath + strlen(cmdPath), sizeof(cmdPath) - strlen(cmdPath),
1453 ".exe");
1455 /* use backslashes in path to avoid problems with some third-party tools */
1456 make_native_path(cmdPath);
1458 /* be sure to double-quote the executable's name in the command */
1459 appendPQExpBuffer(cmdLine, "\"%s\"", cmdPath);
1461 /* append assorted switches to the command line, as needed */
1463 if (registration)
1464 appendPQExpBuffer(cmdLine, " runservice -N \"%s\"",
1465 register_servicename);
1467 if (pg_config)
1469 /* We need the -D path to be absolute */
1470 char *dataDir;
1472 if ((dataDir = make_absolute_path(pg_config)) == NULL)
1474 /* make_absolute_path already reported the error */
1475 exit(1);
1477 make_native_path(dataDir);
1478 appendPQExpBuffer(cmdLine, " -D \"%s\"", dataDir);
1479 free(dataDir);
1482 if (registration && event_source != NULL)
1483 appendPQExpBuffer(cmdLine, " -e \"%s\"", event_source);
1485 if (registration && do_wait)
1486 appendPQExpBufferStr(cmdLine, " -w");
1488 /* Don't propagate a value from an environment variable. */
1489 if (registration && wait_seconds_arg && wait_seconds != DEFAULT_WAIT)
1490 appendPQExpBuffer(cmdLine, " -t %d", wait_seconds);
1492 if (registration && silent_mode)
1493 appendPQExpBufferStr(cmdLine, " -s");
1495 if (post_opts)
1497 if (registration)
1498 appendPQExpBuffer(cmdLine, " -o \"%s\"", post_opts);
1499 else
1500 appendPQExpBuffer(cmdLine, " %s", post_opts);
1503 return cmdLine->data;
1506 static void
1507 pgwin32_doRegister(void)
1509 SC_HANDLE hService;
1510 SC_HANDLE hSCM = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
1512 if (hSCM == NULL)
1514 write_stderr(_("%s: could not open service manager\n"), progname);
1515 exit(1);
1517 if (pgwin32_IsInstalled(hSCM))
1519 CloseServiceHandle(hSCM);
1520 write_stderr(_("%s: service \"%s\" already registered\n"), progname, register_servicename);
1521 exit(1);
1524 if ((hService = CreateService(hSCM, register_servicename, register_servicename,
1525 SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS,
1526 pgctl_start_type, SERVICE_ERROR_NORMAL,
1527 pgwin32_CommandLine(true),
1528 NULL, NULL, "RPCSS\0", register_username, register_password)) == NULL)
1530 CloseServiceHandle(hSCM);
1531 write_stderr(_("%s: could not register service \"%s\": error code %lu\n"),
1532 progname, register_servicename,
1533 (unsigned long) GetLastError());
1534 exit(1);
1536 CloseServiceHandle(hService);
1537 CloseServiceHandle(hSCM);
1540 static void
1541 pgwin32_doUnregister(void)
1543 SC_HANDLE hService;
1544 SC_HANDLE hSCM = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
1546 if (hSCM == NULL)
1548 write_stderr(_("%s: could not open service manager\n"), progname);
1549 exit(1);
1551 if (!pgwin32_IsInstalled(hSCM))
1553 CloseServiceHandle(hSCM);
1554 write_stderr(_("%s: service \"%s\" not registered\n"), progname, register_servicename);
1555 exit(1);
1558 if ((hService = OpenService(hSCM, register_servicename, DELETE)) == NULL)
1560 CloseServiceHandle(hSCM);
1561 write_stderr(_("%s: could not open service \"%s\": error code %lu\n"),
1562 progname, register_servicename,
1563 (unsigned long) GetLastError());
1564 exit(1);
1566 if (!DeleteService(hService))
1568 CloseServiceHandle(hService);
1569 CloseServiceHandle(hSCM);
1570 write_stderr(_("%s: could not unregister service \"%s\": error code %lu\n"),
1571 progname, register_servicename,
1572 (unsigned long) GetLastError());
1573 exit(1);
1575 CloseServiceHandle(hService);
1576 CloseServiceHandle(hSCM);
1579 static void
1580 pgwin32_SetServiceStatus(DWORD currentState)
1582 status.dwCurrentState = currentState;
1583 SetServiceStatus(hStatus, (LPSERVICE_STATUS) &status);
1586 static void WINAPI
1587 pgwin32_ServiceHandler(DWORD request)
1589 switch (request)
1591 case SERVICE_CONTROL_STOP:
1592 case SERVICE_CONTROL_SHUTDOWN:
1595 * We only need a short wait hint here as it just needs to wait
1596 * for the next checkpoint. They occur every 5 seconds during
1597 * shutdown
1599 status.dwWaitHint = 10000;
1600 pgwin32_SetServiceStatus(SERVICE_STOP_PENDING);
1601 SetEvent(shutdownEvent);
1602 return;
1604 case SERVICE_CONTROL_PAUSE:
1605 /* Win32 config reloading */
1606 status.dwWaitHint = 5000;
1607 kill(postmasterPID, SIGHUP);
1608 return;
1610 /* FIXME: These could be used to replace other signals etc */
1611 case SERVICE_CONTROL_CONTINUE:
1612 case SERVICE_CONTROL_INTERROGATE:
1613 default:
1614 break;
1618 static void WINAPI
1619 pgwin32_ServiceMain(DWORD argc, LPTSTR *argv)
1621 PROCESS_INFORMATION pi;
1622 DWORD ret;
1624 /* Initialize variables */
1625 status.dwWin32ExitCode = S_OK;
1626 status.dwCheckPoint = 0;
1627 status.dwWaitHint = 60000;
1628 status.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
1629 status.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN | SERVICE_ACCEPT_PAUSE_CONTINUE;
1630 status.dwServiceSpecificExitCode = 0;
1631 status.dwCurrentState = SERVICE_START_PENDING;
1633 memset(&pi, 0, sizeof(pi));
1635 read_post_opts();
1637 /* Register the control request handler */
1638 if ((hStatus = RegisterServiceCtrlHandler(register_servicename, pgwin32_ServiceHandler)) == (SERVICE_STATUS_HANDLE) 0)
1639 return;
1641 if ((shutdownEvent = CreateEvent(NULL, true, false, NULL)) == NULL)
1642 return;
1644 /* Start the postmaster */
1645 pgwin32_SetServiceStatus(SERVICE_START_PENDING);
1646 if (!CreateRestrictedProcess(pgwin32_CommandLine(false), &pi, true))
1648 pgwin32_SetServiceStatus(SERVICE_STOPPED);
1649 return;
1651 postmasterPID = pi.dwProcessId;
1652 postmasterProcess = pi.hProcess;
1653 CloseHandle(pi.hThread);
1655 if (do_wait)
1657 write_eventlog(EVENTLOG_INFORMATION_TYPE, _("Waiting for server startup...\n"));
1658 if (wait_for_postmaster_start(postmasterPID, true) != POSTMASTER_READY)
1660 write_eventlog(EVENTLOG_ERROR_TYPE, _("Timed out waiting for server startup\n"));
1661 pgwin32_SetServiceStatus(SERVICE_STOPPED);
1662 return;
1664 write_eventlog(EVENTLOG_INFORMATION_TYPE, _("Server started and accepting connections\n"));
1667 pgwin32_SetServiceStatus(SERVICE_RUNNING);
1669 /* Wait for quit... */
1670 ret = WaitForMultipleObjects(2, shutdownHandles, FALSE, INFINITE);
1672 pgwin32_SetServiceStatus(SERVICE_STOP_PENDING);
1673 switch (ret)
1675 case WAIT_OBJECT_0: /* shutdown event */
1678 * status.dwCheckPoint can be incremented by
1679 * wait_for_postmaster_start(), so it might not start from 0.
1681 int maxShutdownCheckPoint = status.dwCheckPoint + 12;
1683 kill(postmasterPID, SIGINT);
1686 * Increment the checkpoint and try again. Abort after 12
1687 * checkpoints as the postmaster has probably hung.
1689 while (WaitForSingleObject(postmasterProcess, 5000) == WAIT_TIMEOUT && status.dwCheckPoint < maxShutdownCheckPoint)
1691 status.dwCheckPoint++;
1692 SetServiceStatus(hStatus, (LPSERVICE_STATUS) &status);
1694 break;
1697 case (WAIT_OBJECT_0 + 1): /* postmaster went down */
1698 break;
1700 default:
1701 /* shouldn't get here? */
1702 break;
1705 CloseHandle(shutdownEvent);
1706 CloseHandle(postmasterProcess);
1708 pgwin32_SetServiceStatus(SERVICE_STOPPED);
1711 static void
1712 pgwin32_doRunAsService(void)
1714 SERVICE_TABLE_ENTRY st[] = {{register_servicename, pgwin32_ServiceMain},
1715 {NULL, NULL}};
1717 if (StartServiceCtrlDispatcher(st) == 0)
1719 write_stderr(_("%s: could not start service \"%s\": error code %lu\n"),
1720 progname, register_servicename,
1721 (unsigned long) GetLastError());
1722 exit(1);
1728 * Set up STARTUPINFO for the new process to inherit this process' handles.
1730 * Process started as services appear to have "empty" handles (GetStdHandle()
1731 * returns NULL) rather than invalid ones. But passing down NULL ourselves
1732 * doesn't work, it's interpreted as STARTUPINFO->hStd* not being set. But we
1733 * can pass down INVALID_HANDLE_VALUE - which makes GetStdHandle() in the new
1734 * process (and its child processes!) return INVALID_HANDLE_VALUE. Which
1735 * achieves the goal of postmaster running in a similar environment as pg_ctl.
1737 static void
1738 InheritStdHandles(STARTUPINFO *si)
1740 si->dwFlags |= STARTF_USESTDHANDLES;
1741 si->hStdInput = GetStdHandle(STD_INPUT_HANDLE);
1742 if (si->hStdInput == NULL)
1743 si->hStdInput = INVALID_HANDLE_VALUE;
1744 si->hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
1745 if (si->hStdOutput == NULL)
1746 si->hStdOutput = INVALID_HANDLE_VALUE;
1747 si->hStdError = GetStdHandle(STD_ERROR_HANDLE);
1748 if (si->hStdError == NULL)
1749 si->hStdError = INVALID_HANDLE_VALUE;
1753 * Create a restricted token, a job object sandbox, and execute the specified
1754 * process with it.
1756 * Returns 0 on success, non-zero on failure, same as CreateProcess().
1758 * NOTE! Job object will only work when running as a service, because it's
1759 * automatically destroyed when pg_ctl exits.
1761 static int
1762 CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo, bool as_service)
1764 int r;
1765 BOOL b;
1766 STARTUPINFO si;
1767 HANDLE origToken;
1768 HANDLE restrictedToken;
1769 BOOL inJob;
1770 SID_IDENTIFIER_AUTHORITY NtAuthority = {SECURITY_NT_AUTHORITY};
1771 SID_AND_ATTRIBUTES dropSids[2];
1772 PTOKEN_PRIVILEGES delPrivs;
1774 ZeroMemory(&si, sizeof(si));
1775 si.cb = sizeof(si);
1778 * Set stdin/stdout/stderr handles to be inherited in the child process.
1779 * That allows postmaster and the processes it starts to perform
1780 * additional checks to see if running in a service (otherwise they get
1781 * the default console handles - which point to "somewhere").
1783 InheritStdHandles(&si);
1785 /* Open the current token to use as a base for the restricted one */
1786 if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &origToken))
1789 * Most Windows targets make DWORD a 32-bit unsigned long, but in case
1790 * it doesn't cast DWORD before printing.
1792 write_stderr(_("%s: could not open process token: error code %lu\n"),
1793 progname, (unsigned long) GetLastError());
1794 return 0;
1797 /* Allocate list of SIDs to remove */
1798 ZeroMemory(&dropSids, sizeof(dropSids));
1799 if (!AllocateAndInitializeSid(&NtAuthority, 2,
1800 SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0,
1801 0, &dropSids[0].Sid) ||
1802 !AllocateAndInitializeSid(&NtAuthority, 2,
1803 SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_POWER_USERS, 0, 0, 0, 0, 0,
1804 0, &dropSids[1].Sid))
1806 write_stderr(_("%s: could not allocate SIDs: error code %lu\n"),
1807 progname, (unsigned long) GetLastError());
1808 return 0;
1811 /* Get list of privileges to remove */
1812 delPrivs = GetPrivilegesToDelete(origToken);
1813 if (delPrivs == NULL)
1814 /* Error message already printed */
1815 return 0;
1817 b = CreateRestrictedToken(origToken,
1819 sizeof(dropSids) / sizeof(dropSids[0]),
1820 dropSids,
1821 delPrivs->PrivilegeCount, delPrivs->Privileges,
1822 0, NULL,
1823 &restrictedToken);
1825 free(delPrivs);
1826 FreeSid(dropSids[1].Sid);
1827 FreeSid(dropSids[0].Sid);
1828 CloseHandle(origToken);
1830 if (!b)
1832 write_stderr(_("%s: could not create restricted token: error code %lu\n"),
1833 progname, (unsigned long) GetLastError());
1834 return 0;
1837 AddUserToTokenDacl(restrictedToken);
1838 r = CreateProcessAsUser(restrictedToken, NULL, cmd, NULL, NULL, TRUE, CREATE_SUSPENDED, NULL, NULL, &si, processInfo);
1840 if (IsProcessInJob(processInfo->hProcess, NULL, &inJob))
1842 if (!inJob)
1845 * Job objects are working, and the new process isn't in one, so
1846 * we can create one safely. If any problems show up when setting
1847 * it, we're going to ignore them.
1849 HANDLE job;
1850 char jobname[128];
1852 sprintf(jobname, "PostgreSQL_%lu",
1853 (unsigned long) processInfo->dwProcessId);
1855 job = CreateJobObject(NULL, jobname);
1856 if (job)
1858 JOBOBJECT_BASIC_LIMIT_INFORMATION basicLimit;
1859 JOBOBJECT_BASIC_UI_RESTRICTIONS uiRestrictions;
1860 JOBOBJECT_SECURITY_LIMIT_INFORMATION securityLimit;
1862 ZeroMemory(&basicLimit, sizeof(basicLimit));
1863 ZeroMemory(&uiRestrictions, sizeof(uiRestrictions));
1864 ZeroMemory(&securityLimit, sizeof(securityLimit));
1866 basicLimit.LimitFlags = JOB_OBJECT_LIMIT_DIE_ON_UNHANDLED_EXCEPTION | JOB_OBJECT_LIMIT_PRIORITY_CLASS;
1867 basicLimit.PriorityClass = NORMAL_PRIORITY_CLASS;
1868 SetInformationJobObject(job, JobObjectBasicLimitInformation, &basicLimit, sizeof(basicLimit));
1870 uiRestrictions.UIRestrictionsClass = JOB_OBJECT_UILIMIT_DESKTOP | JOB_OBJECT_UILIMIT_DISPLAYSETTINGS |
1871 JOB_OBJECT_UILIMIT_EXITWINDOWS | JOB_OBJECT_UILIMIT_READCLIPBOARD |
1872 JOB_OBJECT_UILIMIT_SYSTEMPARAMETERS | JOB_OBJECT_UILIMIT_WRITECLIPBOARD;
1874 SetInformationJobObject(job, JobObjectBasicUIRestrictions, &uiRestrictions, sizeof(uiRestrictions));
1876 securityLimit.SecurityLimitFlags = JOB_OBJECT_SECURITY_NO_ADMIN | JOB_OBJECT_SECURITY_ONLY_TOKEN;
1877 securityLimit.JobToken = restrictedToken;
1878 SetInformationJobObject(job, JobObjectSecurityLimitInformation, &securityLimit, sizeof(securityLimit));
1880 AssignProcessToJobObject(job, processInfo->hProcess);
1885 CloseHandle(restrictedToken);
1887 ResumeThread(processInfo->hThread);
1890 * We intentionally don't close the job object handle, because we want the
1891 * object to live on until pg_ctl shuts down.
1893 return r;
1897 * Get a list of privileges to delete from the access token. We delete all privileges
1898 * except SeLockMemoryPrivilege which is needed to use large pages, and
1899 * SeChangeNotifyPrivilege which is enabled by default in DISABLE_MAX_PRIVILEGE.
1901 static PTOKEN_PRIVILEGES
1902 GetPrivilegesToDelete(HANDLE hToken)
1904 int i,
1906 DWORD length;
1907 PTOKEN_PRIVILEGES tokenPrivs;
1908 LUID luidLockPages;
1909 LUID luidChangeNotify;
1911 if (!LookupPrivilegeValue(NULL, SE_LOCK_MEMORY_NAME, &luidLockPages) ||
1912 !LookupPrivilegeValue(NULL, SE_CHANGE_NOTIFY_NAME, &luidChangeNotify))
1914 write_stderr(_("%s: could not get LUIDs for privileges: error code %lu\n"),
1915 progname, (unsigned long) GetLastError());
1916 return NULL;
1919 if (!GetTokenInformation(hToken, TokenPrivileges, NULL, 0, &length) &&
1920 GetLastError() != ERROR_INSUFFICIENT_BUFFER)
1922 write_stderr(_("%s: could not get token information: error code %lu\n"),
1923 progname, (unsigned long) GetLastError());
1924 return NULL;
1927 tokenPrivs = (PTOKEN_PRIVILEGES) pg_malloc_extended(length,
1928 MCXT_ALLOC_NO_OOM);
1929 if (tokenPrivs == NULL)
1931 write_stderr(_("%s: out of memory\n"), progname);
1932 return NULL;
1935 if (!GetTokenInformation(hToken, TokenPrivileges, tokenPrivs, length, &length))
1937 write_stderr(_("%s: could not get token information: error code %lu\n"),
1938 progname, (unsigned long) GetLastError());
1939 free(tokenPrivs);
1940 return NULL;
1943 for (i = 0; i < tokenPrivs->PrivilegeCount; i++)
1945 if (memcmp(&tokenPrivs->Privileges[i].Luid, &luidLockPages, sizeof(LUID)) == 0 ||
1946 memcmp(&tokenPrivs->Privileges[i].Luid, &luidChangeNotify, sizeof(LUID)) == 0)
1948 for (j = i; j < tokenPrivs->PrivilegeCount - 1; j++)
1949 tokenPrivs->Privileges[j] = tokenPrivs->Privileges[j + 1];
1950 tokenPrivs->PrivilegeCount--;
1954 return tokenPrivs;
1956 #endif /* WIN32 */
1958 static void
1959 do_advice(void)
1961 write_stderr(_("Try \"%s --help\" for more information.\n"), progname);
1966 static void
1967 do_help(void)
1969 printf(_("%s is a utility to initialize, start, stop, or control a PostgreSQL server.\n\n"), progname);
1970 printf(_("Usage:\n"));
1971 printf(_(" %s init[db] [-D DATADIR] [-s] [-o OPTIONS]\n"), progname);
1972 printf(_(" %s start [-D DATADIR] [-l FILENAME] [-W] [-t SECS] [-s]\n"
1973 " [-o OPTIONS] [-p PATH] [-c]\n"), progname);
1974 printf(_(" %s stop [-D DATADIR] [-m SHUTDOWN-MODE] [-W] [-t SECS] [-s]\n"), progname);
1975 printf(_(" %s restart [-D DATADIR] [-m SHUTDOWN-MODE] [-W] [-t SECS] [-s]\n"
1976 " [-o OPTIONS] [-c]\n"), progname);
1977 printf(_(" %s reload [-D DATADIR] [-s]\n"), progname);
1978 printf(_(" %s status [-D DATADIR]\n"), progname);
1979 printf(_(" %s promote [-D DATADIR] [-W] [-t SECS] [-s]\n"), progname);
1980 printf(_(" %s logrotate [-D DATADIR] [-s]\n"), progname);
1981 printf(_(" %s kill SIGNALNAME PID\n"), progname);
1982 #ifdef WIN32
1983 printf(_(" %s register [-D DATADIR] [-N SERVICENAME] [-U USERNAME] [-P PASSWORD]\n"
1984 " [-S START-TYPE] [-e SOURCE] [-W] [-t SECS] [-s] [-o OPTIONS]\n"), progname);
1985 printf(_(" %s unregister [-N SERVICENAME]\n"), progname);
1986 #endif
1988 printf(_("\nCommon options:\n"));
1989 printf(_(" -D, --pgdata=DATADIR location of the database storage area\n"));
1990 #ifdef WIN32
1991 printf(_(" -e SOURCE event source for logging when running as a service\n"));
1992 #endif
1993 printf(_(" -s, --silent only print errors, no informational messages\n"));
1994 printf(_(" -t, --timeout=SECS seconds to wait when using -w option\n"));
1995 printf(_(" -V, --version output version information, then exit\n"));
1996 printf(_(" -w, --wait wait until operation completes (default)\n"));
1997 printf(_(" -W, --no-wait do not wait until operation completes\n"));
1998 printf(_(" -?, --help show this help, then exit\n"));
1999 printf(_("If the -D option is omitted, the environment variable PGDATA is used.\n"));
2001 printf(_("\nOptions for start or restart:\n"));
2002 #if defined(HAVE_GETRLIMIT)
2003 printf(_(" -c, --core-files allow postgres to produce core files\n"));
2004 #else
2005 printf(_(" -c, --core-files not applicable on this platform\n"));
2006 #endif
2007 printf(_(" -l, --log=FILENAME write (or append) server log to FILENAME\n"));
2008 printf(_(" -o, --options=OPTIONS command line options to pass to postgres\n"
2009 " (PostgreSQL server executable) or initdb\n"));
2010 printf(_(" -p PATH-TO-POSTGRES normally not necessary\n"));
2011 printf(_("\nOptions for stop or restart:\n"));
2012 printf(_(" -m, --mode=MODE MODE can be \"smart\", \"fast\", or \"immediate\"\n"));
2014 printf(_("\nShutdown modes are:\n"));
2015 printf(_(" smart quit after all clients have disconnected\n"));
2016 printf(_(" fast quit directly, with proper shutdown (default)\n"));
2017 printf(_(" immediate quit without complete shutdown; will lead to recovery on restart\n"));
2019 printf(_("\nAllowed signal names for kill:\n"));
2020 printf(" ABRT HUP INT KILL QUIT TERM USR1 USR2\n");
2022 #ifdef WIN32
2023 printf(_("\nOptions for register and unregister:\n"));
2024 printf(_(" -N SERVICENAME service name with which to register PostgreSQL server\n"));
2025 printf(_(" -P PASSWORD password of account to register PostgreSQL server\n"));
2026 printf(_(" -U USERNAME user name of account to register PostgreSQL server\n"));
2027 printf(_(" -S START-TYPE service start type to register PostgreSQL server\n"));
2029 printf(_("\nStart types are:\n"));
2030 printf(_(" auto start service automatically during system startup (default)\n"));
2031 printf(_(" demand start service on demand\n"));
2032 #endif
2034 printf(_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
2035 printf(_("%s home page: <%s>\n"), PACKAGE_NAME, PACKAGE_URL);
2040 static void
2041 set_mode(char *modeopt)
2043 if (strcmp(modeopt, "s") == 0 || strcmp(modeopt, "smart") == 0)
2045 shutdown_mode = SMART_MODE;
2046 sig = SIGTERM;
2048 else if (strcmp(modeopt, "f") == 0 || strcmp(modeopt, "fast") == 0)
2050 shutdown_mode = FAST_MODE;
2051 sig = SIGINT;
2053 else if (strcmp(modeopt, "i") == 0 || strcmp(modeopt, "immediate") == 0)
2055 shutdown_mode = IMMEDIATE_MODE;
2056 sig = SIGQUIT;
2058 else
2060 write_stderr(_("%s: unrecognized shutdown mode \"%s\"\n"), progname, modeopt);
2061 do_advice();
2062 exit(1);
2068 static void
2069 set_sig(char *signame)
2071 if (strcmp(signame, "HUP") == 0)
2072 sig = SIGHUP;
2073 else if (strcmp(signame, "INT") == 0)
2074 sig = SIGINT;
2075 else if (strcmp(signame, "QUIT") == 0)
2076 sig = SIGQUIT;
2077 else if (strcmp(signame, "ABRT") == 0)
2078 sig = SIGABRT;
2079 else if (strcmp(signame, "KILL") == 0)
2080 sig = SIGKILL;
2081 else if (strcmp(signame, "TERM") == 0)
2082 sig = SIGTERM;
2083 else if (strcmp(signame, "USR1") == 0)
2084 sig = SIGUSR1;
2085 else if (strcmp(signame, "USR2") == 0)
2086 sig = SIGUSR2;
2087 else
2089 write_stderr(_("%s: unrecognized signal name \"%s\"\n"), progname, signame);
2090 do_advice();
2091 exit(1);
2096 #ifdef WIN32
2097 static void
2098 set_starttype(char *starttypeopt)
2100 if (strcmp(starttypeopt, "a") == 0 || strcmp(starttypeopt, "auto") == 0)
2101 pgctl_start_type = SERVICE_AUTO_START;
2102 else if (strcmp(starttypeopt, "d") == 0 || strcmp(starttypeopt, "demand") == 0)
2103 pgctl_start_type = SERVICE_DEMAND_START;
2104 else
2106 write_stderr(_("%s: unrecognized start type \"%s\"\n"), progname, starttypeopt);
2107 do_advice();
2108 exit(1);
2111 #endif
2114 * adjust_data_dir
2116 * If a configuration-only directory was specified, find the real data dir.
2118 static void
2119 adjust_data_dir(void)
2121 char filename[MAXPGPATH];
2122 char *my_exec_path,
2123 *cmd;
2124 FILE *fd;
2126 /* do nothing if we're working without knowledge of data dir */
2127 if (pg_config == NULL)
2128 return;
2130 /* If there is no postgresql.conf, it can't be a config-only dir */
2131 snprintf(filename, sizeof(filename), "%s/postgresql.conf", pg_config);
2132 if ((fd = fopen(filename, "r")) == NULL)
2133 return;
2134 fclose(fd);
2136 /* If PG_VERSION exists, it can't be a config-only dir */
2137 snprintf(filename, sizeof(filename), "%s/PG_VERSION", pg_config);
2138 if ((fd = fopen(filename, "r")) != NULL)
2140 fclose(fd);
2141 return;
2144 /* Must be a configuration directory, so find the data directory */
2146 /* we use a private my_exec_path to avoid interfering with later uses */
2147 if (exec_path == NULL)
2148 my_exec_path = find_other_exec_or_die(argv0, "postgres", PG_BACKEND_VERSIONSTR);
2149 else
2150 my_exec_path = pg_strdup(exec_path);
2152 /* it's important for -C to be the first option, see main.c */
2153 cmd = psprintf("\"%s\" -C data_directory %s%s",
2154 my_exec_path,
2155 pgdata_opt ? pgdata_opt : "",
2156 post_opts ? post_opts : "");
2157 fflush(NULL);
2159 fd = popen(cmd, "r");
2160 if (fd == NULL || fgets(filename, sizeof(filename), fd) == NULL)
2162 write_stderr(_("%s: could not determine the data directory using command \"%s\"\n"), progname, cmd);
2163 exit(1);
2165 pclose(fd);
2166 free(my_exec_path);
2168 /* strip trailing newline and carriage return */
2169 (void) pg_strip_crlf(filename);
2171 free(pg_data);
2172 pg_data = pg_strdup(filename);
2173 canonicalize_path(pg_data);
2177 static DBState
2178 get_control_dbstate(void)
2180 DBState ret;
2181 bool crc_ok;
2182 ControlFileData *control_file_data = get_controlfile(pg_data, &crc_ok);
2184 if (!crc_ok)
2186 write_stderr(_("%s: control file appears to be corrupt\n"), progname);
2187 exit(1);
2190 ret = control_file_data->state;
2191 pfree(control_file_data);
2192 return ret;
2197 main(int argc, char **argv)
2199 static struct option long_options[] = {
2200 {"help", no_argument, NULL, '?'},
2201 {"version", no_argument, NULL, 'V'},
2202 {"log", required_argument, NULL, 'l'},
2203 {"mode", required_argument, NULL, 'm'},
2204 {"pgdata", required_argument, NULL, 'D'},
2205 {"options", required_argument, NULL, 'o'},
2206 {"silent", no_argument, NULL, 's'},
2207 {"timeout", required_argument, NULL, 't'},
2208 {"core-files", no_argument, NULL, 'c'},
2209 {"wait", no_argument, NULL, 'w'},
2210 {"no-wait", no_argument, NULL, 'W'},
2211 {NULL, 0, NULL, 0}
2214 char *env_wait;
2215 int option_index;
2216 int c;
2217 pgpid_t killproc = 0;
2219 pg_logging_init(argv[0]);
2220 progname = get_progname(argv[0]);
2221 set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_ctl"));
2222 start_time = time(NULL);
2225 * save argv[0] so do_start() can look for the postmaster if necessary. we
2226 * don't look for postmaster here because in many cases we won't need it.
2228 argv0 = argv[0];
2230 /* Set restrictive mode mask until PGDATA permissions are checked */
2231 umask(PG_MODE_MASK_OWNER);
2233 /* support --help and --version even if invoked as root */
2234 if (argc > 1)
2236 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
2238 do_help();
2239 exit(0);
2241 else if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
2243 puts("pg_ctl (PostgreSQL) " PG_VERSION);
2244 exit(0);
2249 * Disallow running as root, to forestall any possible security holes.
2251 #ifndef WIN32
2252 if (geteuid() == 0)
2254 write_stderr(_("%s: cannot be run as root\n"
2255 "Please log in (using, e.g., \"su\") as the "
2256 "(unprivileged) user that will\n"
2257 "own the server process.\n"),
2258 progname);
2259 exit(1);
2261 #endif
2263 env_wait = getenv("PGCTLTIMEOUT");
2264 if (env_wait != NULL)
2265 wait_seconds = atoi(env_wait);
2268 * 'Action' can be before or after args so loop over both. Some
2269 * getopt_long() implementations will reorder argv[] to place all flags
2270 * first (GNU?), but we don't rely on it. Our /port version doesn't do
2271 * that.
2273 optind = 1;
2275 /* process command-line options */
2276 while (optind < argc)
2278 while ((c = getopt_long(argc, argv, "cD:e:l:m:N:o:p:P:sS:t:U:wW",
2279 long_options, &option_index)) != -1)
2281 switch (c)
2283 case 'D':
2285 char *pgdata_D;
2287 pgdata_D = pg_strdup(optarg);
2288 canonicalize_path(pgdata_D);
2289 setenv("PGDATA", pgdata_D, 1);
2292 * We could pass PGDATA just in an environment
2293 * variable but we do -D too for clearer postmaster
2294 * 'ps' display
2296 pgdata_opt = psprintf("-D \"%s\" ", pgdata_D);
2297 free(pgdata_D);
2298 break;
2300 case 'e':
2301 event_source = pg_strdup(optarg);
2302 break;
2303 case 'l':
2304 log_file = pg_strdup(optarg);
2305 break;
2306 case 'm':
2307 set_mode(optarg);
2308 break;
2309 case 'N':
2310 register_servicename = pg_strdup(optarg);
2311 break;
2312 case 'o':
2313 /* append option? */
2314 if (!post_opts)
2315 post_opts = pg_strdup(optarg);
2316 else
2318 char *old_post_opts = post_opts;
2320 post_opts = psprintf("%s %s", old_post_opts, optarg);
2321 free(old_post_opts);
2323 break;
2324 case 'p':
2325 exec_path = pg_strdup(optarg);
2326 break;
2327 case 'P':
2328 register_password = pg_strdup(optarg);
2329 break;
2330 case 's':
2331 silent_mode = true;
2332 break;
2333 case 'S':
2334 #ifdef WIN32
2335 set_starttype(optarg);
2336 #else
2337 write_stderr(_("%s: -S option not supported on this platform\n"),
2338 progname);
2339 exit(1);
2340 #endif
2341 break;
2342 case 't':
2343 wait_seconds = atoi(optarg);
2344 wait_seconds_arg = true;
2345 break;
2346 case 'U':
2347 if (strchr(optarg, '\\'))
2348 register_username = pg_strdup(optarg);
2349 else
2350 /* Prepend .\ for local accounts */
2351 register_username = psprintf(".\\%s", optarg);
2352 break;
2353 case 'w':
2354 do_wait = true;
2355 break;
2356 case 'W':
2357 do_wait = false;
2358 break;
2359 case 'c':
2360 allow_core_files = true;
2361 break;
2362 default:
2363 /* getopt_long already issued a suitable error message */
2364 do_advice();
2365 exit(1);
2369 /* Process an action */
2370 if (optind < argc)
2372 if (ctl_command != NO_COMMAND)
2374 write_stderr(_("%s: too many command-line arguments (first is \"%s\")\n"), progname, argv[optind]);
2375 do_advice();
2376 exit(1);
2379 if (strcmp(argv[optind], "init") == 0
2380 || strcmp(argv[optind], "initdb") == 0)
2381 ctl_command = INIT_COMMAND;
2382 else if (strcmp(argv[optind], "start") == 0)
2383 ctl_command = START_COMMAND;
2384 else if (strcmp(argv[optind], "stop") == 0)
2385 ctl_command = STOP_COMMAND;
2386 else if (strcmp(argv[optind], "restart") == 0)
2387 ctl_command = RESTART_COMMAND;
2388 else if (strcmp(argv[optind], "reload") == 0)
2389 ctl_command = RELOAD_COMMAND;
2390 else if (strcmp(argv[optind], "status") == 0)
2391 ctl_command = STATUS_COMMAND;
2392 else if (strcmp(argv[optind], "promote") == 0)
2393 ctl_command = PROMOTE_COMMAND;
2394 else if (strcmp(argv[optind], "logrotate") == 0)
2395 ctl_command = LOGROTATE_COMMAND;
2396 else if (strcmp(argv[optind], "kill") == 0)
2398 if (argc - optind < 3)
2400 write_stderr(_("%s: missing arguments for kill mode\n"), progname);
2401 do_advice();
2402 exit(1);
2404 ctl_command = KILL_COMMAND;
2405 set_sig(argv[++optind]);
2406 killproc = atol(argv[++optind]);
2408 #ifdef WIN32
2409 else if (strcmp(argv[optind], "register") == 0)
2410 ctl_command = REGISTER_COMMAND;
2411 else if (strcmp(argv[optind], "unregister") == 0)
2412 ctl_command = UNREGISTER_COMMAND;
2413 else if (strcmp(argv[optind], "runservice") == 0)
2414 ctl_command = RUN_AS_SERVICE_COMMAND;
2415 #endif
2416 else
2418 write_stderr(_("%s: unrecognized operation mode \"%s\"\n"), progname, argv[optind]);
2419 do_advice();
2420 exit(1);
2422 optind++;
2426 if (ctl_command == NO_COMMAND)
2428 write_stderr(_("%s: no operation specified\n"), progname);
2429 do_advice();
2430 exit(1);
2433 /* Note we put any -D switch into the env var above */
2434 pg_config = getenv("PGDATA");
2435 if (pg_config)
2437 pg_config = pg_strdup(pg_config);
2438 canonicalize_path(pg_config);
2439 pg_data = pg_strdup(pg_config);
2442 /* -D might point at config-only directory; if so find the real PGDATA */
2443 adjust_data_dir();
2445 /* Complain if -D needed and not provided */
2446 if (pg_config == NULL &&
2447 ctl_command != KILL_COMMAND && ctl_command != UNREGISTER_COMMAND)
2449 write_stderr(_("%s: no database directory specified and environment variable PGDATA unset\n"),
2450 progname);
2451 do_advice();
2452 exit(1);
2455 if (ctl_command == RELOAD_COMMAND)
2457 sig = SIGHUP;
2458 do_wait = false;
2461 if (pg_data)
2463 snprintf(postopts_file, MAXPGPATH, "%s/postmaster.opts", pg_data);
2464 snprintf(version_file, MAXPGPATH, "%s/PG_VERSION", pg_data);
2465 snprintf(pid_file, MAXPGPATH, "%s/postmaster.pid", pg_data);
2466 snprintf(backup_file, MAXPGPATH, "%s/backup_label", pg_data);
2469 * Set mask based on PGDATA permissions,
2471 * Don't error here if the data directory cannot be stat'd. This is
2472 * handled differently based on the command and we don't want to
2473 * interfere with that logic.
2475 if (GetDataDirectoryCreatePerm(pg_data))
2476 umask(pg_mode_mask);
2479 switch (ctl_command)
2481 case INIT_COMMAND:
2482 do_init();
2483 break;
2484 case STATUS_COMMAND:
2485 do_status();
2486 break;
2487 case START_COMMAND:
2488 do_start();
2489 break;
2490 case STOP_COMMAND:
2491 do_stop();
2492 break;
2493 case RESTART_COMMAND:
2494 do_restart();
2495 break;
2496 case RELOAD_COMMAND:
2497 do_reload();
2498 break;
2499 case PROMOTE_COMMAND:
2500 do_promote();
2501 break;
2502 case LOGROTATE_COMMAND:
2503 do_logrotate();
2504 break;
2505 case KILL_COMMAND:
2506 do_kill(killproc);
2507 break;
2508 #ifdef WIN32
2509 case REGISTER_COMMAND:
2510 pgwin32_doRegister();
2511 break;
2512 case UNREGISTER_COMMAND:
2513 pgwin32_doUnregister();
2514 break;
2515 case RUN_AS_SERVICE_COMMAND:
2516 pgwin32_doRunAsService();
2517 break;
2518 #endif
2519 default:
2520 break;
2523 exit(0);