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