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