OSDN Git Service

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