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