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