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