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