]> granicus.if.org Git - postgresql/blob - src/bin/pg_ctl/pg_ctl.c
Miscellaneous cleanup to silence compiler warnings seen on Mingw.
[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-2011, 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          * The Linux Standard Base Core Specification 3.1 says this should return '3'
1193          * http://refspecs.freestandards.org/LSB_3.1.1/LSB-Core-generic/LSB-Core-generic/iniscrptact.html
1194          */
1195         exit(3);
1196 }
1197
1198
1199
1200 static void
1201 do_kill(pgpid_t pid)
1202 {
1203         if (kill((pid_t) pid, sig) != 0)
1204         {
1205                 write_stderr(_("%s: could not send signal %d (PID: %ld): %s\n"),
1206                                          progname, sig, pid, strerror(errno));
1207                 exit(1);
1208         }
1209 }
1210
1211 #if defined(WIN32) || defined(__CYGWIN__)
1212
1213 static bool
1214 pgwin32_IsInstalled(SC_HANDLE hSCM)
1215 {
1216         SC_HANDLE       hService = OpenService(hSCM, register_servicename, SERVICE_QUERY_CONFIG);
1217         bool            bResult = (hService != NULL);
1218
1219         if (bResult)
1220                 CloseServiceHandle(hService);
1221         return bResult;
1222 }
1223
1224 static char *
1225 pgwin32_CommandLine(bool registration)
1226 {
1227         static char cmdLine[MAXPGPATH];
1228         int                     ret;
1229
1230 #ifdef __CYGWIN__
1231         char            buf[MAXPGPATH];
1232 #endif
1233
1234         if (registration)
1235         {
1236                 ret = find_my_exec(argv0, cmdLine);
1237                 if (ret != 0)
1238                 {
1239                         write_stderr(_("%s: could not find own program executable\n"), progname);
1240                         exit(1);
1241                 }
1242         }
1243         else
1244         {
1245                 ret = find_other_exec(argv0, "postgres", PG_BACKEND_VERSIONSTR,
1246                                                           cmdLine);
1247                 if (ret != 0)
1248                 {
1249                         write_stderr(_("%s: could not find postgres program executable\n"), progname);
1250                         exit(1);
1251                 }
1252         }
1253
1254 #ifdef __CYGWIN__
1255         /* need to convert to windows path */
1256 #if CYGWIN_VERSION_DLL_MAJOR >= 1007
1257         cygwin_conv_path(CCP_POSIX_TO_WIN_A, cmdLine, buf, sizeof(buf));
1258 #else
1259         cygwin_conv_to_full_win32_path(cmdLine, buf);
1260 #endif
1261         strcpy(cmdLine, buf);
1262 #endif
1263
1264         if (registration)
1265         {
1266                 if (pg_strcasecmp(cmdLine + strlen(cmdLine) - 4, ".exe"))
1267                 {
1268                         /* If commandline does not end in .exe, append it */
1269                         strcat(cmdLine, ".exe");
1270                 }
1271                 strcat(cmdLine, " runservice -N \"");
1272                 strcat(cmdLine, register_servicename);
1273                 strcat(cmdLine, "\"");
1274         }
1275
1276         if (pg_config)
1277         {
1278                 strcat(cmdLine, " -D \"");
1279                 strcat(cmdLine, pg_config);
1280                 strcat(cmdLine, "\"");
1281         }
1282
1283         if (registration && do_wait)
1284                 strcat(cmdLine, " -w");
1285
1286         if (registration && wait_seconds != DEFAULT_WAIT)
1287                 /* concatenate */
1288                 sprintf(cmdLine + strlen(cmdLine), " -t %d", wait_seconds);
1289
1290         if (registration && silent_mode)
1291                 strcat(cmdLine, " -s");
1292
1293         if (post_opts)
1294         {
1295                 strcat(cmdLine, " ");
1296                 if (registration)
1297                         strcat(cmdLine, " -o \"");
1298                 strcat(cmdLine, post_opts);
1299                 if (registration)
1300                         strcat(cmdLine, "\"");
1301         }
1302
1303         return cmdLine;
1304 }
1305
1306 static void
1307 pgwin32_doRegister(void)
1308 {
1309         SC_HANDLE       hService;
1310         SC_HANDLE       hSCM = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
1311
1312         if (hSCM == NULL)
1313         {
1314                 write_stderr(_("%s: could not open service manager\n"), progname);
1315                 exit(1);
1316         }
1317         if (pgwin32_IsInstalled(hSCM))
1318         {
1319                 CloseServiceHandle(hSCM);
1320                 write_stderr(_("%s: service \"%s\" already registered\n"), progname, register_servicename);
1321                 exit(1);
1322         }
1323
1324         if ((hService = CreateService(hSCM, register_servicename, register_servicename,
1325                                                            SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS,
1326                                                                   pgctl_start_type, SERVICE_ERROR_NORMAL,
1327                                                                   pgwin32_CommandLine(true),
1328            NULL, NULL, "RPCSS\0", register_username, register_password)) == NULL)
1329         {
1330                 CloseServiceHandle(hSCM);
1331                 write_stderr(_("%s: could not register service \"%s\": error code %lu\n"), progname, register_servicename, GetLastError());
1332                 exit(1);
1333         }
1334         CloseServiceHandle(hService);
1335         CloseServiceHandle(hSCM);
1336 }
1337
1338 static void
1339 pgwin32_doUnregister(void)
1340 {
1341         SC_HANDLE       hService;
1342         SC_HANDLE       hSCM = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
1343
1344         if (hSCM == NULL)
1345         {
1346                 write_stderr(_("%s: could not open service manager\n"), progname);
1347                 exit(1);
1348         }
1349         if (!pgwin32_IsInstalled(hSCM))
1350         {
1351                 CloseServiceHandle(hSCM);
1352                 write_stderr(_("%s: service \"%s\" not registered\n"), progname, register_servicename);
1353                 exit(1);
1354         }
1355
1356         if ((hService = OpenService(hSCM, register_servicename, DELETE)) == NULL)
1357         {
1358                 CloseServiceHandle(hSCM);
1359                 write_stderr(_("%s: could not open service \"%s\": error code %lu\n"), progname, register_servicename, GetLastError());
1360                 exit(1);
1361         }
1362         if (!DeleteService(hService))
1363         {
1364                 CloseServiceHandle(hService);
1365                 CloseServiceHandle(hSCM);
1366                 write_stderr(_("%s: could not unregister service \"%s\": error code %lu\n"), progname, register_servicename, GetLastError());
1367                 exit(1);
1368         }
1369         CloseServiceHandle(hService);
1370         CloseServiceHandle(hSCM);
1371 }
1372
1373 static void
1374 pgwin32_SetServiceStatus(DWORD currentState)
1375 {
1376         status.dwCurrentState = currentState;
1377         SetServiceStatus(hStatus, (LPSERVICE_STATUS) &status);
1378 }
1379
1380 static void WINAPI
1381 pgwin32_ServiceHandler(DWORD request)
1382 {
1383         switch (request)
1384         {
1385                 case SERVICE_CONTROL_STOP:
1386                 case SERVICE_CONTROL_SHUTDOWN:
1387
1388                         /*
1389                          * We only need a short wait hint here as it just needs to wait
1390                          * for the next checkpoint. They occur every 5 seconds during
1391                          * shutdown
1392                          */
1393                         status.dwWaitHint = 10000;
1394                         pgwin32_SetServiceStatus(SERVICE_STOP_PENDING);
1395                         SetEvent(shutdownEvent);
1396                         return;
1397
1398                 case SERVICE_CONTROL_PAUSE:
1399                         /* Win32 config reloading */
1400                         status.dwWaitHint = 5000;
1401                         kill(postmasterPID, SIGHUP);
1402                         return;
1403
1404                         /* FIXME: These could be used to replace other signals etc */
1405                 case SERVICE_CONTROL_CONTINUE:
1406                 case SERVICE_CONTROL_INTERROGATE:
1407                 default:
1408                         break;
1409         }
1410 }
1411
1412 static void WINAPI
1413 pgwin32_ServiceMain(DWORD argc, LPTSTR *argv)
1414 {
1415         PROCESS_INFORMATION pi;
1416         DWORD           ret;
1417
1418         /* Initialize variables */
1419         status.dwWin32ExitCode = S_OK;
1420         status.dwCheckPoint = 0;
1421         status.dwWaitHint = 60000;
1422         status.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
1423         status.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN | SERVICE_ACCEPT_PAUSE_CONTINUE;
1424         status.dwServiceSpecificExitCode = 0;
1425         status.dwCurrentState = SERVICE_START_PENDING;
1426
1427         memset(&pi, 0, sizeof(pi));
1428
1429         read_post_opts();
1430
1431         /* Register the control request handler */
1432         if ((hStatus = RegisterServiceCtrlHandler(register_servicename, pgwin32_ServiceHandler)) == (SERVICE_STATUS_HANDLE) 0)
1433                 return;
1434
1435         if ((shutdownEvent = CreateEvent(NULL, true, false, NULL)) == NULL)
1436                 return;
1437
1438         /* Start the postmaster */
1439         pgwin32_SetServiceStatus(SERVICE_START_PENDING);
1440         if (!CreateRestrictedProcess(pgwin32_CommandLine(false), &pi, true))
1441         {
1442                 pgwin32_SetServiceStatus(SERVICE_STOPPED);
1443                 return;
1444         }
1445         postmasterPID = pi.dwProcessId;
1446         postmasterProcess = pi.hProcess;
1447         CloseHandle(pi.hThread);
1448
1449         if (do_wait)
1450         {
1451                 write_eventlog(EVENTLOG_INFORMATION_TYPE, _("Waiting for server startup...\n"));
1452                 if (test_postmaster_connection(true) != PQPING_OK)
1453                 {
1454                         write_eventlog(EVENTLOG_ERROR_TYPE, _("Timed out waiting for server startup\n"));
1455                         pgwin32_SetServiceStatus(SERVICE_STOPPED);
1456                         return;
1457                 }
1458                 write_eventlog(EVENTLOG_INFORMATION_TYPE, _("Server started and accepting connections\n"));
1459         }
1460
1461         pgwin32_SetServiceStatus(SERVICE_RUNNING);
1462
1463         /* Wait for quit... */
1464         ret = WaitForMultipleObjects(2, shutdownHandles, FALSE, INFINITE);
1465
1466         pgwin32_SetServiceStatus(SERVICE_STOP_PENDING);
1467         switch (ret)
1468         {
1469                 case WAIT_OBJECT_0:             /* shutdown event */
1470                         kill(postmasterPID, SIGINT);
1471
1472                         /*
1473                          * Increment the checkpoint and try again Abort after 12
1474                          * checkpoints as the postmaster has probably hung
1475                          */
1476                         while (WaitForSingleObject(postmasterProcess, 5000) == WAIT_TIMEOUT && status.dwCheckPoint < 12)
1477                                 status.dwCheckPoint++;
1478                         break;
1479
1480                 case (WAIT_OBJECT_0 + 1):               /* postmaster went down */
1481                         break;
1482
1483                 default:
1484                         /* shouldn't get here? */
1485                         break;
1486         }
1487
1488         CloseHandle(shutdownEvent);
1489         CloseHandle(postmasterProcess);
1490
1491         pgwin32_SetServiceStatus(SERVICE_STOPPED);
1492 }
1493
1494 static void
1495 pgwin32_doRunAsService(void)
1496 {
1497         SERVICE_TABLE_ENTRY st[] = {{register_servicename, pgwin32_ServiceMain},
1498         {NULL, NULL}};
1499
1500         if (StartServiceCtrlDispatcher(st) == 0)
1501         {
1502                 write_stderr(_("%s: could not start service \"%s\": error code %lu\n"), progname, register_servicename, GetLastError());
1503                 exit(1);
1504         }
1505 }
1506
1507
1508 /*
1509  * Mingw headers are incomplete, and so are the libraries. So we have to load
1510  * a whole lot of API functions dynamically. Since we have to do this anyway,
1511  * also load the couple of functions that *do* exist in minwg headers but not
1512  * on NT4. That way, we don't break on NT4.
1513  */
1514 typedef BOOL (WINAPI * __CreateRestrictedToken) (HANDLE, DWORD, DWORD, PSID_AND_ATTRIBUTES, DWORD, PLUID_AND_ATTRIBUTES, DWORD, PSID_AND_ATTRIBUTES, PHANDLE);
1515 typedef BOOL (WINAPI * __IsProcessInJob) (HANDLE, HANDLE, PBOOL);
1516 typedef HANDLE (WINAPI * __CreateJobObject) (LPSECURITY_ATTRIBUTES, LPCTSTR);
1517 typedef BOOL (WINAPI * __SetInformationJobObject) (HANDLE, JOBOBJECTINFOCLASS, LPVOID, DWORD);
1518 typedef BOOL (WINAPI * __AssignProcessToJobObject) (HANDLE, HANDLE);
1519 typedef BOOL (WINAPI * __QueryInformationJobObject) (HANDLE, JOBOBJECTINFOCLASS, LPVOID, DWORD, LPDWORD);
1520
1521 /* Windows API define missing from some versions of MingW headers */
1522 #ifndef  DISABLE_MAX_PRIVILEGE
1523 #define DISABLE_MAX_PRIVILEGE   0x1
1524 #endif
1525
1526 /*
1527  * Create a restricted token, a job object sandbox, and execute the specified
1528  * process with it.
1529  *
1530  * Returns 0 on success, non-zero on failure, same as CreateProcess().
1531  *
1532  * On NT4, or any other system not containing the required functions, will
1533  * launch the process under the current token without doing any modifications.
1534  *
1535  * NOTE! Job object will only work when running as a service, because it's
1536  * automatically destroyed when pg_ctl exits.
1537  */
1538 static int
1539 CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo, bool as_service)
1540 {
1541         int                     r;
1542         BOOL            b;
1543         STARTUPINFO si;
1544         HANDLE          origToken;
1545         HANDLE          restrictedToken;
1546         SID_IDENTIFIER_AUTHORITY NtAuthority = {SECURITY_NT_AUTHORITY};
1547         SID_AND_ATTRIBUTES dropSids[2];
1548
1549         /* Functions loaded dynamically */
1550         __CreateRestrictedToken _CreateRestrictedToken = NULL;
1551         __IsProcessInJob _IsProcessInJob = NULL;
1552         __CreateJobObject _CreateJobObject = NULL;
1553         __SetInformationJobObject _SetInformationJobObject = NULL;
1554         __AssignProcessToJobObject _AssignProcessToJobObject = NULL;
1555         __QueryInformationJobObject _QueryInformationJobObject = NULL;
1556         HANDLE          Kernel32Handle;
1557         HANDLE          Advapi32Handle;
1558
1559         ZeroMemory(&si, sizeof(si));
1560         si.cb = sizeof(si);
1561
1562         Advapi32Handle = LoadLibrary("ADVAPI32.DLL");
1563         if (Advapi32Handle != NULL)
1564         {
1565                 _CreateRestrictedToken = (__CreateRestrictedToken) GetProcAddress(Advapi32Handle, "CreateRestrictedToken");
1566         }
1567
1568         if (_CreateRestrictedToken == NULL)
1569         {
1570                 /*
1571                  * NT4 doesn't have CreateRestrictedToken, so just call ordinary
1572                  * CreateProcess
1573                  */
1574                 write_stderr(_("%s: WARNING: cannot create restricted tokens on this platform\n"), progname);
1575                 if (Advapi32Handle != NULL)
1576                         FreeLibrary(Advapi32Handle);
1577                 return CreateProcess(NULL, cmd, NULL, NULL, FALSE, 0, NULL, NULL, &si, processInfo);
1578         }
1579
1580         /* Open the current token to use as a base for the restricted one */
1581         if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &origToken))
1582         {
1583                 write_stderr(_("%s: could not open process token: error code %lu\n"), progname, GetLastError());
1584                 return 0;
1585         }
1586
1587         /* Allocate list of SIDs to remove */
1588         ZeroMemory(&dropSids, sizeof(dropSids));
1589         if (!AllocateAndInitializeSid(&NtAuthority, 2,
1590                  SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0,
1591                                                                   0, &dropSids[0].Sid) ||
1592                 !AllocateAndInitializeSid(&NtAuthority, 2,
1593         SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_POWER_USERS, 0, 0, 0, 0, 0,
1594                                                                   0, &dropSids[1].Sid))
1595         {
1596                 write_stderr(_("%s: could not allocate SIDs: error code %lu\n"), progname, GetLastError());
1597                 return 0;
1598         }
1599
1600         b = _CreateRestrictedToken(origToken,
1601                                                            DISABLE_MAX_PRIVILEGE,
1602                                                            sizeof(dropSids) / sizeof(dropSids[0]),
1603                                                            dropSids,
1604                                                            0, NULL,
1605                                                            0, NULL,
1606                                                            &restrictedToken);
1607
1608         FreeSid(dropSids[1].Sid);
1609         FreeSid(dropSids[0].Sid);
1610         CloseHandle(origToken);
1611         FreeLibrary(Advapi32Handle);
1612
1613         if (!b)
1614         {
1615                 write_stderr(_("%s: could not create restricted token: error code %lu\n"), progname, GetLastError());
1616                 return 0;
1617         }
1618
1619 #ifndef __CYGWIN__
1620         AddUserToTokenDacl(restrictedToken);
1621 #endif
1622
1623         r = CreateProcessAsUser(restrictedToken, NULL, cmd, NULL, NULL, TRUE, CREATE_SUSPENDED, NULL, NULL, &si, processInfo);
1624
1625         Kernel32Handle = LoadLibrary("KERNEL32.DLL");
1626         if (Kernel32Handle != NULL)
1627         {
1628                 _IsProcessInJob = (__IsProcessInJob) GetProcAddress(Kernel32Handle, "IsProcessInJob");
1629                 _CreateJobObject = (__CreateJobObject) GetProcAddress(Kernel32Handle, "CreateJobObjectA");
1630                 _SetInformationJobObject = (__SetInformationJobObject) GetProcAddress(Kernel32Handle, "SetInformationJobObject");
1631                 _AssignProcessToJobObject = (__AssignProcessToJobObject) GetProcAddress(Kernel32Handle, "AssignProcessToJobObject");
1632                 _QueryInformationJobObject = (__QueryInformationJobObject) GetProcAddress(Kernel32Handle, "QueryInformationJobObject");
1633         }
1634
1635         /* Verify that we found all functions */
1636         if (_IsProcessInJob == NULL || _CreateJobObject == NULL || _SetInformationJobObject == NULL || _AssignProcessToJobObject == NULL || _QueryInformationJobObject == NULL)
1637         {
1638                 /*
1639                  * IsProcessInJob() is not available on < WinXP, so there is no need
1640                  * to log the error every time in that case
1641                  */
1642                 OSVERSIONINFO osv;
1643
1644                 osv.dwOSVersionInfoSize = sizeof(osv);
1645                 if (!GetVersionEx(&osv) ||              /* could not get version */
1646                         (osv.dwMajorVersion == 5 && osv.dwMinorVersion > 0) ||          /* 5.1=xp, 5.2=2003, etc */
1647                         osv.dwMajorVersion > 5)         /* anything newer should have the API */
1648
1649                         /*
1650                          * Log error if we can't get version, or if we're on WinXP/2003 or
1651                          * newer
1652                          */
1653                         write_stderr(_("%s: WARNING: could not locate all job object functions in system API\n"), progname);
1654         }
1655         else
1656         {
1657                 BOOL            inJob;
1658
1659                 if (_IsProcessInJob(processInfo->hProcess, NULL, &inJob))
1660                 {
1661                         if (!inJob)
1662                         {
1663                                 /*
1664                                  * Job objects are working, and the new process isn't in one,
1665                                  * so we can create one safely. If any problems show up when
1666                                  * setting it, we're going to ignore them.
1667                                  */
1668                                 HANDLE          job;
1669                                 char            jobname[128];
1670
1671                                 sprintf(jobname, "PostgreSQL_%lu", processInfo->dwProcessId);
1672
1673                                 job = _CreateJobObject(NULL, jobname);
1674                                 if (job)
1675                                 {
1676                                         JOBOBJECT_BASIC_LIMIT_INFORMATION basicLimit;
1677                                         JOBOBJECT_BASIC_UI_RESTRICTIONS uiRestrictions;
1678                                         JOBOBJECT_SECURITY_LIMIT_INFORMATION securityLimit;
1679                                         OSVERSIONINFO osv;
1680
1681                                         ZeroMemory(&basicLimit, sizeof(basicLimit));
1682                                         ZeroMemory(&uiRestrictions, sizeof(uiRestrictions));
1683                                         ZeroMemory(&securityLimit, sizeof(securityLimit));
1684
1685                                         basicLimit.LimitFlags = JOB_OBJECT_LIMIT_DIE_ON_UNHANDLED_EXCEPTION | JOB_OBJECT_LIMIT_PRIORITY_CLASS;
1686                                         basicLimit.PriorityClass = NORMAL_PRIORITY_CLASS;
1687                                         _SetInformationJobObject(job, JobObjectBasicLimitInformation, &basicLimit, sizeof(basicLimit));
1688
1689                                         uiRestrictions.UIRestrictionsClass = JOB_OBJECT_UILIMIT_DESKTOP | JOB_OBJECT_UILIMIT_DISPLAYSETTINGS |
1690                                                 JOB_OBJECT_UILIMIT_EXITWINDOWS | JOB_OBJECT_UILIMIT_READCLIPBOARD |
1691                                                 JOB_OBJECT_UILIMIT_SYSTEMPARAMETERS | JOB_OBJECT_UILIMIT_WRITECLIPBOARD;
1692
1693                                         if (as_service)
1694                                         {
1695                                                 osv.dwOSVersionInfoSize = sizeof(osv);
1696                                                 if (!GetVersionEx(&osv) ||
1697                                                         osv.dwMajorVersion < 6 ||
1698                                                 (osv.dwMajorVersion == 6 && osv.dwMinorVersion == 0))
1699                                                 {
1700                                                         /*
1701                                                          * On Windows 7 (and presumably later),
1702                                                          * JOB_OBJECT_UILIMIT_HANDLES prevents us from
1703                                                          * starting as a service. So we only enable it on
1704                                                          * Vista and earlier (version <= 6.0)
1705                                                          */
1706                                                         uiRestrictions.UIRestrictionsClass |= JOB_OBJECT_UILIMIT_HANDLES;
1707                                                 }
1708                                         }
1709                                         _SetInformationJobObject(job, JobObjectBasicUIRestrictions, &uiRestrictions, sizeof(uiRestrictions));
1710
1711                                         securityLimit.SecurityLimitFlags = JOB_OBJECT_SECURITY_NO_ADMIN | JOB_OBJECT_SECURITY_ONLY_TOKEN;
1712                                         securityLimit.JobToken = restrictedToken;
1713                                         _SetInformationJobObject(job, JobObjectSecurityLimitInformation, &securityLimit, sizeof(securityLimit));
1714
1715                                         _AssignProcessToJobObject(job, processInfo->hProcess);
1716                                 }
1717                         }
1718                 }
1719         }
1720
1721
1722         CloseHandle(restrictedToken);
1723
1724         ResumeThread(processInfo->hThread);
1725
1726         FreeLibrary(Kernel32Handle);
1727
1728         /*
1729          * We intentionally don't close the job object handle, because we want the
1730          * object to live on until pg_ctl shuts down.
1731          */
1732         return r;
1733 }
1734 #endif
1735
1736 static void
1737 do_advice(void)
1738 {
1739         write_stderr(_("Try \"%s --help\" for more information.\n"), progname);
1740 }
1741
1742
1743
1744 static void
1745 do_help(void)
1746 {
1747         printf(_("%s is a utility to initialize, start, stop, or control a PostgreSQL server.\n\n"), progname);
1748         printf(_("Usage:\n"));
1749         printf(_("  %s init[db]               [-D DATADIR] [-s] [-o \"OPTIONS\"]\n"), progname);
1750         printf(_("  %s start   [-w] [-t SECS] [-D DATADIR] [-s] [-l FILENAME] [-o \"OPTIONS\"]\n"), progname);
1751         printf(_("  %s stop    [-W] [-t SECS] [-D DATADIR] [-s] [-m SHUTDOWN-MODE]\n"), progname);
1752         printf(_("  %s restart [-w] [-t SECS] [-D DATADIR] [-s] [-m SHUTDOWN-MODE]\n"
1753                          "                 [-o \"OPTIONS\"]\n"), progname);
1754         printf(_("  %s reload  [-D DATADIR] [-s]\n"), progname);
1755         printf(_("  %s status  [-D DATADIR]\n"), progname);
1756         printf(_("  %s promote [-D DATADIR] [-s]\n"), progname);
1757         printf(_("  %s kill    SIGNALNAME PID\n"), progname);
1758 #if defined(WIN32) || defined(__CYGWIN__)
1759         printf(_("  %s register   [-N SERVICENAME] [-U USERNAME] [-P PASSWORD] [-D DATADIR]\n"
1760                          "                    [-S START-TYPE] [-w] [-t SECS] [-o \"OPTIONS\"]\n"), progname);
1761         printf(_("  %s unregister [-N SERVICENAME]\n"), progname);
1762 #endif
1763
1764         printf(_("\nCommon options:\n"));
1765         printf(_("  -D, --pgdata DATADIR   location of the database storage area\n"));
1766         printf(_("  -s, --silent           only print errors, no informational messages\n"));
1767         printf(_("  -t SECS                seconds to wait when using -w option\n"));
1768         printf(_("  -w                     wait until operation completes\n"));
1769         printf(_("  -W                     do not wait until operation completes\n"));
1770         printf(_("  --help                 show this help, then exit\n"));
1771         printf(_("  --version              output version information, then exit\n"));
1772         printf(_("(The default is to wait for shutdown, but not for start or restart.)\n\n"));
1773         printf(_("If the -D option is omitted, the environment variable PGDATA is used.\n"));
1774
1775         printf(_("\nOptions for start or restart:\n"));
1776 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_CORE)
1777         printf(_("  -c, --core-files       allow postgres to produce core files\n"));
1778 #else
1779         printf(_("  -c, --core-files       not applicable on this platform\n"));
1780 #endif
1781         printf(_("  -l, --log FILENAME     write (or append) server log to FILENAME\n"));
1782         printf(_("  -o OPTIONS             command line options to pass to postgres\n"
1783          "                         (PostgreSQL server executable) or initdb\n"));
1784         printf(_("  -p PATH-TO-POSTGRES    normally not necessary\n"));
1785         printf(_("\nOptions for stop or restart:\n"));
1786         printf(_("  -m SHUTDOWN-MODE   can be \"smart\", \"fast\", or \"immediate\"\n"));
1787
1788         printf(_("\nShutdown modes are:\n"));
1789         printf(_("  smart       quit after all clients have disconnected\n"));
1790         printf(_("  fast        quit directly, with proper shutdown\n"));
1791         printf(_("  immediate   quit without complete shutdown; will lead to recovery on restart\n"));
1792
1793         printf(_("\nAllowed signal names for kill:\n"));
1794         printf("  HUP INT QUIT ABRT TERM USR1 USR2\n");
1795
1796 #if defined(WIN32) || defined(__CYGWIN__)
1797         printf(_("\nOptions for register and unregister:\n"));
1798         printf(_("  -N SERVICENAME  service name with which to register PostgreSQL server\n"));
1799         printf(_("  -P PASSWORD     password of account to register PostgreSQL server\n"));
1800         printf(_("  -U USERNAME     user name of account to register PostgreSQL server\n"));
1801         printf(_("  -S START-TYPE   service start type to register PostgreSQL server\n"));
1802
1803         printf(_("\nStart types are:\n"));
1804         printf(_("  auto       start service automatically during system startup (default)\n"));
1805         printf(_("  demand     start service on demand\n"));
1806 #endif
1807
1808         printf(_("\nReport bugs to <pgsql-bugs@postgresql.org>.\n"));
1809 }
1810
1811
1812
1813 static void
1814 set_mode(char *modeopt)
1815 {
1816         if (strcmp(modeopt, "s") == 0 || strcmp(modeopt, "smart") == 0)
1817         {
1818                 shutdown_mode = SMART_MODE;
1819                 sig = SIGTERM;
1820         }
1821         else if (strcmp(modeopt, "f") == 0 || strcmp(modeopt, "fast") == 0)
1822         {
1823                 shutdown_mode = FAST_MODE;
1824                 sig = SIGINT;
1825         }
1826         else if (strcmp(modeopt, "i") == 0 || strcmp(modeopt, "immediate") == 0)
1827         {
1828                 shutdown_mode = IMMEDIATE_MODE;
1829                 sig = SIGQUIT;
1830         }
1831         else
1832         {
1833                 write_stderr(_("%s: unrecognized shutdown mode \"%s\"\n"), progname, modeopt);
1834                 do_advice();
1835                 exit(1);
1836         }
1837 }
1838
1839
1840
1841 static void
1842 set_sig(char *signame)
1843 {
1844         if (!strcmp(signame, "HUP"))
1845                 sig = SIGHUP;
1846         else if (!strcmp(signame, "INT"))
1847                 sig = SIGINT;
1848         else if (!strcmp(signame, "QUIT"))
1849                 sig = SIGQUIT;
1850         else if (!strcmp(signame, "ABRT"))
1851                 sig = SIGABRT;
1852
1853         /*
1854          * probably should NOT provide SIGKILL
1855          *
1856          * else if (!strcmp(signame,"KILL")) sig = SIGKILL;
1857          */
1858         else if (!strcmp(signame, "TERM"))
1859                 sig = SIGTERM;
1860         else if (!strcmp(signame, "USR1"))
1861                 sig = SIGUSR1;
1862         else if (!strcmp(signame, "USR2"))
1863                 sig = SIGUSR2;
1864         else
1865         {
1866                 write_stderr(_("%s: unrecognized signal name \"%s\"\n"), progname, signame);
1867                 do_advice();
1868                 exit(1);
1869         }
1870 }
1871
1872
1873 #if defined(WIN32) || defined(__CYGWIN__)
1874 static void
1875 set_starttype(char *starttypeopt)
1876 {
1877         if (strcmp(starttypeopt, "a") == 0 || strcmp(starttypeopt, "auto") == 0)
1878                 pgctl_start_type = SERVICE_AUTO_START;
1879         else if (strcmp(starttypeopt, "d") == 0 || strcmp(starttypeopt, "demand") == 0)
1880                 pgctl_start_type = SERVICE_DEMAND_START;
1881         else
1882         {
1883                 write_stderr(_("%s: unrecognized start type \"%s\"\n"), progname, starttypeopt);
1884                 do_advice();
1885                 exit(1);
1886         }
1887 }
1888 #endif
1889
1890 /*
1891  * adjust_data_dir
1892  *
1893  * If a configuration-only directory was specified, find the real data dir.
1894  */
1895 void
1896 adjust_data_dir(void)
1897 {
1898         char            cmd[MAXPGPATH], filename[MAXPGPATH], *my_exec_path;
1899         FILE       *fd;
1900
1901         /* If there is no postgresql.conf, it can't be a config-only dir */
1902         snprintf(filename, sizeof(filename), "%s/postgresql.conf", pg_config);
1903         if ((fd = fopen(filename, "r")) == NULL)
1904                 return;
1905         fclose(fd);
1906
1907         /* If PG_VERSION exists, it can't be a config-only dir */
1908         snprintf(filename, sizeof(filename), "%s/PG_VERSION", pg_config);
1909         if ((fd = fopen(filename, "r")) != NULL)
1910         {
1911                 fclose(fd);
1912                 return;
1913         }
1914
1915         /* Must be a configuration directory, so find the data directory */
1916
1917         /* we use a private my_exec_path to avoid interfering with later uses */
1918         if (exec_path == NULL)
1919                 my_exec_path = find_other_exec_or_die(argv0, "postgres", PG_BACKEND_VERSIONSTR);
1920         else
1921                 my_exec_path = xstrdup(exec_path);
1922
1923         snprintf(cmd, MAXPGPATH, SYSTEMQUOTE "\"%s\" %s%s -C data_directory" SYSTEMQUOTE,
1924                          my_exec_path, pgdata_opt ? pgdata_opt : "", post_opts ?
1925                          post_opts : "");
1926
1927         fd = popen(cmd, "r");
1928         if (fd == NULL || fgets(filename, sizeof(filename), fd) == NULL)
1929         {
1930                 write_stderr(_("%s: cannot find the data directory using %s\n"), progname, my_exec_path);
1931                 exit(1);
1932         }
1933         pclose(fd);
1934         free(my_exec_path);
1935
1936         /* Remove trailing newline */
1937         if (strchr(filename, '\n') != NULL)
1938                 *strchr(filename, '\n') = '\0';
1939
1940         free(pg_data);
1941         pg_data = xstrdup(filename);
1942         canonicalize_path(pg_data);
1943 }
1944
1945
1946 int
1947 main(int argc, char **argv)
1948 {
1949         static struct option long_options[] = {
1950                 {"help", no_argument, NULL, '?'},
1951                 {"version", no_argument, NULL, 'V'},
1952                 {"log", required_argument, NULL, 'l'},
1953                 {"mode", required_argument, NULL, 'm'},
1954                 {"pgdata", required_argument, NULL, 'D'},
1955                 {"silent", no_argument, NULL, 's'},
1956                 {"timeout", required_argument, NULL, 't'},
1957                 {"core-files", no_argument, NULL, 'c'},
1958                 {NULL, 0, NULL, 0}
1959         };
1960
1961         int                     option_index;
1962         int                     c;
1963         pgpid_t         killproc = 0;
1964
1965 #if defined(WIN32) || defined(__CYGWIN__)
1966         setvbuf(stderr, NULL, _IONBF, 0);
1967 #endif
1968
1969         progname = get_progname(argv[0]);
1970         set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_ctl"));
1971         start_time = time(NULL);
1972
1973         /*
1974          * save argv[0] so do_start() can look for the postmaster if necessary. we
1975          * don't look for postmaster here because in many cases we won't need it.
1976          */
1977         argv0 = argv[0];
1978
1979         umask(S_IRWXG | S_IRWXO);
1980
1981         /* support --help and --version even if invoked as root */
1982         if (argc > 1)
1983         {
1984                 if (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--help") == 0 ||
1985                         strcmp(argv[1], "-?") == 0)
1986                 {
1987                         do_help();
1988                         exit(0);
1989                 }
1990                 else if (strcmp(argv[1], "-V") == 0 || strcmp(argv[1], "--version") == 0)
1991                 {
1992                         puts("pg_ctl (PostgreSQL) " PG_VERSION);
1993                         exit(0);
1994                 }
1995         }
1996
1997         /*
1998          * Disallow running as root, to forestall any possible security holes.
1999          */
2000 #ifndef WIN32
2001         if (geteuid() == 0)
2002         {
2003                 write_stderr(_("%s: cannot be run as root\n"
2004                                            "Please log in (using, e.g., \"su\") as the "
2005                                            "(unprivileged) user that will\n"
2006                                            "own the server process.\n"),
2007                                          progname);
2008                 exit(1);
2009         }
2010 #endif
2011
2012         /*
2013          * 'Action' can be before or after args so loop over both. Some
2014          * getopt_long() implementations will reorder argv[] to place all flags
2015          * first (GNU?), but we don't rely on it. Our /port version doesn't do
2016          * that.
2017          */
2018         optind = 1;
2019
2020         /* process command-line options */
2021         while (optind < argc)
2022         {
2023                 while ((c = getopt_long(argc, argv, "cD:l:m:N:o:p:P:sS:t:U:wW", long_options, &option_index)) != -1)
2024                 {
2025                         switch (c)
2026                         {
2027                                 case 'D':
2028                                         {
2029                                                 char       *pgdata_D;
2030                                                 char       *env_var = pg_malloc(strlen(optarg) + 8);
2031
2032                                                 pgdata_D = xstrdup(optarg);
2033                                                 canonicalize_path(pgdata_D);
2034                                                 snprintf(env_var, strlen(optarg) + 8, "PGDATA=%s",
2035                                                                  pgdata_D);
2036                                                 putenv(env_var);
2037
2038                                                 /*
2039                                                  * We could pass PGDATA just in an environment
2040                                                  * variable but we do -D too for clearer postmaster
2041                                                  * 'ps' display
2042                                                  */
2043                                                 pgdata_opt = pg_malloc(strlen(pgdata_D) + 7);
2044                                                 snprintf(pgdata_opt, strlen(pgdata_D) + 7,
2045                                                                  "-D \"%s\" ",
2046                                                                  pgdata_D);
2047                                                 break;
2048                                         }
2049                                 case 'l':
2050                                         log_file = xstrdup(optarg);
2051                                         break;
2052                                 case 'm':
2053                                         set_mode(optarg);
2054                                         break;
2055                                 case 'N':
2056                                         register_servicename = xstrdup(optarg);
2057                                         break;
2058                                 case 'o':
2059                                         post_opts = xstrdup(optarg);
2060                                         break;
2061                                 case 'p':
2062                                         exec_path = xstrdup(optarg);
2063                                         break;
2064                                 case 'P':
2065                                         register_password = xstrdup(optarg);
2066                                         break;
2067                                 case 's':
2068                                         silent_mode = true;
2069                                         break;
2070                                 case 'S':
2071 #if defined(WIN32) || defined(__CYGWIN__)
2072                                         set_starttype(optarg);
2073 #else
2074                                         write_stderr(_("%s: -S option not supported on this platform\n"),
2075                                                                  progname);
2076                                         exit(1);
2077 #endif
2078                                         break;
2079                                 case 't':
2080                                         wait_seconds = atoi(optarg);
2081                                         break;
2082                                 case 'U':
2083                                         if (strchr(optarg, '\\'))
2084                                                 register_username = xstrdup(optarg);
2085                                         else
2086                                                 /* Prepend .\ for local accounts */
2087                                         {
2088                                                 register_username = malloc(strlen(optarg) + 3);
2089                                                 if (!register_username)
2090                                                 {
2091                                                         write_stderr(_("%s: out of memory\n"), progname);
2092                                                         exit(1);
2093                                                 }
2094                                                 strcpy(register_username, ".\\");
2095                                                 strcat(register_username, optarg);
2096                                         }
2097                                         break;
2098                                 case 'w':
2099                                         do_wait = true;
2100                                         wait_set = true;
2101                                         break;
2102                                 case 'W':
2103                                         do_wait = false;
2104                                         wait_set = true;
2105                                         break;
2106                                 case 'c':
2107                                         allow_core_files = true;
2108                                         break;
2109                                 default:
2110                                         /* getopt_long already issued a suitable error message */
2111                                         do_advice();
2112                                         exit(1);
2113                         }
2114                 }
2115
2116                 /* Process an action */
2117                 if (optind < argc)
2118                 {
2119                         if (ctl_command != NO_COMMAND)
2120                         {
2121                                 write_stderr(_("%s: too many command-line arguments (first is \"%s\")\n"), progname, argv[optind]);
2122                                 do_advice();
2123                                 exit(1);
2124                         }
2125
2126                         if (strcmp(argv[optind], "init") == 0
2127                                 || strcmp(argv[optind], "initdb") == 0)
2128                                 ctl_command = INIT_COMMAND;
2129                         else if (strcmp(argv[optind], "start") == 0)
2130                                 ctl_command = START_COMMAND;
2131                         else if (strcmp(argv[optind], "stop") == 0)
2132                                 ctl_command = STOP_COMMAND;
2133                         else if (strcmp(argv[optind], "restart") == 0)
2134                                 ctl_command = RESTART_COMMAND;
2135                         else if (strcmp(argv[optind], "reload") == 0)
2136                                 ctl_command = RELOAD_COMMAND;
2137                         else if (strcmp(argv[optind], "status") == 0)
2138                                 ctl_command = STATUS_COMMAND;
2139                         else if (strcmp(argv[optind], "promote") == 0)
2140                                 ctl_command = PROMOTE_COMMAND;
2141                         else if (strcmp(argv[optind], "kill") == 0)
2142                         {
2143                                 if (argc - optind < 3)
2144                                 {
2145                                         write_stderr(_("%s: missing arguments for kill mode\n"), progname);
2146                                         do_advice();
2147                                         exit(1);
2148                                 }
2149                                 ctl_command = KILL_COMMAND;
2150                                 set_sig(argv[++optind]);
2151                                 killproc = atol(argv[++optind]);
2152                         }
2153 #if defined(WIN32) || defined(__CYGWIN__)
2154                         else if (strcmp(argv[optind], "register") == 0)
2155                                 ctl_command = REGISTER_COMMAND;
2156                         else if (strcmp(argv[optind], "unregister") == 0)
2157                                 ctl_command = UNREGISTER_COMMAND;
2158                         else if (strcmp(argv[optind], "runservice") == 0)
2159                                 ctl_command = RUN_AS_SERVICE_COMMAND;
2160 #endif
2161                         else
2162                         {
2163                                 write_stderr(_("%s: unrecognized operation mode \"%s\"\n"), progname, argv[optind]);
2164                                 do_advice();
2165                                 exit(1);
2166                         }
2167                         optind++;
2168                 }
2169         }
2170
2171         if (ctl_command == NO_COMMAND)
2172         {
2173                 write_stderr(_("%s: no operation specified\n"), progname);
2174                 do_advice();
2175                 exit(1);
2176         }
2177
2178         /* Note we put any -D switch into the env var above */
2179         pg_config = getenv("PGDATA");
2180         if (pg_config)
2181         {
2182                 pg_config = xstrdup(pg_config);
2183                 canonicalize_path(pg_config);
2184                 pg_data = xstrdup(pg_config);
2185         }
2186
2187         adjust_data_dir();
2188         
2189         if (pg_config == NULL &&
2190                 ctl_command != KILL_COMMAND && ctl_command != UNREGISTER_COMMAND)
2191         {
2192                 write_stderr(_("%s: no database directory specified and environment variable PGDATA unset\n"),
2193                                          progname);
2194                 do_advice();
2195                 exit(1);
2196         }
2197
2198         if (!wait_set)
2199         {
2200                 switch (ctl_command)
2201                 {
2202                         case RESTART_COMMAND:
2203                         case START_COMMAND:
2204                                 do_wait = false;
2205                                 break;
2206                         case STOP_COMMAND:
2207                                 do_wait = true;
2208                                 break;
2209                         default:
2210                                 break;
2211                 }
2212         }
2213
2214         if (ctl_command == RELOAD_COMMAND)
2215         {
2216                 sig = SIGHUP;
2217                 do_wait = false;
2218         }
2219
2220         if (pg_data)
2221         {
2222                 snprintf(postopts_file, MAXPGPATH, "%s/postmaster.opts", pg_data);
2223                 snprintf(pid_file, MAXPGPATH, "%s/postmaster.pid", pg_data);
2224                 snprintf(backup_file, MAXPGPATH, "%s/backup_label", pg_data);
2225                 snprintf(recovery_file, MAXPGPATH, "%s/recovery.conf", pg_data);
2226                 snprintf(promote_file, MAXPGPATH, "%s/promote", pg_data);
2227         }
2228
2229         switch (ctl_command)
2230         {
2231                 case INIT_COMMAND:
2232                         do_init();
2233                         break;
2234                 case STATUS_COMMAND:
2235                         do_status();
2236                         break;
2237                 case START_COMMAND:
2238                         do_start();
2239                         break;
2240                 case STOP_COMMAND:
2241                         do_stop();
2242                         break;
2243                 case RESTART_COMMAND:
2244                         do_restart();
2245                         break;
2246                 case RELOAD_COMMAND:
2247                         do_reload();
2248                         break;
2249                 case PROMOTE_COMMAND:
2250                         do_promote();
2251                         break;
2252                 case KILL_COMMAND:
2253                         do_kill(killproc);
2254                         break;
2255 #if defined(WIN32) || defined(__CYGWIN__)
2256                 case REGISTER_COMMAND:
2257                         pgwin32_doRegister();
2258                         break;
2259                 case UNREGISTER_COMMAND:
2260                         pgwin32_doUnregister();
2261                         break;
2262                 case RUN_AS_SERVICE_COMMAND:
2263                         pgwin32_doRunAsService();
2264                         break;
2265 #endif
2266                 default:
2267                         break;
2268         }
2269
2270         exit(0);
2271 }