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