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