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