LCOV - code coverage report
Current view: top level - src/bin/pg_ctl - pg_ctl.c (source / functions) Coverage Total Hit
Test: PostgreSQL 20devel Lines: 69.3 % 685 475
Test Date: 2026-09-25 23:15:50 Functions: 93.3 % 30 28
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 61.5 % 369 227

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

Generated by: LCOV version 2.0-1