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