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