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