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