]> granicus.if.org Git - postgresql/blob - src/backend/postmaster/postmaster.c
Add a boolean GUC parameter "bonjour" to control whether a Bonjour-enabled
[postgresql] / src / backend / postmaster / postmaster.c
1 /*-------------------------------------------------------------------------
2  *
3  * postmaster.c
4  *        This program acts as a clearing house for requests to the
5  *        POSTGRES system.      Frontend programs send a startup message
6  *        to the Postmaster and the postmaster uses the info in the
7  *        message to setup a backend process.
8  *
9  *        The postmaster also manages system-wide operations such as
10  *        startup and shutdown. The postmaster itself doesn't do those
11  *        operations, mind you --- it just forks off a subprocess to do them
12  *        at the right times.  It also takes care of resetting the system
13  *        if a backend crashes.
14  *
15  *        The postmaster process creates the shared memory and semaphore
16  *        pools during startup, but as a rule does not touch them itself.
17  *        In particular, it is not a member of the PGPROC array of backends
18  *        and so it cannot participate in lock-manager operations.      Keeping
19  *        the postmaster away from shared memory operations makes it simpler
20  *        and more reliable.  The postmaster is almost always able to recover
21  *        from crashes of individual backends by resetting shared memory;
22  *        if it did much with shared memory then it would be prone to crashing
23  *        along with the backends.
24  *
25  *        When a request message is received, we now fork() immediately.
26  *        The child process performs authentication of the request, and
27  *        then becomes a backend if successful.  This allows the auth code
28  *        to be written in a simple single-threaded style (as opposed to the
29  *        crufty "poor man's multitasking" code that used to be needed).
30  *        More importantly, it ensures that blockages in non-multithreaded
31  *        libraries like SSL or PAM cannot cause denial of service to other
32  *        clients.
33  *
34  *
35  * Portions Copyright (c) 1996-2009, PostgreSQL Global Development Group
36  * Portions Copyright (c) 1994, Regents of the University of California
37  *
38  *
39  * IDENTIFICATION
40  *        $PostgreSQL: pgsql/src/backend/postmaster/postmaster.c,v 1.596 2009/09/08 17:08:36 tgl Exp $
41  *
42  * NOTES
43  *
44  * Initialization:
45  *              The Postmaster sets up shared memory data structures
46  *              for the backends.
47  *
48  * Synchronization:
49  *              The Postmaster shares memory with the backends but should avoid
50  *              touching shared memory, so as not to become stuck if a crashing
51  *              backend screws up locks or shared memory.  Likewise, the Postmaster
52  *              should never block on messages from frontend clients.
53  *
54  * Garbage Collection:
55  *              The Postmaster cleans up after backends if they have an emergency
56  *              exit and/or core dump.
57  *
58  * Error Reporting:
59  *              Use write_stderr() only for reporting "interactive" errors
60  *              (essentially, bogus arguments on the command line).  Once the
61  *              postmaster is launched, use ereport().  In particular, don't use
62  *              write_stderr() for anything that occurs after pmdaemonize.
63  *
64  *-------------------------------------------------------------------------
65  */
66
67 #include "postgres.h"
68
69 #include <unistd.h>
70 #include <signal.h>
71 #include <time.h>
72 #include <sys/wait.h>
73 #include <ctype.h>
74 #include <sys/stat.h>
75 #include <sys/socket.h>
76 #include <fcntl.h>
77 #include <sys/param.h>
78 #include <netinet/in.h>
79 #include <arpa/inet.h>
80 #include <netdb.h>
81 #include <limits.h>
82
83 #ifdef HAVE_SYS_SELECT_H
84 #include <sys/select.h>
85 #endif
86
87 #ifdef HAVE_GETOPT_H
88 #include <getopt.h>
89 #endif
90
91 #ifdef USE_BONJOUR
92 #include <dns_sd.h>
93 #endif
94
95 #include "access/transam.h"
96 #include "access/xlog.h"
97 #include "bootstrap/bootstrap.h"
98 #include "catalog/pg_control.h"
99 #include "lib/dllist.h"
100 #include "libpq/auth.h"
101 #include "libpq/ip.h"
102 #include "libpq/libpq.h"
103 #include "libpq/pqsignal.h"
104 #include "miscadmin.h"
105 #include "pgstat.h"
106 #include "postmaster/autovacuum.h"
107 #include "postmaster/fork_process.h"
108 #include "postmaster/pgarch.h"
109 #include "postmaster/postmaster.h"
110 #include "postmaster/syslogger.h"
111 #include "storage/fd.h"
112 #include "storage/ipc.h"
113 #include "storage/pg_shmem.h"
114 #include "storage/pmsignal.h"
115 #include "storage/proc.h"
116 #include "tcop/tcopprot.h"
117 #include "utils/builtins.h"
118 #include "utils/datetime.h"
119 #include "utils/memutils.h"
120 #include "utils/ps_status.h"
121
122 #ifdef EXEC_BACKEND
123 #include "storage/spin.h"
124 #endif
125
126
127 /*
128  * List of active backends (or child processes anyway; we don't actually
129  * know whether a given child has become a backend or is still in the
130  * authorization phase).  This is used mainly to keep track of how many
131  * children we have and send them appropriate signals when necessary.
132  *
133  * "Special" children such as the startup, bgwriter and autovacuum launcher
134  * tasks are not in this list.  Autovacuum worker processes are in it.
135  * Also, "dead_end" children are in it: these are children launched just
136  * for the purpose of sending a friendly rejection message to a would-be
137  * client.      We must track them because they are attached to shared memory,
138  * but we know they will never become live backends.  dead_end children are
139  * not assigned a PMChildSlot.
140  */
141 typedef struct bkend
142 {
143         pid_t           pid;                    /* process id of backend */
144         long            cancel_key;             /* cancel key for cancels for this backend */
145         int                     child_slot;             /* PMChildSlot for this backend, if any */
146         bool            is_autovacuum;  /* is it an autovacuum process? */
147         bool            dead_end;               /* is it going to send an error and quit? */
148         Dlelem          elem;                   /* list link in BackendList */
149 } Backend;
150
151 static Dllist *BackendList;
152
153 #ifdef EXEC_BACKEND
154 static Backend *ShmemBackendArray;
155 #endif
156
157 /* The socket number we are listening for connections on */
158 int                     PostPortNumber;
159 char       *UnixSocketDir;
160 char       *ListenAddresses;
161
162 /*
163  * ReservedBackends is the number of backends reserved for superuser use.
164  * This number is taken out of the pool size given by MaxBackends so
165  * number of backend slots available to non-superusers is
166  * (MaxBackends - ReservedBackends).  Note what this really means is
167  * "if there are <= ReservedBackends connections available, only superusers
168  * can make new connections" --- pre-existing superuser connections don't
169  * count against the limit.
170  */
171 int                     ReservedBackends;
172
173 /* The socket(s) we're listening to. */
174 #define MAXLISTEN       64
175 static int      ListenSocket[MAXLISTEN];
176
177 /*
178  * Set by the -o option
179  */
180 static char ExtraOptions[MAXPGPATH];
181
182 /*
183  * These globals control the behavior of the postmaster in case some
184  * backend dumps core.  Normally, it kills all peers of the dead backend
185  * and reinitializes shared memory.  By specifying -s or -n, we can have
186  * the postmaster stop (rather than kill) peers and not reinitialize
187  * shared data structures.      (Reinit is currently dead code, though.)
188  */
189 static bool Reinit = true;
190 static int      SendStop = false;
191
192 /* still more option variables */
193 bool            EnableSSL = false;
194 bool            SilentMode = false; /* silent_mode */
195
196 int                     PreAuthDelay = 0;
197 int                     AuthenticationTimeout = 60;
198
199 bool            log_hostname;           /* for ps display and logging */
200 bool            Log_connections = false;
201 bool            Db_user_namespace = false;
202
203 bool            enable_bonjour = false;
204 char       *bonjour_name;
205
206 /* PIDs of special child processes; 0 when not running */
207 static pid_t StartupPID = 0,
208                         BgWriterPID = 0,
209                         WalWriterPID = 0,
210                         AutoVacPID = 0,
211                         PgArchPID = 0,
212                         PgStatPID = 0,
213                         SysLoggerPID = 0;
214
215 /* Startup/shutdown state */
216 #define                 NoShutdown              0
217 #define                 SmartShutdown   1
218 #define                 FastShutdown    2
219
220 static int      Shutdown = NoShutdown;
221
222 static bool FatalError = false; /* T if recovering from backend crash */
223 static bool RecoveryError = false;              /* T if WAL recovery failed */
224
225 /*
226  * We use a simple state machine to control startup, shutdown, and
227  * crash recovery (which is rather like shutdown followed by startup).
228  *
229  * After doing all the postmaster initialization work, we enter PM_STARTUP
230  * state and the startup process is launched. The startup process begins by
231  * reading the control file and other preliminary initialization steps.
232  * In a normal startup, or after crash recovery, the startup process exits
233  * with exit code 0 and we switch to PM_RUN state.  However, archive recovery
234  * is handled specially since it takes much longer and we would like to support
235  * hot standby during archive recovery.
236  *
237  * When the startup process is ready to start archive recovery, it signals the
238  * postmaster, and we switch to PM_RECOVERY state. The background writer is
239  * launched, while the startup process continues applying WAL.
240  * After reaching a consistent point in WAL redo, startup process signals
241  * us again, and we switch to PM_RECOVERY_CONSISTENT state. There's currently
242  * no difference between PM_RECOVERY and PM_RECOVERY_CONSISTENT, but we
243  * could start accepting connections to perform read-only queries at this
244  * point, if we had the infrastructure to do that.
245  * When archive recovery is finished, the startup process exits with exit
246  * code 0 and we switch to PM_RUN state.
247  *
248  * Normal child backends can only be launched when we are in PM_RUN state.
249  * (We also allow it in PM_WAIT_BACKUP state, but only for superusers.)
250  * In other states we handle connection requests by launching "dead_end"
251  * child processes, which will simply send the client an error message and
252  * quit.  (We track these in the BackendList so that we can know when they
253  * are all gone; this is important because they're still connected to shared
254  * memory, and would interfere with an attempt to destroy the shmem segment,
255  * possibly leading to SHMALL failure when we try to make a new one.)
256  * In PM_WAIT_DEAD_END state we are waiting for all the dead_end children
257  * to drain out of the system, and therefore stop accepting connection
258  * requests at all until the last existing child has quit (which hopefully
259  * will not be very long).
260  *
261  * Notice that this state variable does not distinguish *why* we entered
262  * states later than PM_RUN --- Shutdown and FatalError must be consulted
263  * to find that out.  FatalError is never true in PM_RECOVERY_* or PM_RUN
264  * states, nor in PM_SHUTDOWN states (because we don't enter those states
265  * when trying to recover from a crash).  It can be true in PM_STARTUP state,
266  * because we don't clear it until we've successfully started WAL redo.
267  * Similarly, RecoveryError means that we have crashed during recovery, and
268  * should not try to restart.
269  */
270 typedef enum
271 {
272         PM_INIT,                                        /* postmaster starting */
273         PM_STARTUP,                                     /* waiting for startup subprocess */
274         PM_RECOVERY,                            /* in archive recovery mode */
275         PM_RECOVERY_CONSISTENT,         /* consistent recovery mode */
276         PM_RUN,                                         /* normal "database is alive" state */
277         PM_WAIT_BACKUP,                         /* waiting for online backup mode to end */
278         PM_WAIT_BACKENDS,                       /* waiting for live backends to exit */
279         PM_SHUTDOWN,                            /* waiting for bgwriter to do shutdown ckpt */
280         PM_SHUTDOWN_2,                          /* waiting for archiver to finish */
281         PM_WAIT_DEAD_END,                       /* waiting for dead_end children to exit */
282         PM_NO_CHILDREN                          /* all important children have exited */
283 } PMState;
284
285 static PMState pmState = PM_INIT;
286
287 bool            ClientAuthInProgress = false;           /* T during new-client
288                                                                                                  * authentication */
289
290 bool            redirection_done = false;       /* stderr redirected for syslogger? */
291
292 /* received START_AUTOVAC_LAUNCHER signal */
293 static volatile sig_atomic_t start_autovac_launcher = false;
294 /* the launcher needs to be signalled to communicate some condition */
295 static volatile bool            avlauncher_needs_signal = false;
296
297 /*
298  * State for assigning random salts and cancel keys.
299  * Also, the global MyCancelKey passes the cancel key assigned to a given
300  * backend from the postmaster to that backend (via fork).
301  */
302 static unsigned int random_seed = 0;
303 static struct timeval random_start_time;
304
305 extern char *optarg;
306 extern int      optind,
307                         opterr;
308
309 #ifdef HAVE_INT_OPTRESET
310 extern int      optreset;                       /* might not be declared by system headers */
311 #endif
312
313 #ifdef USE_BONJOUR
314 static DNSServiceRef bonjour_sdref = NULL;
315 #endif
316
317 /*
318  * postmaster.c - function prototypes
319  */
320 static void getInstallationPaths(const char *argv0);
321 static void checkDataDir(void);
322 static void pmdaemonize(void);
323 static Port *ConnCreate(int serverFd);
324 static void ConnFree(Port *port);
325 static void reset_shared(int port);
326 static void SIGHUP_handler(SIGNAL_ARGS);
327 static void pmdie(SIGNAL_ARGS);
328 static void reaper(SIGNAL_ARGS);
329 static void sigusr1_handler(SIGNAL_ARGS);
330 static void startup_die(SIGNAL_ARGS);
331 static void dummy_handler(SIGNAL_ARGS);
332 static void CleanupBackend(int pid, int exitstatus);
333 static void HandleChildCrash(int pid, int exitstatus, const char *procname);
334 static void LogChildExit(int lev, const char *procname,
335                          int pid, int exitstatus);
336 static void PostmasterStateMachine(void);
337 static void BackendInitialize(Port *port);
338 static int      BackendRun(Port *port);
339 static void ExitPostmaster(int status);
340 static int      ServerLoop(void);
341 static int      BackendStartup(Port *port);
342 static int      ProcessStartupPacket(Port *port, bool SSLdone);
343 static void processCancelRequest(Port *port, void *pkt);
344 static int      initMasks(fd_set *rmask);
345 static void report_fork_failure_to_client(Port *port, int errnum);
346 static enum CAC_state canAcceptConnections(void);
347 static long PostmasterRandom(void);
348 static void RandomSalt(char *md5Salt);
349 static void signal_child(pid_t pid, int signal);
350 static void SignalSomeChildren(int signal, bool only_autovac);
351
352 #define SignalChildren(sig)                     SignalSomeChildren(sig, false)
353 #define SignalAutovacWorkers(sig)       SignalSomeChildren(sig, true)
354 static int      CountChildren(void);
355 static bool CreateOptsFile(int argc, char *argv[], char *fullprogname);
356 static pid_t StartChildProcess(AuxProcType type);
357 static void StartAutovacuumWorker(void);
358
359 #ifdef EXEC_BACKEND
360
361 #ifdef WIN32
362 static pid_t win32_waitpid(int *exitstatus);
363 static void WINAPI pgwin32_deadchild_callback(PVOID lpParameter, BOOLEAN TimerOrWaitFired);
364
365 static HANDLE win32ChildQueue;
366
367 typedef struct
368 {
369         HANDLE          waitHandle;
370         HANDLE          procHandle;
371         DWORD           procId;
372 } win32_deadchild_waitinfo;
373
374 HANDLE          PostmasterHandle;
375 #endif
376
377 static pid_t backend_forkexec(Port *port);
378 static pid_t internal_forkexec(int argc, char *argv[], Port *port);
379
380 /* Type for a socket that can be inherited to a client process */
381 #ifdef WIN32
382 typedef struct
383 {
384         SOCKET          origsocket;             /* Original socket value, or -1 if not a
385                                                                  * socket */
386         WSAPROTOCOL_INFO wsainfo;
387 } InheritableSocket;
388 #else
389 typedef int InheritableSocket;
390 #endif
391
392 typedef struct LWLock LWLock;   /* ugly kluge */
393
394 /*
395  * Structure contains all variables passed to exec:ed backends
396  */
397 typedef struct
398 {
399         Port            port;
400         InheritableSocket portsocket;
401         char            DataDir[MAXPGPATH];
402         int                     ListenSocket[MAXLISTEN];
403         long            MyCancelKey;
404         int                     MyPMChildSlot;
405         unsigned long UsedShmemSegID;
406         void       *UsedShmemSegAddr;
407         slock_t    *ShmemLock;
408         VariableCache ShmemVariableCache;
409         Backend    *ShmemBackendArray;
410         LWLock     *LWLockArray;
411         slock_t    *ProcStructLock;
412         PROC_HDR   *ProcGlobal;
413         PGPROC     *AuxiliaryProcs;
414         PMSignalData *PMSignalState;
415         InheritableSocket pgStatSock;
416         pid_t           PostmasterPid;
417         TimestampTz PgStartTime;
418         TimestampTz PgReloadTime;
419         bool            redirection_done;
420 #ifdef WIN32
421         HANDLE          PostmasterHandle;
422         HANDLE          initial_signal_pipe;
423         HANDLE          syslogPipe[2];
424 #else
425         int                     syslogPipe[2];
426 #endif
427         char            my_exec_path[MAXPGPATH];
428         char            pkglib_path[MAXPGPATH];
429         char            ExtraOptions[MAXPGPATH];
430 } BackendParameters;
431
432 static void read_backend_variables(char *id, Port *port);
433 static void restore_backend_variables(BackendParameters *param, Port *port);
434
435 #ifndef WIN32
436 static bool save_backend_variables(BackendParameters *param, Port *port);
437 #else
438 static bool save_backend_variables(BackendParameters *param, Port *port,
439                                            HANDLE childProcess, pid_t childPid);
440 #endif
441
442 static void ShmemBackendArrayAdd(Backend *bn);
443 static void ShmemBackendArrayRemove(Backend *bn);
444 #endif   /* EXEC_BACKEND */
445
446 #define StartupDataBase()               StartChildProcess(StartupProcess)
447 #define StartBackgroundWriter() StartChildProcess(BgWriterProcess)
448 #define StartWalWriter()                StartChildProcess(WalWriterProcess)
449
450 /* Macros to check exit status of a child process */
451 #define EXIT_STATUS_0(st)  ((st) == 0)
452 #define EXIT_STATUS_1(st)  (WIFEXITED(st) && WEXITSTATUS(st) == 1)
453
454
455 /*
456  * Postmaster main entry point
457  */
458 int
459 PostmasterMain(int argc, char *argv[])
460 {
461         int                     opt;
462         int                     status;
463         char       *userDoption = NULL;
464         int                     i;
465
466         MyProcPid = PostmasterPid = getpid();
467
468         MyStartTime = time(NULL);
469
470         IsPostmasterEnvironment = true;
471
472         /*
473          * for security, no dir or file created can be group or other accessible
474          */
475         umask((mode_t) 0077);
476
477         /*
478          * Fire up essential subsystems: memory management
479          */
480         MemoryContextInit();
481
482         /*
483          * By default, palloc() requests in the postmaster will be allocated in
484          * the PostmasterContext, which is space that can be recycled by backends.
485          * Allocated data that needs to be available to backends should be
486          * allocated in TopMemoryContext.
487          */
488         PostmasterContext = AllocSetContextCreate(TopMemoryContext,
489                                                                                           "Postmaster",
490                                                                                           ALLOCSET_DEFAULT_MINSIZE,
491                                                                                           ALLOCSET_DEFAULT_INITSIZE,
492                                                                                           ALLOCSET_DEFAULT_MAXSIZE);
493         MemoryContextSwitchTo(PostmasterContext);
494
495         /* Initialize paths to installation files */
496         getInstallationPaths(argv[0]);
497
498         /*
499          * Options setup
500          */
501         InitializeGUCOptions();
502
503         opterr = 1;
504
505         /*
506          * Parse command-line options.  CAUTION: keep this in sync with
507          * tcop/postgres.c (the option sets should not conflict) and with the
508          * common help() function in main/main.c.
509          */
510         while ((opt = getopt(argc, argv, "A:B:c:D:d:EeFf:h:ijk:lN:nOo:Pp:r:S:sTt:W:-:")) != -1)
511         {
512                 switch (opt)
513                 {
514                         case 'A':
515                                 SetConfigOption("debug_assertions", optarg, PGC_POSTMASTER, PGC_S_ARGV);
516                                 break;
517
518                         case 'B':
519                                 SetConfigOption("shared_buffers", optarg, PGC_POSTMASTER, PGC_S_ARGV);
520                                 break;
521
522                         case 'D':
523                                 userDoption = optarg;
524                                 break;
525
526                         case 'd':
527                                 set_debug_options(atoi(optarg), PGC_POSTMASTER, PGC_S_ARGV);
528                                 break;
529
530                         case 'E':
531                                 SetConfigOption("log_statement", "all", PGC_POSTMASTER, PGC_S_ARGV);
532                                 break;
533
534                         case 'e':
535                                 SetConfigOption("datestyle", "euro", PGC_POSTMASTER, PGC_S_ARGV);
536                                 break;
537
538                         case 'F':
539                                 SetConfigOption("fsync", "false", PGC_POSTMASTER, PGC_S_ARGV);
540                                 break;
541
542                         case 'f':
543                                 if (!set_plan_disabling_options(optarg, PGC_POSTMASTER, PGC_S_ARGV))
544                                 {
545                                         write_stderr("%s: invalid argument for option -f: \"%s\"\n",
546                                                                  progname, optarg);
547                                         ExitPostmaster(1);
548                                 }
549                                 break;
550
551                         case 'h':
552                                 SetConfigOption("listen_addresses", optarg, PGC_POSTMASTER, PGC_S_ARGV);
553                                 break;
554
555                         case 'i':
556                                 SetConfigOption("listen_addresses", "*", PGC_POSTMASTER, PGC_S_ARGV);
557                                 break;
558
559                         case 'j':
560                                 /* only used by interactive backend */
561                                 break;
562
563                         case 'k':
564                                 SetConfigOption("unix_socket_directory", optarg, PGC_POSTMASTER, PGC_S_ARGV);
565                                 break;
566
567                         case 'l':
568                                 SetConfigOption("ssl", "true", PGC_POSTMASTER, PGC_S_ARGV);
569                                 break;
570
571                         case 'N':
572                                 SetConfigOption("max_connections", optarg, PGC_POSTMASTER, PGC_S_ARGV);
573                                 break;
574
575                         case 'n':
576                                 /* Don't reinit shared mem after abnormal exit */
577                                 Reinit = false;
578                                 break;
579
580                         case 'O':
581                                 SetConfigOption("allow_system_table_mods", "true", PGC_POSTMASTER, PGC_S_ARGV);
582                                 break;
583
584                         case 'o':
585                                 /* Other options to pass to the backend on the command line */
586                                 snprintf(ExtraOptions + strlen(ExtraOptions),
587                                                  sizeof(ExtraOptions) - strlen(ExtraOptions),
588                                                  " %s", optarg);
589                                 break;
590
591                         case 'P':
592                                 SetConfigOption("ignore_system_indexes", "true", PGC_POSTMASTER, PGC_S_ARGV);
593                                 break;
594
595                         case 'p':
596                                 SetConfigOption("port", optarg, PGC_POSTMASTER, PGC_S_ARGV);
597                                 break;
598
599                         case 'r':
600                                 /* only used by single-user backend */
601                                 break;
602
603                         case 'S':
604                                 SetConfigOption("work_mem", optarg, PGC_POSTMASTER, PGC_S_ARGV);
605                                 break;
606
607                         case 's':
608                                 SetConfigOption("log_statement_stats", "true", PGC_POSTMASTER, PGC_S_ARGV);
609                                 break;
610
611                         case 'T':
612
613                                 /*
614                                  * In the event that some backend dumps core, send SIGSTOP,
615                                  * rather than SIGQUIT, to all its peers.  This lets the wily
616                                  * post_hacker collect core dumps from everyone.
617                                  */
618                                 SendStop = true;
619                                 break;
620
621                         case 't':
622                                 {
623                                         const char *tmp = get_stats_option_name(optarg);
624
625                                         if (tmp)
626                                         {
627                                                 SetConfigOption(tmp, "true", PGC_POSTMASTER, PGC_S_ARGV);
628                                         }
629                                         else
630                                         {
631                                                 write_stderr("%s: invalid argument for option -t: \"%s\"\n",
632                                                                          progname, optarg);
633                                                 ExitPostmaster(1);
634                                         }
635                                         break;
636                                 }
637
638                         case 'W':
639                                 SetConfigOption("post_auth_delay", optarg, PGC_POSTMASTER, PGC_S_ARGV);
640                                 break;
641
642                         case 'c':
643                         case '-':
644                                 {
645                                         char       *name,
646                                                            *value;
647
648                                         ParseLongOption(optarg, &name, &value);
649                                         if (!value)
650                                         {
651                                                 if (opt == '-')
652                                                         ereport(ERROR,
653                                                                         (errcode(ERRCODE_SYNTAX_ERROR),
654                                                                          errmsg("--%s requires a value",
655                                                                                         optarg)));
656                                                 else
657                                                         ereport(ERROR,
658                                                                         (errcode(ERRCODE_SYNTAX_ERROR),
659                                                                          errmsg("-c %s requires a value",
660                                                                                         optarg)));
661                                         }
662
663                                         SetConfigOption(name, value, PGC_POSTMASTER, PGC_S_ARGV);
664                                         free(name);
665                                         if (value)
666                                                 free(value);
667                                         break;
668                                 }
669
670                         default:
671                                 write_stderr("Try \"%s --help\" for more information.\n",
672                                                          progname);
673                                 ExitPostmaster(1);
674                 }
675         }
676
677         /*
678          * Postmaster accepts no non-option switch arguments.
679          */
680         if (optind < argc)
681         {
682                 write_stderr("%s: invalid argument: \"%s\"\n",
683                                          progname, argv[optind]);
684                 write_stderr("Try \"%s --help\" for more information.\n",
685                                          progname);
686                 ExitPostmaster(1);
687         }
688
689         /*
690          * Locate the proper configuration files and data directory, and read
691          * postgresql.conf for the first time.
692          */
693         if (!SelectConfigFiles(userDoption, progname))
694                 ExitPostmaster(2);
695
696         /* Verify that DataDir looks reasonable */
697         checkDataDir();
698
699         /* And switch working directory into it */
700         ChangeToDataDir();
701
702         /*
703          * Check for invalid combinations of GUC settings.
704          */
705         if (ReservedBackends >= MaxBackends)
706         {
707                 write_stderr("%s: superuser_reserved_connections must be less than max_connections\n", progname);
708                 ExitPostmaster(1);
709         }
710
711         /*
712          * Other one-time internal sanity checks can go here, if they are fast.
713          * (Put any slow processing further down, after postmaster.pid creation.)
714          */
715         if (!CheckDateTokenTables())
716         {
717                 write_stderr("%s: invalid datetoken tables, please fix\n", progname);
718                 ExitPostmaster(1);
719         }
720
721         /*
722          * Now that we are done processing the postmaster arguments, reset
723          * getopt(3) library so that it will work correctly in subprocesses.
724          */
725         optind = 1;
726 #ifdef HAVE_INT_OPTRESET
727         optreset = 1;                           /* some systems need this too */
728 #endif
729
730         /* For debugging: display postmaster environment */
731         {
732                 extern char **environ;
733                 char      **p;
734
735                 ereport(DEBUG3,
736                                 (errmsg_internal("%s: PostmasterMain: initial environ dump:",
737                                                                  progname)));
738                 ereport(DEBUG3,
739                          (errmsg_internal("-----------------------------------------")));
740                 for (p = environ; *p; ++p)
741                         ereport(DEBUG3,
742                                         (errmsg_internal("\t%s", *p)));
743                 ereport(DEBUG3,
744                          (errmsg_internal("-----------------------------------------")));
745         }
746
747         /*
748          * Fork away from controlling terminal, if silent_mode specified.
749          *
750          * Must do this before we grab any interlock files, else the interlocks
751          * will show the wrong PID.
752          */
753         if (SilentMode)
754                 pmdaemonize();
755
756         /*
757          * Create lockfile for data directory.
758          *
759          * We want to do this before we try to grab the input sockets, because the
760          * data directory interlock is more reliable than the socket-file
761          * interlock (thanks to whoever decided to put socket files in /tmp :-().
762          * For the same reason, it's best to grab the TCP socket(s) before the
763          * Unix socket.
764          */
765         CreateDataDirLockFile(true);
766
767         /*
768          * If timezone is not set, determine what the OS uses.  (In theory this
769          * should be done during GUC initialization, but because it can take as
770          * much as several seconds, we delay it until after we've created the
771          * postmaster.pid file.  This prevents problems with boot scripts that
772          * expect the pidfile to appear quickly.  Also, we avoid problems with
773          * trying to locate the timezone files too early in initialization.)
774          */
775         pg_timezone_initialize();
776
777         /*
778          * Likewise, init timezone_abbreviations if not already set.
779          */
780         pg_timezone_abbrev_initialize();
781
782         /*
783          * Initialize SSL library, if specified.
784          */
785 #ifdef USE_SSL
786         if (EnableSSL)
787                 secure_initialize();
788 #endif
789
790         /*
791          * process any libraries that should be preloaded at postmaster start
792          */
793         process_shared_preload_libraries();
794
795         /*
796          * Remove old temporary files.  At this point there can be no other
797          * Postgres processes running in this directory, so this should be safe.
798          */
799         RemovePgTempFiles();
800
801         /*
802          * Establish input sockets.
803          */
804         for (i = 0; i < MAXLISTEN; i++)
805                 ListenSocket[i] = -1;
806
807         if (ListenAddresses)
808         {
809                 char       *rawstring;
810                 List       *elemlist;
811                 ListCell   *l;
812                 int                     success = 0;
813
814                 /* Need a modifiable copy of ListenAddresses */
815                 rawstring = pstrdup(ListenAddresses);
816
817                 /* Parse string into list of identifiers */
818                 if (!SplitIdentifierString(rawstring, ',', &elemlist))
819                 {
820                         /* syntax error in list */
821                         ereport(FATAL,
822                                         (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
823                                          errmsg("invalid list syntax for \"listen_addresses\"")));
824                 }
825
826                 foreach(l, elemlist)
827                 {
828                         char       *curhost = (char *) lfirst(l);
829
830                         if (strcmp(curhost, "*") == 0)
831                                 status = StreamServerPort(AF_UNSPEC, NULL,
832                                                                                   (unsigned short) PostPortNumber,
833                                                                                   UnixSocketDir,
834                                                                                   ListenSocket, MAXLISTEN);
835                         else
836                                 status = StreamServerPort(AF_UNSPEC, curhost,
837                                                                                   (unsigned short) PostPortNumber,
838                                                                                   UnixSocketDir,
839                                                                                   ListenSocket, MAXLISTEN);
840                         if (status == STATUS_OK)
841                                 success++;
842                         else
843                                 ereport(WARNING,
844                                                 (errmsg("could not create listen socket for \"%s\"",
845                                                                 curhost)));
846                 }
847
848                 if (!success && list_length(elemlist))
849                         ereport(FATAL,
850                                         (errmsg("could not create any TCP/IP sockets")));
851
852                 list_free(elemlist);
853                 pfree(rawstring);
854         }
855
856 #ifdef USE_BONJOUR
857         /* Register for Bonjour only if we opened TCP socket(s) */
858         if (enable_bonjour && ListenSocket[0] != -1)
859         {
860                 DNSServiceErrorType err;
861
862                 /*
863                  * We pass 0 for interface_index, which will result in registering on
864                  * all "applicable" interfaces.  It's not entirely clear from the
865                  * DNS-SD docs whether this would be appropriate if we have bound to
866                  * just a subset of the available network interfaces.
867                  */
868                 err = DNSServiceRegister(&bonjour_sdref,
869                                                                  0,
870                                                                  0,
871                                                                  bonjour_name,
872                                                                  "_postgresql._tcp.",
873                                                                  NULL,
874                                                                  NULL,
875                                                                  htons(PostPortNumber),
876                                                                  0,
877                                                                  NULL,
878                                                                  NULL,
879                                                                  NULL);
880                 if (err != kDNSServiceErr_NoError)
881                         elog(LOG, "DNSServiceRegister() failed: error code %ld",
882                                  (long) err);
883                 /*
884                  * We don't bother to read the mDNS daemon's reply, and we expect
885                  * that it will automatically terminate our registration when the
886                  * socket is closed at postmaster termination.  So there's nothing
887                  * more to be done here.  However, the bonjour_sdref is kept around
888                  * so that forked children can close their copies of the socket.
889                  */
890         }
891 #endif
892
893 #ifdef HAVE_UNIX_SOCKETS
894         status = StreamServerPort(AF_UNIX, NULL,
895                                                           (unsigned short) PostPortNumber,
896                                                           UnixSocketDir,
897                                                           ListenSocket, MAXLISTEN);
898         if (status != STATUS_OK)
899                 ereport(WARNING,
900                                 (errmsg("could not create Unix-domain socket")));
901 #endif
902
903         /*
904          * check that we have some socket to listen on
905          */
906         if (ListenSocket[0] == -1)
907                 ereport(FATAL,
908                                 (errmsg("no socket created for listening")));
909
910         /*
911          * Set up shared memory and semaphores.
912          */
913         reset_shared(PostPortNumber);
914
915         /*
916          * Estimate number of openable files.  This must happen after setting up
917          * semaphores, because on some platforms semaphores count as open files.
918          */
919         set_max_safe_fds();
920
921         /*
922          * Initialize the list of active backends.
923          */
924         BackendList = DLNewList();
925
926 #ifdef WIN32
927
928         /*
929          * Initialize I/O completion port used to deliver list of dead children.
930          */
931         win32ChildQueue = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 1);
932         if (win32ChildQueue == NULL)
933                 ereport(FATAL,
934                    (errmsg("could not create I/O completion port for child queue")));
935
936         /*
937          * Set up a handle that child processes can use to check whether the
938          * postmaster is still running.
939          */
940         if (DuplicateHandle(GetCurrentProcess(),
941                                                 GetCurrentProcess(),
942                                                 GetCurrentProcess(),
943                                                 &PostmasterHandle,
944                                                 0,
945                                                 TRUE,
946                                                 DUPLICATE_SAME_ACCESS) == 0)
947                 ereport(FATAL,
948                                 (errmsg_internal("could not duplicate postmaster handle: error code %d",
949                                                                  (int) GetLastError())));
950 #endif
951
952         /*
953          * Record postmaster options.  We delay this till now to avoid recording
954          * bogus options (eg, NBuffers too high for available memory).
955          */
956         if (!CreateOptsFile(argc, argv, my_exec_path))
957                 ExitPostmaster(1);
958
959 #ifdef EXEC_BACKEND
960         /* Write out nondefault GUC settings for child processes to use */
961         write_nondefault_variables(PGC_POSTMASTER);
962 #endif
963
964         /*
965          * Write the external PID file if requested
966          */
967         if (external_pid_file)
968         {
969                 FILE       *fpidfile = fopen(external_pid_file, "w");
970
971                 if (fpidfile)
972                 {
973                         fprintf(fpidfile, "%d\n", MyProcPid);
974                         fclose(fpidfile);
975                         /* Should we remove the pid file on postmaster exit? */
976                 }
977                 else
978                         write_stderr("%s: could not write external PID file \"%s\": %s\n",
979                                                  progname, external_pid_file, strerror(errno));
980         }
981
982         /*
983          * Set up signal handlers for the postmaster process.
984          *
985          * CAUTION: when changing this list, check for side-effects on the signal
986          * handling setup of child processes.  See tcop/postgres.c,
987          * bootstrap/bootstrap.c, postmaster/bgwriter.c, postmaster/walwriter.c,
988          * postmaster/autovacuum.c, postmaster/pgarch.c, postmaster/pgstat.c, and
989          * postmaster/syslogger.c.
990          */
991         pqinitmask();
992         PG_SETMASK(&BlockSig);
993
994         pqsignal(SIGHUP, SIGHUP_handler);       /* reread config file and have
995                                                                                  * children do same */
996         pqsignal(SIGINT, pmdie);        /* send SIGTERM and shut down */
997         pqsignal(SIGQUIT, pmdie);       /* send SIGQUIT and die */
998         pqsignal(SIGTERM, pmdie);       /* wait for children and shut down */
999         pqsignal(SIGALRM, SIG_IGN); /* ignored */
1000         pqsignal(SIGPIPE, SIG_IGN); /* ignored */
1001         pqsignal(SIGUSR1, sigusr1_handler); /* message from child process */
1002         pqsignal(SIGUSR2, dummy_handler);       /* unused, reserve for children */
1003         pqsignal(SIGCHLD, reaper);      /* handle child termination */
1004         pqsignal(SIGTTIN, SIG_IGN); /* ignored */
1005         pqsignal(SIGTTOU, SIG_IGN); /* ignored */
1006         /* ignore SIGXFSZ, so that ulimit violations work like disk full */
1007 #ifdef SIGXFSZ
1008         pqsignal(SIGXFSZ, SIG_IGN); /* ignored */
1009 #endif
1010
1011         /*
1012          * If enabled, start up syslogger collection subprocess
1013          */
1014         SysLoggerPID = SysLogger_Start();
1015
1016         /*
1017          * Reset whereToSendOutput from DestDebug (its starting state) to
1018          * DestNone. This stops ereport from sending log messages to stderr unless
1019          * Log_destination permits.  We don't do this until the postmaster is
1020          * fully launched, since startup failures may as well be reported to
1021          * stderr.
1022          */
1023         whereToSendOutput = DestNone;
1024
1025         /*
1026          * Initialize stats collection subsystem (this does NOT start the
1027          * collector process!)
1028          */
1029         pgstat_init();
1030
1031         /*
1032          * Initialize the autovacuum subsystem (again, no process start yet)
1033          */
1034         autovac_init();
1035
1036         /*
1037          * Load configuration files for client authentication.
1038          */
1039         if (!load_hba())
1040         {
1041                 /*
1042                  * It makes no sense to continue if we fail to load the HBA file,
1043                  * since there is no way to connect to the database in this case.
1044                  */
1045                 ereport(FATAL,
1046                                 (errmsg("could not load pg_hba.conf")));
1047         }
1048         load_ident();
1049
1050         /*
1051          * Remember postmaster startup time
1052          */
1053         PgStartTime = GetCurrentTimestamp();
1054         /* PostmasterRandom wants its own copy */
1055         gettimeofday(&random_start_time, NULL);
1056
1057         /*
1058          * We're ready to rock and roll...
1059          */
1060         StartupPID = StartupDataBase();
1061         Assert(StartupPID != 0);
1062         pmState = PM_STARTUP;
1063
1064         status = ServerLoop();
1065
1066         /*
1067          * ServerLoop probably shouldn't ever return, but if it does, close down.
1068          */
1069         ExitPostmaster(status != STATUS_OK);
1070
1071         return 0;                                       /* not reached */
1072 }
1073
1074
1075 /*
1076  * Compute and check the directory paths to files that are part of the
1077  * installation (as deduced from the postgres executable's own location)
1078  */
1079 static void
1080 getInstallationPaths(const char *argv0)
1081 {
1082         DIR                *pdir;
1083
1084         /* Locate the postgres executable itself */
1085         if (find_my_exec(argv0, my_exec_path) < 0)
1086                 elog(FATAL, "%s: could not locate my own executable path", argv0);
1087
1088 #ifdef EXEC_BACKEND
1089         /* Locate executable backend before we change working directory */
1090         if (find_other_exec(argv0, "postgres", PG_BACKEND_VERSIONSTR,
1091                                                 postgres_exec_path) < 0)
1092                 ereport(FATAL,
1093                                 (errmsg("%s: could not locate matching postgres executable",
1094                                                 argv0)));
1095 #endif
1096
1097         /*
1098          * Locate the pkglib directory --- this has to be set early in case we try
1099          * to load any modules from it in response to postgresql.conf entries.
1100          */
1101         get_pkglib_path(my_exec_path, pkglib_path);
1102
1103         /*
1104          * Verify that there's a readable directory there; otherwise the Postgres
1105          * installation is incomplete or corrupt.  (A typical cause of this
1106          * failure is that the postgres executable has been moved or hardlinked to
1107          * some directory that's not a sibling of the installation lib/
1108          * directory.)
1109          */
1110         pdir = AllocateDir(pkglib_path);
1111         if (pdir == NULL)
1112                 ereport(ERROR,
1113                                 (errcode_for_file_access(),
1114                                  errmsg("could not open directory \"%s\": %m",
1115                                                 pkglib_path),
1116                                  errhint("This may indicate an incomplete PostgreSQL installation, or that the file \"%s\" has been moved away from its proper location.",
1117                                                  my_exec_path)));
1118         FreeDir(pdir);
1119
1120         /*
1121          * XXX is it worth similarly checking the share/ directory?  If the lib/
1122          * directory is there, then share/ probably is too.
1123          */
1124 }
1125
1126
1127 /*
1128  * Validate the proposed data directory
1129  */
1130 static void
1131 checkDataDir(void)
1132 {
1133         char            path[MAXPGPATH];
1134         FILE       *fp;
1135         struct stat stat_buf;
1136
1137         Assert(DataDir);
1138
1139         if (stat(DataDir, &stat_buf) != 0)
1140         {
1141                 if (errno == ENOENT)
1142                         ereport(FATAL,
1143                                         (errcode_for_file_access(),
1144                                          errmsg("data directory \"%s\" does not exist",
1145                                                         DataDir)));
1146                 else
1147                         ereport(FATAL,
1148                                         (errcode_for_file_access(),
1149                                  errmsg("could not read permissions of directory \"%s\": %m",
1150                                                 DataDir)));
1151         }
1152
1153         /* eventual chdir would fail anyway, but let's test ... */
1154         if (!S_ISDIR(stat_buf.st_mode))
1155                 ereport(FATAL,
1156                                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1157                                  errmsg("specified data directory \"%s\" is not a directory",
1158                                                 DataDir)));
1159
1160         /*
1161          * Check that the directory belongs to my userid; if not, reject.
1162          *
1163          * This check is an essential part of the interlock that prevents two
1164          * postmasters from starting in the same directory (see CreateLockFile()).
1165          * Do not remove or weaken it.
1166          *
1167          * XXX can we safely enable this check on Windows?
1168          */
1169 #if !defined(WIN32) && !defined(__CYGWIN__)
1170         if (stat_buf.st_uid != geteuid())
1171                 ereport(FATAL,
1172                                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1173                                  errmsg("data directory \"%s\" has wrong ownership",
1174                                                 DataDir),
1175                                  errhint("The server must be started by the user that owns the data directory.")));
1176 #endif
1177
1178         /*
1179          * Check if the directory has group or world access.  If so, reject.
1180          *
1181          * It would be possible to allow weaker constraints (for example, allow
1182          * group access) but we cannot make a general assumption that that is
1183          * okay; for example there are platforms where nearly all users
1184          * customarily belong to the same group.  Perhaps this test should be
1185          * configurable.
1186          *
1187          * XXX temporarily suppress check when on Windows, because there may not
1188          * be proper support for Unix-y file permissions.  Need to think of a
1189          * reasonable check to apply on Windows.
1190          */
1191 #if !defined(WIN32) && !defined(__CYGWIN__)
1192         if (stat_buf.st_mode & (S_IRWXG | S_IRWXO))
1193                 ereport(FATAL,
1194                                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1195                                  errmsg("data directory \"%s\" has group or world access",
1196                                                 DataDir),
1197                                  errdetail("Permissions should be u=rwx (0700).")));
1198 #endif
1199
1200         /* Look for PG_VERSION before looking for pg_control */
1201         ValidatePgVersion(DataDir);
1202
1203         snprintf(path, sizeof(path), "%s/global/pg_control", DataDir);
1204
1205         fp = AllocateFile(path, PG_BINARY_R);
1206         if (fp == NULL)
1207         {
1208                 write_stderr("%s: could not find the database system\n"
1209                                          "Expected to find it in the directory \"%s\",\n"
1210                                          "but could not open file \"%s\": %s\n",
1211                                          progname, DataDir, path, strerror(errno));
1212                 ExitPostmaster(2);
1213         }
1214         FreeFile(fp);
1215 }
1216
1217
1218 /*
1219  * Fork away from the controlling terminal (silent_mode option)
1220  *
1221  * Since this requires disconnecting from stdin/stdout/stderr (in case they're
1222  * linked to the terminal), we re-point stdin to /dev/null and stdout/stderr
1223  * to "postmaster.log" in the data directory, where we're already chdir'd.
1224  */
1225 static void
1226 pmdaemonize(void)
1227 {
1228 #ifndef WIN32
1229         const char *pmlogname = "postmaster.log";
1230         int                     dvnull;
1231         int                     pmlog;
1232         pid_t           pid;
1233         int                     res;
1234
1235         /*
1236          * Make sure we can open the files we're going to redirect to.  If this
1237          * fails, we want to complain before disconnecting.  Mention the full path
1238          * of the logfile in the error message, even though we address it by
1239          * relative path.
1240          */
1241         dvnull = open(DEVNULL, O_RDONLY, 0);
1242         if (dvnull < 0)
1243         {
1244                 write_stderr("%s: could not open file \"%s\": %s\n",
1245                                          progname, DEVNULL, strerror(errno));
1246                 ExitPostmaster(1);
1247         }
1248         pmlog = open(pmlogname, O_CREAT | O_WRONLY | O_APPEND, 0600);
1249         if (pmlog < 0)
1250         {
1251                 write_stderr("%s: could not open log file \"%s/%s\": %s\n",
1252                                          progname, DataDir, pmlogname, strerror(errno));
1253                 ExitPostmaster(1);
1254         }
1255
1256         /*
1257          * Okay to fork.
1258          */
1259         pid = fork_process();
1260         if (pid == (pid_t) -1)
1261         {
1262                 write_stderr("%s: could not fork background process: %s\n",
1263                                          progname, strerror(errno));
1264                 ExitPostmaster(1);
1265         }
1266         else if (pid)
1267         {                                                       /* parent */
1268                 /* Parent should just exit, without doing any atexit cleanup */
1269                 _exit(0);
1270         }
1271
1272         MyProcPid = PostmasterPid = getpid();           /* reset PID vars to child */
1273
1274         MyStartTime = time(NULL);
1275
1276         /*
1277          * Some systems use setsid() to dissociate from the TTY's process group,
1278          * while on others it depends on stdin/stdout/stderr.  Do both if possible.
1279          */
1280 #ifdef HAVE_SETSID
1281         if (setsid() < 0)
1282         {
1283                 write_stderr("%s: could not dissociate from controlling TTY: %s\n",
1284                                          progname, strerror(errno));
1285                 ExitPostmaster(1);
1286         }
1287 #endif
1288
1289         /*
1290          * Reassociate stdin/stdout/stderr.  fork_process() cleared any pending
1291          * output, so this should be safe.  The only plausible error is EINTR,
1292          * which just means we should retry.
1293          */
1294         do {
1295                 res = dup2(dvnull, 0);
1296         } while (res < 0 && errno == EINTR);
1297         close(dvnull);
1298         do {
1299                 res = dup2(pmlog, 1);
1300         } while (res < 0 && errno == EINTR);
1301         do {
1302                 res = dup2(pmlog, 2);
1303         } while (res < 0 && errno == EINTR);
1304         close(pmlog);
1305 #else                                                   /* WIN32 */
1306         /* not supported */
1307         elog(FATAL, "silent_mode is not supported under Windows");
1308 #endif   /* WIN32 */
1309 }
1310
1311
1312 /*
1313  * Main idle loop of postmaster
1314  */
1315 static int
1316 ServerLoop(void)
1317 {
1318         fd_set          readmask;
1319         int                     nSockets;
1320         time_t          now,
1321                                 last_touch_time;
1322
1323         last_touch_time = time(NULL);
1324
1325         nSockets = initMasks(&readmask);
1326
1327         for (;;)
1328         {
1329                 fd_set          rmask;
1330                 int                     selres;
1331
1332                 /*
1333                  * Wait for a connection request to arrive.
1334                  *
1335                  * We wait at most one minute, to ensure that the other background
1336                  * tasks handled below get done even when no requests are arriving.
1337                  *
1338                  * If we are in PM_WAIT_DEAD_END state, then we don't want to accept
1339                  * any new connections, so we don't call select() at all; just sleep
1340                  * for a little bit with signals unblocked.
1341                  */
1342                 memcpy((char *) &rmask, (char *) &readmask, sizeof(fd_set));
1343
1344                 PG_SETMASK(&UnBlockSig);
1345
1346                 if (pmState == PM_WAIT_DEAD_END)
1347                 {
1348                         pg_usleep(100000L); /* 100 msec seems reasonable */
1349                         selres = 0;
1350                 }
1351                 else
1352                 {
1353                         /* must set timeout each time; some OSes change it! */
1354                         struct timeval timeout;
1355
1356                         timeout.tv_sec = 60;
1357                         timeout.tv_usec = 0;
1358
1359                         selres = select(nSockets, &rmask, NULL, NULL, &timeout);
1360                 }
1361
1362                 /*
1363                  * Block all signals until we wait again.  (This makes it safe for our
1364                  * signal handlers to do nontrivial work.)
1365                  */
1366                 PG_SETMASK(&BlockSig);
1367
1368                 /* Now check the select() result */
1369                 if (selres < 0)
1370                 {
1371                         if (errno != EINTR && errno != EWOULDBLOCK)
1372                         {
1373                                 ereport(LOG,
1374                                                 (errcode_for_socket_access(),
1375                                                  errmsg("select() failed in postmaster: %m")));
1376                                 return STATUS_ERROR;
1377                         }
1378                 }
1379
1380                 /*
1381                  * New connection pending on any of our sockets? If so, fork a child
1382                  * process to deal with it.
1383                  */
1384                 if (selres > 0)
1385                 {
1386                         int                     i;
1387
1388                         for (i = 0; i < MAXLISTEN; i++)
1389                         {
1390                                 if (ListenSocket[i] == -1)
1391                                         break;
1392                                 if (FD_ISSET(ListenSocket[i], &rmask))
1393                                 {
1394                                         Port       *port;
1395
1396                                         port = ConnCreate(ListenSocket[i]);
1397                                         if (port)
1398                                         {
1399                                                 BackendStartup(port);
1400
1401                                                 /*
1402                                                  * We no longer need the open socket or port structure
1403                                                  * in this process
1404                                                  */
1405                                                 StreamClose(port->sock);
1406                                                 ConnFree(port);
1407                                         }
1408                                 }
1409                         }
1410                 }
1411
1412                 /* If we have lost the log collector, try to start a new one */
1413                 if (SysLoggerPID == 0 && Logging_collector)
1414                         SysLoggerPID = SysLogger_Start();
1415
1416                 /*
1417                  * If no background writer process is running, and we are not in a
1418                  * state that prevents it, start one.  It doesn't matter if this
1419                  * fails, we'll just try again later.
1420                  */
1421                 if (BgWriterPID == 0 &&
1422                         (pmState == PM_RUN || pmState == PM_RECOVERY ||
1423                          pmState == PM_RECOVERY_CONSISTENT))
1424                         BgWriterPID = StartBackgroundWriter();
1425
1426                 /*
1427                  * Likewise, if we have lost the walwriter process, try to start a new
1428                  * one.
1429                  */
1430                 if (WalWriterPID == 0 && pmState == PM_RUN)
1431                         WalWriterPID = StartWalWriter();
1432
1433                 /* If we have lost the autovacuum launcher, try to start a new one */
1434                 if (AutoVacPID == 0 &&
1435                         (AutoVacuumingActive() || start_autovac_launcher) &&
1436                         pmState == PM_RUN)
1437                 {
1438                         AutoVacPID = StartAutoVacLauncher();
1439                         if (AutoVacPID != 0)
1440                                 start_autovac_launcher = false; /* signal processed */
1441                 }
1442
1443                 /* If we have lost the archiver, try to start a new one */
1444                 if (XLogArchivingActive() && PgArchPID == 0 && pmState == PM_RUN)
1445                         PgArchPID = pgarch_start();
1446
1447                 /* If we have lost the stats collector, try to start a new one */
1448                 if (PgStatPID == 0 && pmState == PM_RUN)
1449                         PgStatPID = pgstat_start();
1450
1451                 /* If we need to signal the autovacuum launcher, do so now */
1452                 if (avlauncher_needs_signal)
1453                 {
1454                         avlauncher_needs_signal = false;
1455                         if (AutoVacPID != 0)
1456                                 kill(AutoVacPID, SIGUSR2);
1457                 }
1458
1459                 /*
1460                  * Touch the socket and lock file every 58 minutes, to ensure that
1461                  * they are not removed by overzealous /tmp-cleaning tasks.  We assume
1462                  * no one runs cleaners with cutoff times of less than an hour ...
1463                  */
1464                 now = time(NULL);
1465                 if (now - last_touch_time >= 58 * SECS_PER_MINUTE)
1466                 {
1467                         TouchSocketFile();
1468                         TouchSocketLockFile();
1469                         last_touch_time = now;
1470                 }
1471         }
1472 }
1473
1474
1475 /*
1476  * Initialise the masks for select() for the ports we are listening on.
1477  * Return the number of sockets to listen on.
1478  */
1479 static int
1480 initMasks(fd_set *rmask)
1481 {
1482         int                     maxsock = -1;
1483         int                     i;
1484
1485         FD_ZERO(rmask);
1486
1487         for (i = 0; i < MAXLISTEN; i++)
1488         {
1489                 int                     fd = ListenSocket[i];
1490
1491                 if (fd == -1)
1492                         break;
1493                 FD_SET          (fd, rmask);
1494
1495                 if (fd > maxsock)
1496                         maxsock = fd;
1497         }
1498
1499         return maxsock + 1;
1500 }
1501
1502
1503 /*
1504  * Read a client's startup packet and do something according to it.
1505  *
1506  * Returns STATUS_OK or STATUS_ERROR, or might call ereport(FATAL) and
1507  * not return at all.
1508  *
1509  * (Note that ereport(FATAL) stuff is sent to the client, so only use it
1510  * if that's what you want.  Return STATUS_ERROR if you don't want to
1511  * send anything to the client, which would typically be appropriate
1512  * if we detect a communications failure.)
1513  */
1514 static int
1515 ProcessStartupPacket(Port *port, bool SSLdone)
1516 {
1517         int32           len;
1518         void       *buf;
1519         ProtocolVersion proto;
1520         MemoryContext oldcontext;
1521
1522         if (pq_getbytes((char *) &len, 4) == EOF)
1523         {
1524                 /*
1525                  * EOF after SSLdone probably means the client didn't like our
1526                  * response to NEGOTIATE_SSL_CODE.      That's not an error condition, so
1527                  * don't clutter the log with a complaint.
1528                  */
1529                 if (!SSLdone)
1530                         ereport(COMMERROR,
1531                                         (errcode(ERRCODE_PROTOCOL_VIOLATION),
1532                                          errmsg("incomplete startup packet")));
1533                 return STATUS_ERROR;
1534         }
1535
1536         len = ntohl(len);
1537         len -= 4;
1538
1539         if (len < (int32) sizeof(ProtocolVersion) ||
1540                 len > MAX_STARTUP_PACKET_LENGTH)
1541         {
1542                 ereport(COMMERROR,
1543                                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1544                                  errmsg("invalid length of startup packet")));
1545                 return STATUS_ERROR;
1546         }
1547
1548         /*
1549          * Allocate at least the size of an old-style startup packet, plus one
1550          * extra byte, and make sure all are zeroes.  This ensures we will have
1551          * null termination of all strings, in both fixed- and variable-length
1552          * packet layouts.
1553          */
1554         if (len <= (int32) sizeof(StartupPacket))
1555                 buf = palloc0(sizeof(StartupPacket) + 1);
1556         else
1557                 buf = palloc0(len + 1);
1558
1559         if (pq_getbytes(buf, len) == EOF)
1560         {
1561                 ereport(COMMERROR,
1562                                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1563                                  errmsg("incomplete startup packet")));
1564                 return STATUS_ERROR;
1565         }
1566
1567         /*
1568          * The first field is either a protocol version number or a special
1569          * request code.
1570          */
1571         port->proto = proto = ntohl(*((ProtocolVersion *) buf));
1572
1573         if (proto == CANCEL_REQUEST_CODE)
1574         {
1575                 processCancelRequest(port, buf);
1576                 /* Not really an error, but we don't want to proceed further */
1577                 return STATUS_ERROR;
1578         }
1579
1580         if (proto == NEGOTIATE_SSL_CODE && !SSLdone)
1581         {
1582                 char            SSLok;
1583
1584 #ifdef USE_SSL
1585                 /* No SSL when disabled or on Unix sockets */
1586                 if (!EnableSSL || IS_AF_UNIX(port->laddr.addr.ss_family))
1587                         SSLok = 'N';
1588                 else
1589                         SSLok = 'S';            /* Support for SSL */
1590 #else
1591                 SSLok = 'N';                    /* No support for SSL */
1592 #endif
1593
1594 retry1:
1595                 if (send(port->sock, &SSLok, 1, 0) != 1)
1596                 {
1597                         if (errno == EINTR)
1598                                 goto retry1;    /* if interrupted, just retry */
1599                         ereport(COMMERROR,
1600                                         (errcode_for_socket_access(),
1601                                          errmsg("failed to send SSL negotiation response: %m")));
1602                         return STATUS_ERROR;    /* close the connection */
1603                 }
1604
1605 #ifdef USE_SSL
1606                 if (SSLok == 'S' && secure_open_server(port) == -1)
1607                         return STATUS_ERROR;
1608 #endif
1609                 /* regular startup packet, cancel, etc packet should follow... */
1610                 /* but not another SSL negotiation request */
1611                 return ProcessStartupPacket(port, true);
1612         }
1613
1614         /* Could add additional special packet types here */
1615
1616         /*
1617          * Set FrontendProtocol now so that ereport() knows what format to send if
1618          * we fail during startup.
1619          */
1620         FrontendProtocol = proto;
1621
1622         /* Check we can handle the protocol the frontend is using. */
1623
1624         if (PG_PROTOCOL_MAJOR(proto) < PG_PROTOCOL_MAJOR(PG_PROTOCOL_EARLIEST) ||
1625                 PG_PROTOCOL_MAJOR(proto) > PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST) ||
1626                 (PG_PROTOCOL_MAJOR(proto) == PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST) &&
1627                  PG_PROTOCOL_MINOR(proto) > PG_PROTOCOL_MINOR(PG_PROTOCOL_LATEST)))
1628                 ereport(FATAL,
1629                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1630                                  errmsg("unsupported frontend protocol %u.%u: server supports %u.0 to %u.%u",
1631                                                 PG_PROTOCOL_MAJOR(proto), PG_PROTOCOL_MINOR(proto),
1632                                                 PG_PROTOCOL_MAJOR(PG_PROTOCOL_EARLIEST),
1633                                                 PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST),
1634                                                 PG_PROTOCOL_MINOR(PG_PROTOCOL_LATEST))));
1635
1636         /*
1637          * Now fetch parameters out of startup packet and save them into the Port
1638          * structure.  All data structures attached to the Port struct must be
1639          * allocated in TopMemoryContext so that they will remain available in
1640          * a running backend (even after PostmasterContext is destroyed).  We need
1641          * not worry about leaking this storage on failure, since we aren't in the
1642          * postmaster process anymore.
1643          */
1644         oldcontext = MemoryContextSwitchTo(TopMemoryContext);
1645
1646         if (PG_PROTOCOL_MAJOR(proto) >= 3)
1647         {
1648                 int32           offset = sizeof(ProtocolVersion);
1649
1650                 /*
1651                  * Scan packet body for name/option pairs.      We can assume any string
1652                  * beginning within the packet body is null-terminated, thanks to
1653                  * zeroing extra byte above.
1654                  */
1655                 port->guc_options = NIL;
1656
1657                 while (offset < len)
1658                 {
1659                         char       *nameptr = ((char *) buf) + offset;
1660                         int32           valoffset;
1661                         char       *valptr;
1662
1663                         if (*nameptr == '\0')
1664                                 break;                  /* found packet terminator */
1665                         valoffset = offset + strlen(nameptr) + 1;
1666                         if (valoffset >= len)
1667                                 break;                  /* missing value, will complain below */
1668                         valptr = ((char *) buf) + valoffset;
1669
1670                         if (strcmp(nameptr, "database") == 0)
1671                                 port->database_name = pstrdup(valptr);
1672                         else if (strcmp(nameptr, "user") == 0)
1673                                 port->user_name = pstrdup(valptr);
1674                         else if (strcmp(nameptr, "options") == 0)
1675                                 port->cmdline_options = pstrdup(valptr);
1676                         else
1677                         {
1678                                 /* Assume it's a generic GUC option */
1679                                 port->guc_options = lappend(port->guc_options,
1680                                                                                         pstrdup(nameptr));
1681                                 port->guc_options = lappend(port->guc_options,
1682                                                                                         pstrdup(valptr));
1683                         }
1684                         offset = valoffset + strlen(valptr) + 1;
1685                 }
1686
1687                 /*
1688                  * If we didn't find a packet terminator exactly at the end of the
1689                  * given packet length, complain.
1690                  */
1691                 if (offset != len - 1)
1692                         ereport(FATAL,
1693                                         (errcode(ERRCODE_PROTOCOL_VIOLATION),
1694                                          errmsg("invalid startup packet layout: expected terminator as last byte")));
1695         }
1696         else
1697         {
1698                 /*
1699                  * Get the parameters from the old-style, fixed-width-fields startup
1700                  * packet as C strings.  The packet destination was cleared first so a
1701                  * short packet has zeros silently added.  We have to be prepared to
1702                  * truncate the pstrdup result for oversize fields, though.
1703                  */
1704                 StartupPacket *packet = (StartupPacket *) buf;
1705
1706                 port->database_name = pstrdup(packet->database);
1707                 if (strlen(port->database_name) > sizeof(packet->database))
1708                         port->database_name[sizeof(packet->database)] = '\0';
1709                 port->user_name = pstrdup(packet->user);
1710                 if (strlen(port->user_name) > sizeof(packet->user))
1711                         port->user_name[sizeof(packet->user)] = '\0';
1712                 port->cmdline_options = pstrdup(packet->options);
1713                 if (strlen(port->cmdline_options) > sizeof(packet->options))
1714                         port->cmdline_options[sizeof(packet->options)] = '\0';
1715                 port->guc_options = NIL;
1716         }
1717
1718         /* Check a user name was given. */
1719         if (port->user_name == NULL || port->user_name[0] == '\0')
1720                 ereport(FATAL,
1721                                 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
1722                          errmsg("no PostgreSQL user name specified in startup packet")));
1723
1724         /* The database defaults to the user name. */
1725         if (port->database_name == NULL || port->database_name[0] == '\0')
1726                 port->database_name = pstrdup(port->user_name);
1727
1728         if (Db_user_namespace)
1729         {
1730                 /*
1731                  * If user@, it is a global user, remove '@'. We only want to do this
1732                  * if there is an '@' at the end and no earlier in the user string or
1733                  * they may fake as a local user of another database attaching to this
1734                  * database.
1735                  */
1736                 if (strchr(port->user_name, '@') ==
1737                         port->user_name + strlen(port->user_name) - 1)
1738                         *strchr(port->user_name, '@') = '\0';
1739                 else
1740                 {
1741                         /* Append '@' and dbname */
1742                         char       *db_user;
1743
1744                         db_user = palloc(strlen(port->user_name) +
1745                                                          strlen(port->database_name) + 2);
1746                         sprintf(db_user, "%s@%s", port->user_name, port->database_name);
1747                         port->user_name = db_user;
1748                 }
1749         }
1750
1751         /*
1752          * Truncate given database and user names to length of a Postgres name.
1753          * This avoids lookup failures when overlength names are given.
1754          */
1755         if (strlen(port->database_name) >= NAMEDATALEN)
1756                 port->database_name[NAMEDATALEN - 1] = '\0';
1757         if (strlen(port->user_name) >= NAMEDATALEN)
1758                 port->user_name[NAMEDATALEN - 1] = '\0';
1759
1760         /*
1761          * Done putting stuff in TopMemoryContext.
1762          */
1763         MemoryContextSwitchTo(oldcontext);
1764
1765         /*
1766          * If we're going to reject the connection due to database state, say so
1767          * now instead of wasting cycles on an authentication exchange. (This also
1768          * allows a pg_ping utility to be written.)
1769          */
1770         switch (port->canAcceptConnections)
1771         {
1772                 case CAC_STARTUP:
1773                         ereport(FATAL,
1774                                         (errcode(ERRCODE_CANNOT_CONNECT_NOW),
1775                                          errmsg("the database system is starting up")));
1776                         break;
1777                 case CAC_SHUTDOWN:
1778                         ereport(FATAL,
1779                                         (errcode(ERRCODE_CANNOT_CONNECT_NOW),
1780                                          errmsg("the database system is shutting down")));
1781                         break;
1782                 case CAC_RECOVERY:
1783                         ereport(FATAL,
1784                                         (errcode(ERRCODE_CANNOT_CONNECT_NOW),
1785                                          errmsg("the database system is in recovery mode")));
1786                         break;
1787                 case CAC_TOOMANY:
1788                         ereport(FATAL,
1789                                         (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
1790                                          errmsg("sorry, too many clients already")));
1791                         break;
1792                 case CAC_WAITBACKUP:
1793                         /* OK for now, will check in InitPostgres */
1794                         break;
1795                 case CAC_OK:
1796                         break;
1797         }
1798
1799         return STATUS_OK;
1800 }
1801
1802
1803 /*
1804  * The client has sent a cancel request packet, not a normal
1805  * start-a-new-connection packet.  Perform the necessary processing.
1806  * Nothing is sent back to the client.
1807  */
1808 static void
1809 processCancelRequest(Port *port, void *pkt)
1810 {
1811         CancelRequestPacket *canc = (CancelRequestPacket *) pkt;
1812         int                     backendPID;
1813         long            cancelAuthCode;
1814         Backend    *bp;
1815
1816 #ifndef EXEC_BACKEND
1817         Dlelem     *curr;
1818 #else
1819         int                     i;
1820 #endif
1821
1822         backendPID = (int) ntohl(canc->backendPID);
1823         cancelAuthCode = (long) ntohl(canc->cancelAuthCode);
1824
1825         /*
1826          * See if we have a matching backend.  In the EXEC_BACKEND case, we can no
1827          * longer access the postmaster's own backend list, and must rely on the
1828          * duplicate array in shared memory.
1829          */
1830 #ifndef EXEC_BACKEND
1831         for (curr = DLGetHead(BackendList); curr; curr = DLGetSucc(curr))
1832         {
1833                 bp = (Backend *) DLE_VAL(curr);
1834 #else
1835         for (i = MaxLivePostmasterChildren() - 1; i >= 0; i--)
1836         {
1837                 bp = (Backend *) &ShmemBackendArray[i];
1838 #endif
1839                 if (bp->pid == backendPID)
1840                 {
1841                         if (bp->cancel_key == cancelAuthCode)
1842                         {
1843                                 /* Found a match; signal that backend to cancel current op */
1844                                 ereport(DEBUG2,
1845                                                 (errmsg_internal("processing cancel request: sending SIGINT to process %d",
1846                                                                                  backendPID)));
1847                                 signal_child(bp->pid, SIGINT);
1848                         }
1849                         else
1850                                 /* Right PID, wrong key: no way, Jose */
1851                                 ereport(LOG,
1852                                                 (errmsg("wrong key in cancel request for process %d",
1853                                                                 backendPID)));
1854                         return;
1855                 }
1856         }
1857
1858         /* No matching backend */
1859         ereport(LOG,
1860                         (errmsg("PID %d in cancel request did not match any process",
1861                                         backendPID)));
1862 }
1863
1864 /*
1865  * canAcceptConnections --- check to see if database state allows connections.
1866  */
1867 static enum CAC_state
1868 canAcceptConnections(void)
1869 {
1870         /*
1871          * Can't start backends when in startup/shutdown/recovery state.
1872          *
1873          * In state PM_WAIT_BACKUP only superusers can connect (this must be
1874          * allowed so that a superuser can end online backup mode); we return
1875          * CAC_WAITBACKUP code to indicate that this must be checked later.
1876          */
1877         if (pmState != PM_RUN)
1878         {
1879                 if (pmState == PM_WAIT_BACKUP)
1880                         return CAC_WAITBACKUP;          /* allow superusers only */
1881                 if (Shutdown > NoShutdown)
1882                         return CAC_SHUTDOWN;    /* shutdown is pending */
1883                 if (!FatalError &&
1884                         (pmState == PM_STARTUP ||
1885                          pmState == PM_RECOVERY ||
1886                          pmState == PM_RECOVERY_CONSISTENT))
1887                         return CAC_STARTUP; /* normal startup */
1888                 return CAC_RECOVERY;    /* else must be crash recovery */
1889         }
1890
1891         /*
1892          * Don't start too many children.
1893          *
1894          * We allow more connections than we can have backends here because some
1895          * might still be authenticating; they might fail auth, or some existing
1896          * backend might exit before the auth cycle is completed. The exact
1897          * MaxBackends limit is enforced when a new backend tries to join the
1898          * shared-inval backend array.
1899          *
1900          * The limit here must match the sizes of the per-child-process arrays;
1901          * see comments for MaxLivePostmasterChildren().
1902          */
1903         if (CountChildren() >= MaxLivePostmasterChildren())
1904                 return CAC_TOOMANY;
1905
1906         return CAC_OK;
1907 }
1908
1909
1910 /*
1911  * ConnCreate -- create a local connection data structure
1912  */
1913 static Port *
1914 ConnCreate(int serverFd)
1915 {
1916         Port       *port;
1917
1918         if (!(port = (Port *) calloc(1, sizeof(Port))))
1919         {
1920                 ereport(LOG,
1921                                 (errcode(ERRCODE_OUT_OF_MEMORY),
1922                                  errmsg("out of memory")));
1923                 ExitPostmaster(1);
1924         }
1925
1926         if (StreamConnection(serverFd, port) != STATUS_OK)
1927         {
1928                 if (port->sock >= 0)
1929                         StreamClose(port->sock);
1930                 ConnFree(port);
1931                 port = NULL;
1932         }
1933         else
1934         {
1935                 /*
1936                  * Precompute password salt values to use for this connection. It's
1937                  * slightly annoying to do this long in advance of knowing whether
1938                  * we'll need 'em or not, but we must do the random() calls before we
1939                  * fork, not after.  Else the postmaster's random sequence won't get
1940                  * advanced, and all backends would end up using the same salt...
1941                  */
1942                 RandomSalt(port->md5Salt);
1943         }
1944
1945         /*
1946          * Allocate GSSAPI specific state struct
1947          */
1948 #ifndef EXEC_BACKEND
1949 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
1950         port->gss = (pg_gssinfo *) calloc(1, sizeof(pg_gssinfo));
1951         if (!port->gss)
1952         {
1953                 ereport(LOG,
1954                                 (errcode(ERRCODE_OUT_OF_MEMORY),
1955                                  errmsg("out of memory")));
1956                 ExitPostmaster(1);
1957         }
1958 #endif
1959 #endif
1960
1961         return port;
1962 }
1963
1964
1965 /*
1966  * ConnFree -- free a local connection data structure
1967  */
1968 static void
1969 ConnFree(Port *conn)
1970 {
1971 #ifdef USE_SSL
1972         secure_close(conn);
1973 #endif
1974         if (conn->gss)
1975                 free(conn->gss);
1976         free(conn);
1977 }
1978
1979
1980 /*
1981  * ClosePostmasterPorts -- close all the postmaster's open sockets
1982  *
1983  * This is called during child process startup to release file descriptors
1984  * that are not needed by that child process.  The postmaster still has
1985  * them open, of course.
1986  *
1987  * Note: we pass am_syslogger as a boolean because we don't want to set
1988  * the global variable yet when this is called.
1989  */
1990 void
1991 ClosePostmasterPorts(bool am_syslogger)
1992 {
1993         int                     i;
1994
1995         /* Close the listen sockets */
1996         for (i = 0; i < MAXLISTEN; i++)
1997         {
1998                 if (ListenSocket[i] != -1)
1999                 {
2000                         StreamClose(ListenSocket[i]);
2001                         ListenSocket[i] = -1;
2002                 }
2003         }
2004
2005         /* If using syslogger, close the read side of the pipe */
2006         if (!am_syslogger)
2007         {
2008 #ifndef WIN32
2009                 if (syslogPipe[0] >= 0)
2010                         close(syslogPipe[0]);
2011                 syslogPipe[0] = -1;
2012 #else
2013                 if (syslogPipe[0])
2014                         CloseHandle(syslogPipe[0]);
2015                 syslogPipe[0] = 0;
2016 #endif
2017         }
2018
2019 #ifdef USE_BONJOUR
2020         /* If using Bonjour, close the connection to the mDNS daemon */
2021         if (bonjour_sdref)
2022                 close(DNSServiceRefSockFD(bonjour_sdref));
2023 #endif
2024 }
2025
2026
2027 /*
2028  * reset_shared -- reset shared memory and semaphores
2029  */
2030 static void
2031 reset_shared(int port)
2032 {
2033         /*
2034          * Create or re-create shared memory and semaphores.
2035          *
2036          * Note: in each "cycle of life" we will normally assign the same IPC keys
2037          * (if using SysV shmem and/or semas), since the port number is used to
2038          * determine IPC keys.  This helps ensure that we will clean up dead IPC
2039          * objects if the postmaster crashes and is restarted.
2040          */
2041         CreateSharedMemoryAndSemaphores(false, port);
2042 }
2043
2044
2045 /*
2046  * SIGHUP -- reread config files, and tell children to do same
2047  */
2048 static void
2049 SIGHUP_handler(SIGNAL_ARGS)
2050 {
2051         int                     save_errno = errno;
2052
2053         PG_SETMASK(&BlockSig);
2054
2055         if (Shutdown <= SmartShutdown)
2056         {
2057                 ereport(LOG,
2058                                 (errmsg("received SIGHUP, reloading configuration files")));
2059                 ProcessConfigFile(PGC_SIGHUP);
2060                 SignalChildren(SIGHUP);
2061                 if (StartupPID != 0)
2062                         signal_child(StartupPID, SIGHUP);
2063                 if (BgWriterPID != 0)
2064                         signal_child(BgWriterPID, SIGHUP);
2065                 if (WalWriterPID != 0)
2066                         signal_child(WalWriterPID, SIGHUP);
2067                 if (AutoVacPID != 0)
2068                         signal_child(AutoVacPID, SIGHUP);
2069                 if (PgArchPID != 0)
2070                         signal_child(PgArchPID, SIGHUP);
2071                 if (SysLoggerPID != 0)
2072                         signal_child(SysLoggerPID, SIGHUP);
2073                 if (PgStatPID != 0)
2074                         signal_child(PgStatPID, SIGHUP);
2075
2076                 /* Reload authentication config files too */
2077                 if (!load_hba())
2078                         ereport(WARNING,
2079                                         (errmsg("pg_hba.conf not reloaded")));
2080
2081                 load_ident();
2082
2083 #ifdef EXEC_BACKEND
2084                 /* Update the starting-point file for future children */
2085                 write_nondefault_variables(PGC_SIGHUP);
2086 #endif
2087         }
2088
2089         PG_SETMASK(&UnBlockSig);
2090
2091         errno = save_errno;
2092 }
2093
2094
2095 /*
2096  * pmdie -- signal handler for processing various postmaster signals.
2097  */
2098 static void
2099 pmdie(SIGNAL_ARGS)
2100 {
2101         int                     save_errno = errno;
2102
2103         PG_SETMASK(&BlockSig);
2104
2105         ereport(DEBUG2,
2106                         (errmsg_internal("postmaster received signal %d",
2107                                                          postgres_signal_arg)));
2108
2109         switch (postgres_signal_arg)
2110         {
2111                 case SIGTERM:
2112
2113                         /*
2114                          * Smart Shutdown:
2115                          *
2116                          * Wait for children to end their work, then shut down.
2117                          */
2118                         if (Shutdown >= SmartShutdown)
2119                                 break;
2120                         Shutdown = SmartShutdown;
2121                         ereport(LOG,
2122                                         (errmsg("received smart shutdown request")));
2123
2124                         if (pmState == PM_RUN || pmState == PM_RECOVERY ||
2125                                 pmState == PM_RECOVERY_CONSISTENT)
2126                         {
2127                                 /* autovacuum workers are told to shut down immediately */
2128                                 SignalAutovacWorkers(SIGTERM);
2129                                 /* and the autovac launcher too */
2130                                 if (AutoVacPID != 0)
2131                                         signal_child(AutoVacPID, SIGTERM);
2132                                 /* and the walwriter too */
2133                                 if (WalWriterPID != 0)
2134                                         signal_child(WalWriterPID, SIGTERM);
2135                                 pmState = PM_WAIT_BACKUP;
2136                         }
2137
2138                         /*
2139                          * Now wait for online backup mode to end and backends to exit.
2140                          * If that is already the case, PostmasterStateMachine will take
2141                          * the next step.
2142                          */
2143                         PostmasterStateMachine();
2144                         break;
2145
2146                 case SIGINT:
2147
2148                         /*
2149                          * Fast Shutdown:
2150                          *
2151                          * Abort all children with SIGTERM (rollback active transactions
2152                          * and exit) and shut down when they are gone.
2153                          */
2154                         if (Shutdown >= FastShutdown)
2155                                 break;
2156                         Shutdown = FastShutdown;
2157                         ereport(LOG,
2158                                         (errmsg("received fast shutdown request")));
2159
2160                         if (StartupPID != 0)
2161                                 signal_child(StartupPID, SIGTERM);
2162                         if (pmState == PM_RECOVERY)
2163                         {
2164                                 /* only bgwriter is active in this state */
2165                                 pmState = PM_WAIT_BACKENDS;
2166                         }
2167                         if (pmState == PM_RUN ||
2168                                 pmState == PM_WAIT_BACKUP ||
2169                                 pmState == PM_WAIT_BACKENDS ||
2170                                 pmState == PM_RECOVERY_CONSISTENT)
2171                         {
2172                                 ereport(LOG,
2173                                                 (errmsg("aborting any active transactions")));
2174                                 /* shut down all backends and autovac workers */
2175                                 SignalChildren(SIGTERM);
2176                                 /* and the autovac launcher too */
2177                                 if (AutoVacPID != 0)
2178                                         signal_child(AutoVacPID, SIGTERM);
2179                                 /* and the walwriter too */
2180                                 if (WalWriterPID != 0)
2181                                         signal_child(WalWriterPID, SIGTERM);
2182                                 pmState = PM_WAIT_BACKENDS;
2183                         }
2184
2185                         /*
2186                          * Now wait for backends to exit.  If there are none,
2187                          * PostmasterStateMachine will take the next step.
2188                          */
2189                         PostmasterStateMachine();
2190                         break;
2191
2192                 case SIGQUIT:
2193
2194                         /*
2195                          * Immediate Shutdown:
2196                          *
2197                          * abort all children with SIGQUIT and exit without attempt to
2198                          * properly shut down data base system.
2199                          */
2200                         ereport(LOG,
2201                                         (errmsg("received immediate shutdown request")));
2202                         SignalChildren(SIGQUIT);
2203                         if (StartupPID != 0)
2204                                 signal_child(StartupPID, SIGQUIT);
2205                         if (BgWriterPID != 0)
2206                                 signal_child(BgWriterPID, SIGQUIT);
2207                         if (WalWriterPID != 0)
2208                                 signal_child(WalWriterPID, SIGQUIT);
2209                         if (AutoVacPID != 0)
2210                                 signal_child(AutoVacPID, SIGQUIT);
2211                         if (PgArchPID != 0)
2212                                 signal_child(PgArchPID, SIGQUIT);
2213                         if (PgStatPID != 0)
2214                                 signal_child(PgStatPID, SIGQUIT);
2215                         ExitPostmaster(0);
2216                         break;
2217         }
2218
2219         PG_SETMASK(&UnBlockSig);
2220
2221         errno = save_errno;
2222 }
2223
2224 /*
2225  * Reaper -- signal handler to cleanup after a child process dies.
2226  */
2227 static void
2228 reaper(SIGNAL_ARGS)
2229 {
2230         int                     save_errno = errno;
2231         int                     pid;                    /* process id of dead child process */
2232         int                     exitstatus;             /* its exit status */
2233
2234         /* These macros hide platform variations in getting child status */
2235 #ifdef HAVE_WAITPID
2236         int                     status;                 /* child exit status */
2237
2238 #define LOOPTEST()              ((pid = waitpid(-1, &status, WNOHANG)) > 0)
2239 #define LOOPHEADER()    (exitstatus = status)
2240 #else                                                   /* !HAVE_WAITPID */
2241 #ifndef WIN32
2242         union wait      status;                 /* child exit status */
2243
2244 #define LOOPTEST()              ((pid = wait3(&status, WNOHANG, NULL)) > 0)
2245 #define LOOPHEADER()    (exitstatus = status.w_status)
2246 #else                                                   /* WIN32 */
2247 #define LOOPTEST()              ((pid = win32_waitpid(&exitstatus)) > 0)
2248 #define LOOPHEADER()
2249 #endif   /* WIN32 */
2250 #endif   /* HAVE_WAITPID */
2251
2252         PG_SETMASK(&BlockSig);
2253
2254         ereport(DEBUG4,
2255                         (errmsg_internal("reaping dead processes")));
2256
2257         while (LOOPTEST())
2258         {
2259                 LOOPHEADER();
2260
2261                 /*
2262                  * Check if this child was a startup process.
2263                  */
2264                 if (pid == StartupPID)
2265                 {
2266                         StartupPID = 0;
2267
2268                         /*
2269                          * Unexpected exit of startup process (including FATAL exit)
2270                          * during PM_STARTUP is treated as catastrophic. There are no
2271                          * other processes running yet, so we can just exit.
2272                          */
2273                         if (pmState == PM_STARTUP && !EXIT_STATUS_0(exitstatus))
2274                         {
2275                                 LogChildExit(LOG, _("startup process"),
2276                                                          pid, exitstatus);
2277                                 ereport(LOG,
2278                                 (errmsg("aborting startup due to startup process failure")));
2279                                 ExitPostmaster(1);
2280                         }
2281
2282                         /*
2283                          * Startup process exited in response to a shutdown request (or it
2284                          * completed normally regardless of the shutdown request).
2285                          */
2286                         if (Shutdown > NoShutdown &&
2287                                 (EXIT_STATUS_0(exitstatus) || EXIT_STATUS_1(exitstatus)))
2288                         {
2289                                 pmState = PM_WAIT_BACKENDS;
2290                                 /* PostmasterStateMachine logic does the rest */
2291                                 continue;
2292                         }
2293
2294                         /*
2295                          * Any unexpected exit (including FATAL exit) of the startup
2296                          * process is treated as a crash, except that we don't want to
2297                          * reinitialize.
2298                          */
2299                         if (!EXIT_STATUS_0(exitstatus))
2300                         {
2301                                 RecoveryError = true;
2302                                 HandleChildCrash(pid, exitstatus,
2303                                                                  _("startup process"));
2304                                 continue;
2305                         }
2306
2307                         /*
2308                          * Startup succeeded, commence normal operations
2309                          */
2310                         FatalError = false;
2311                         pmState = PM_RUN;
2312
2313                         /*
2314                          * Crank up the background writer, if we didn't do that already
2315                          * when we entered consistent recovery state.  It doesn't matter
2316                          * if this fails, we'll just try again later.
2317                          */
2318                         if (BgWriterPID == 0)
2319                                 BgWriterPID = StartBackgroundWriter();
2320
2321                         /*
2322                          * Likewise, start other special children as needed.  In a restart
2323                          * situation, some of them may be alive already.
2324                          */
2325                         if (WalWriterPID == 0)
2326                                 WalWriterPID = StartWalWriter();
2327                         if (AutoVacuumingActive() && AutoVacPID == 0)
2328                                 AutoVacPID = StartAutoVacLauncher();
2329                         if (XLogArchivingActive() && PgArchPID == 0)
2330                                 PgArchPID = pgarch_start();
2331                         if (PgStatPID == 0)
2332                                 PgStatPID = pgstat_start();
2333
2334                         /* at this point we are really open for business */
2335                         ereport(LOG,
2336                                  (errmsg("database system is ready to accept connections")));
2337
2338                         continue;
2339                 }
2340
2341                 /*
2342                  * Was it the bgwriter?
2343                  */
2344                 if (pid == BgWriterPID)
2345                 {
2346                         BgWriterPID = 0;
2347                         if (EXIT_STATUS_0(exitstatus) && pmState == PM_SHUTDOWN)
2348                         {
2349                                 /*
2350                                  * OK, we saw normal exit of the bgwriter after it's been told
2351                                  * to shut down.  We expect that it wrote a shutdown
2352                                  * checkpoint.  (If for some reason it didn't, recovery will
2353                                  * occur on next postmaster start.)
2354                                  *
2355                                  * At this point we should have no normal backend children
2356                                  * left (else we'd not be in PM_SHUTDOWN state) but we might
2357                                  * have dead_end children to wait for.
2358                                  *
2359                                  * If we have an archiver subprocess, tell it to do a last
2360                                  * archive cycle and quit; otherwise we can go directly to
2361                                  * PM_WAIT_DEAD_END state.
2362                                  */
2363                                 Assert(Shutdown > NoShutdown);
2364
2365                                 if (PgArchPID != 0)
2366                                 {
2367                                         /* Waken archiver for the last time */
2368                                         signal_child(PgArchPID, SIGUSR2);
2369                                         pmState = PM_SHUTDOWN_2;
2370                                 }
2371                                 else
2372                                         pmState = PM_WAIT_DEAD_END;
2373
2374                                 /*
2375                                  * We can also shut down the stats collector now; there's
2376                                  * nothing left for it to do.
2377                                  */
2378                                 if (PgStatPID != 0)
2379                                         signal_child(PgStatPID, SIGQUIT);
2380                         }
2381                         else
2382                         {
2383                                 /*
2384                                  * Any unexpected exit of the bgwriter (including FATAL exit)
2385                                  * is treated as a crash.
2386                                  */
2387                                 HandleChildCrash(pid, exitstatus,
2388                                                                  _("background writer process"));
2389                         }
2390
2391                         continue;
2392                 }
2393
2394                 /*
2395                  * Was it the wal writer?  Normal exit can be ignored; we'll start a
2396                  * new one at the next iteration of the postmaster's main loop, if
2397                  * necessary.  Any other exit condition is treated as a crash.
2398                  */
2399                 if (pid == WalWriterPID)
2400                 {
2401                         WalWriterPID = 0;
2402                         if (!EXIT_STATUS_0(exitstatus))
2403                                 HandleChildCrash(pid, exitstatus,
2404                                                                  _("WAL writer process"));
2405                         continue;
2406                 }
2407
2408                 /*
2409                  * Was it the autovacuum launcher?      Normal exit can be ignored; we'll
2410                  * start a new one at the next iteration of the postmaster's main
2411                  * loop, if necessary.  Any other exit condition is treated as a
2412                  * crash.
2413                  */
2414                 if (pid == AutoVacPID)
2415                 {
2416                         AutoVacPID = 0;
2417                         if (!EXIT_STATUS_0(exitstatus))
2418                                 HandleChildCrash(pid, exitstatus,
2419                                                                  _("autovacuum launcher process"));
2420                         continue;
2421                 }
2422
2423                 /*
2424                  * Was it the archiver?  If so, just try to start a new one; no need
2425                  * to force reset of the rest of the system.  (If fail, we'll try
2426                  * again in future cycles of the main loop.)  But if we were waiting
2427                  * for it to shut down, advance to the next shutdown step.
2428                  */
2429                 if (pid == PgArchPID)
2430                 {
2431                         PgArchPID = 0;
2432                         if (!EXIT_STATUS_0(exitstatus))
2433                                 LogChildExit(LOG, _("archiver process"),
2434                                                          pid, exitstatus);
2435                         if (XLogArchivingActive() && pmState == PM_RUN)
2436                                 PgArchPID = pgarch_start();
2437                         else if (pmState == PM_SHUTDOWN_2)
2438                                 pmState = PM_WAIT_DEAD_END;
2439                         continue;
2440                 }
2441
2442                 /*
2443                  * Was it the statistics collector?  If so, just try to start a new
2444                  * one; no need to force reset of the rest of the system.  (If fail,
2445                  * we'll try again in future cycles of the main loop.)
2446                  */
2447                 if (pid == PgStatPID)
2448                 {
2449                         PgStatPID = 0;
2450                         if (!EXIT_STATUS_0(exitstatus))
2451                                 LogChildExit(LOG, _("statistics collector process"),
2452                                                          pid, exitstatus);
2453                         if (pmState == PM_RUN)
2454                                 PgStatPID = pgstat_start();
2455                         continue;
2456                 }
2457
2458                 /* Was it the system logger?  If so, try to start a new one */
2459                 if (pid == SysLoggerPID)
2460                 {
2461                         SysLoggerPID = 0;
2462                         /* for safety's sake, launch new logger *first* */
2463                         SysLoggerPID = SysLogger_Start();
2464                         if (!EXIT_STATUS_0(exitstatus))
2465                                 LogChildExit(LOG, _("system logger process"),
2466                                                          pid, exitstatus);
2467                         continue;
2468                 }
2469
2470                 /*
2471                  * Else do standard backend child cleanup.
2472                  */
2473                 CleanupBackend(pid, exitstatus);
2474         }                                                       /* loop over pending child-death reports */
2475
2476         /*
2477          * After cleaning out the SIGCHLD queue, see if we have any state changes
2478          * or actions to make.
2479          */
2480         PostmasterStateMachine();
2481
2482         /* Done with signal handler */
2483         PG_SETMASK(&UnBlockSig);
2484
2485         errno = save_errno;
2486 }
2487
2488
2489 /*
2490  * CleanupBackend -- cleanup after terminated backend.
2491  *
2492  * Remove all local state associated with backend.
2493  */
2494 static void
2495 CleanupBackend(int pid,
2496                            int exitstatus)      /* child's exit status. */
2497 {
2498         Dlelem     *curr;
2499
2500         LogChildExit(DEBUG2, _("server process"), pid, exitstatus);
2501
2502         /*
2503          * If a backend dies in an ugly way then we must signal all other backends
2504          * to quickdie.  If exit status is zero (normal) or one (FATAL exit), we
2505          * assume everything is all right and proceed to remove the backend from
2506          * the active backend list.
2507          */
2508         if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
2509         {
2510                 HandleChildCrash(pid, exitstatus, _("server process"));
2511                 return;
2512         }
2513
2514         for (curr = DLGetHead(BackendList); curr; curr = DLGetSucc(curr))
2515         {
2516                 Backend    *bp = (Backend *) DLE_VAL(curr);
2517
2518                 if (bp->pid == pid)
2519                 {
2520                         if (!bp->dead_end)
2521                         {
2522                                 if (!ReleasePostmasterChildSlot(bp->child_slot))
2523                                 {
2524                                         /*
2525                                          * Uh-oh, the child failed to clean itself up.  Treat as a
2526                                          * crash after all.
2527                                          */
2528                                         HandleChildCrash(pid, exitstatus, _("server process"));
2529                                         return;
2530                                 }
2531 #ifdef EXEC_BACKEND
2532                                 ShmemBackendArrayRemove(bp);
2533 #endif
2534                         }
2535                         DLRemove(curr);
2536                         free(bp);
2537                         break;
2538                 }
2539         }
2540 }
2541
2542 /*
2543  * HandleChildCrash -- cleanup after failed backend, bgwriter, walwriter,
2544  * or autovacuum.
2545  *
2546  * The objectives here are to clean up our local state about the child
2547  * process, and to signal all other remaining children to quickdie.
2548  */
2549 static void
2550 HandleChildCrash(int pid, int exitstatus, const char *procname)
2551 {
2552         Dlelem     *curr,
2553                            *next;
2554         Backend    *bp;
2555
2556         /*
2557          * Make log entry unless there was a previous crash (if so, nonzero exit
2558          * status is to be expected in SIGQUIT response; don't clutter log)
2559          */
2560         if (!FatalError)
2561         {
2562                 LogChildExit(LOG, procname, pid, exitstatus);
2563                 ereport(LOG,
2564                                 (errmsg("terminating any other active server processes")));
2565         }
2566
2567         /* Process regular backends */
2568         for (curr = DLGetHead(BackendList); curr; curr = next)
2569         {
2570                 next = DLGetSucc(curr);
2571                 bp = (Backend *) DLE_VAL(curr);
2572                 if (bp->pid == pid)
2573                 {
2574                         /*
2575                          * Found entry for freshly-dead backend, so remove it.
2576                          */
2577                         if (!bp->dead_end)
2578                         {
2579                                 (void) ReleasePostmasterChildSlot(bp->child_slot);
2580 #ifdef EXEC_BACKEND
2581                                 ShmemBackendArrayRemove(bp);
2582 #endif
2583                         }
2584                         DLRemove(curr);
2585                         free(bp);
2586                         /* Keep looping so we can signal remaining backends */
2587                 }
2588                 else
2589                 {
2590                         /*
2591                          * This backend is still alive.  Unless we did so already, tell it
2592                          * to commit hara-kiri.
2593                          *
2594                          * SIGQUIT is the special signal that says exit without proc_exit
2595                          * and let the user know what's going on. But if SendStop is set
2596                          * (-s on command line), then we send SIGSTOP instead, so that we
2597                          * can get core dumps from all backends by hand.
2598                          *
2599                          * We could exclude dead_end children here, but at least in the
2600                          * SIGSTOP case it seems better to include them.
2601                          */
2602                         if (!FatalError)
2603                         {
2604                                 ereport(DEBUG2,
2605                                                 (errmsg_internal("sending %s to process %d",
2606                                                                                  (SendStop ? "SIGSTOP" : "SIGQUIT"),
2607                                                                                  (int) bp->pid)));
2608                                 signal_child(bp->pid, (SendStop ? SIGSTOP : SIGQUIT));
2609                         }
2610                 }
2611         }
2612
2613         /* Take care of the startup process too */
2614         if (pid == StartupPID)
2615                 StartupPID = 0;
2616         else if (StartupPID != 0 && !FatalError)
2617         {
2618                 ereport(DEBUG2,
2619                                 (errmsg_internal("sending %s to process %d",
2620                                                                  (SendStop ? "SIGSTOP" : "SIGQUIT"),
2621                                                                  (int) StartupPID)));
2622                 signal_child(StartupPID, (SendStop ? SIGSTOP : SIGQUIT));
2623         }
2624
2625         /* Take care of the bgwriter too */
2626         if (pid == BgWriterPID)
2627                 BgWriterPID = 0;
2628         else if (BgWriterPID != 0 && !FatalError)
2629         {
2630                 ereport(DEBUG2,
2631                                 (errmsg_internal("sending %s to process %d",
2632                                                                  (SendStop ? "SIGSTOP" : "SIGQUIT"),
2633                                                                  (int) BgWriterPID)));
2634                 signal_child(BgWriterPID, (SendStop ? SIGSTOP : SIGQUIT));
2635         }
2636
2637         /* Take care of the walwriter too */
2638         if (pid == WalWriterPID)
2639                 WalWriterPID = 0;
2640         else if (WalWriterPID != 0 && !FatalError)
2641         {
2642                 ereport(DEBUG2,
2643                                 (errmsg_internal("sending %s to process %d",
2644                                                                  (SendStop ? "SIGSTOP" : "SIGQUIT"),
2645                                                                  (int) WalWriterPID)));
2646                 signal_child(WalWriterPID, (SendStop ? SIGSTOP : SIGQUIT));
2647         }
2648
2649         /* Take care of the autovacuum launcher too */
2650         if (pid == AutoVacPID)
2651                 AutoVacPID = 0;
2652         else if (AutoVacPID != 0 && !FatalError)
2653         {
2654                 ereport(DEBUG2,
2655                                 (errmsg_internal("sending %s to process %d",
2656                                                                  (SendStop ? "SIGSTOP" : "SIGQUIT"),
2657                                                                  (int) AutoVacPID)));
2658                 signal_child(AutoVacPID, (SendStop ? SIGSTOP : SIGQUIT));
2659         }
2660
2661         /*
2662          * Force a power-cycle of the pgarch process too.  (This isn't absolutely
2663          * necessary, but it seems like a good idea for robustness, and it
2664          * simplifies the state-machine logic in the case where a shutdown request
2665          * arrives during crash processing.)
2666          */
2667         if (PgArchPID != 0 && !FatalError)
2668         {
2669                 ereport(DEBUG2,
2670                                 (errmsg_internal("sending %s to process %d",
2671                                                                  "SIGQUIT",
2672                                                                  (int) PgArchPID)));
2673                 signal_child(PgArchPID, SIGQUIT);
2674         }
2675
2676         /*
2677          * Force a power-cycle of the pgstat process too.  (This isn't absolutely
2678          * necessary, but it seems like a good idea for robustness, and it
2679          * simplifies the state-machine logic in the case where a shutdown request
2680          * arrives during crash processing.)
2681          */
2682         if (PgStatPID != 0 && !FatalError)
2683         {
2684                 ereport(DEBUG2,
2685                                 (errmsg_internal("sending %s to process %d",
2686                                                                  "SIGQUIT",
2687                                                                  (int) PgStatPID)));
2688                 signal_child(PgStatPID, SIGQUIT);
2689                 allow_immediate_pgstat_restart();
2690         }
2691
2692         /* We do NOT restart the syslogger */
2693
2694         FatalError = true;
2695         /* We now transit into a state of waiting for children to die */
2696         if (pmState == PM_RECOVERY ||
2697                 pmState == PM_RECOVERY_CONSISTENT ||
2698                 pmState == PM_RUN ||
2699                 pmState == PM_WAIT_BACKUP ||
2700                 pmState == PM_SHUTDOWN)
2701                 pmState = PM_WAIT_BACKENDS;
2702 }
2703
2704 /*
2705  * Log the death of a child process.
2706  */
2707 static void
2708 LogChildExit(int lev, const char *procname, int pid, int exitstatus)
2709 {
2710         if (WIFEXITED(exitstatus))
2711                 ereport(lev,
2712
2713                 /*------
2714                   translator: %s is a noun phrase describing a child process, such as
2715                   "server process" */
2716                                 (errmsg("%s (PID %d) exited with exit code %d",
2717                                                 procname, pid, WEXITSTATUS(exitstatus))));
2718         else if (WIFSIGNALED(exitstatus))
2719 #if defined(WIN32)
2720                 ereport(lev,
2721
2722                 /*------
2723                   translator: %s is a noun phrase describing a child process, such as
2724                   "server process" */
2725                                 (errmsg("%s (PID %d) was terminated by exception 0x%X",
2726                                                 procname, pid, WTERMSIG(exitstatus)),
2727                                  errhint("See C include file \"ntstatus.h\" for a description of the hexadecimal value.")));
2728 #elif defined(HAVE_DECL_SYS_SIGLIST) && HAVE_DECL_SYS_SIGLIST
2729         ereport(lev,
2730
2731         /*------
2732           translator: %s is a noun phrase describing a child process, such as
2733           "server process" */
2734                         (errmsg("%s (PID %d) was terminated by signal %d: %s",
2735                                         procname, pid, WTERMSIG(exitstatus),
2736                                         WTERMSIG(exitstatus) < NSIG ?
2737                                         sys_siglist[WTERMSIG(exitstatus)] : "(unknown)")));
2738 #else
2739                 ereport(lev,
2740
2741                 /*------
2742                   translator: %s is a noun phrase describing a child process, such as
2743                   "server process" */
2744                                 (errmsg("%s (PID %d) was terminated by signal %d",
2745                                                 procname, pid, WTERMSIG(exitstatus))));
2746 #endif
2747         else
2748                 ereport(lev,
2749
2750                 /*------
2751                   translator: %s is a noun phrase describing a child process, such as
2752                   "server process" */
2753                                 (errmsg("%s (PID %d) exited with unrecognized status %d",
2754                                                 procname, pid, exitstatus)));
2755 }
2756
2757 /*
2758  * Advance the postmaster's state machine and take actions as appropriate
2759  *
2760  * This is common code for pmdie() and reaper(), which receive the signals
2761  * that might mean we need to change state.
2762  */
2763 static void
2764 PostmasterStateMachine(void)
2765 {
2766         if (pmState == PM_WAIT_BACKUP)
2767         {
2768                 /*
2769                  * PM_WAIT_BACKUP state ends when online backup mode is not active.
2770                  */
2771                 if (!BackupInProgress())
2772                         pmState = PM_WAIT_BACKENDS;
2773         }
2774
2775         /*
2776          * If we are in a state-machine state that implies waiting for backends to
2777          * exit, see if they're all gone, and change state if so.
2778          */
2779         if (pmState == PM_WAIT_BACKENDS)
2780         {
2781                 /*
2782                  * PM_WAIT_BACKENDS state ends when we have no regular backends
2783                  * (including autovac workers) and no walwriter or autovac launcher.
2784                  * If we are doing crash recovery then we expect the bgwriter to exit
2785                  * too, otherwise not.  The archiver, stats, and syslogger processes
2786                  * are disregarded since they are not connected to shared memory; we
2787                  * also disregard dead_end children here.
2788                  */
2789                 if (CountChildren() == 0 &&
2790                         StartupPID == 0 &&
2791                         (BgWriterPID == 0 || !FatalError) &&
2792                         WalWriterPID == 0 &&
2793                         AutoVacPID == 0)
2794                 {
2795                         if (FatalError)
2796                         {
2797                                 /*
2798                                  * Start waiting for dead_end children to die.  This state
2799                                  * change causes ServerLoop to stop creating new ones.
2800                                  */
2801                                 pmState = PM_WAIT_DEAD_END;
2802
2803                                 /*
2804                                  * We already SIGQUIT'd the archiver and stats processes, if
2805                                  * any, when we entered FatalError state.
2806                                  */
2807                         }
2808                         else
2809                         {
2810                                 /*
2811                                  * If we get here, we are proceeding with normal shutdown. All
2812                                  * the regular children are gone, and it's time to tell the
2813                                  * bgwriter to do a shutdown checkpoint.
2814                                  */
2815                                 Assert(Shutdown > NoShutdown);
2816                                 /* Start the bgwriter if not running */
2817                                 if (BgWriterPID == 0)
2818                                         BgWriterPID = StartBackgroundWriter();
2819                                 /* And tell it to shut down */
2820                                 if (BgWriterPID != 0)
2821                                 {
2822                                         signal_child(BgWriterPID, SIGUSR2);
2823                                         pmState = PM_SHUTDOWN;
2824                                 }
2825                                 else
2826                                 {
2827                                         /*
2828                                          * If we failed to fork a bgwriter, just shut down. Any
2829                                          * required cleanup will happen at next restart. We set
2830                                          * FatalError so that an "abnormal shutdown" message gets
2831                                          * logged when we exit.
2832                                          */
2833                                         FatalError = true;
2834                                         pmState = PM_WAIT_DEAD_END;
2835
2836                                         /* Kill the archiver and stats collector too */
2837                                         if (PgArchPID != 0)
2838                                                 signal_child(PgArchPID, SIGQUIT);
2839                                         if (PgStatPID != 0)
2840                                                 signal_child(PgStatPID, SIGQUIT);
2841                                 }
2842                         }
2843                 }
2844         }
2845
2846         if (pmState == PM_WAIT_DEAD_END)
2847         {
2848                 /*
2849                  * PM_WAIT_DEAD_END state ends when the BackendList is entirely empty
2850                  * (ie, no dead_end children remain), and the archiver and stats
2851                  * collector are gone too.
2852                  *
2853                  * The reason we wait for those two is to protect them against a new
2854                  * postmaster starting conflicting subprocesses; this isn't an
2855                  * ironclad protection, but it at least helps in the
2856                  * shutdown-and-immediately-restart scenario.  Note that they have
2857                  * already been sent appropriate shutdown signals, either during a
2858                  * normal state transition leading up to PM_WAIT_DEAD_END, or during
2859                  * FatalError processing.
2860                  */
2861                 if (DLGetHead(BackendList) == NULL &&
2862                         PgArchPID == 0 && PgStatPID == 0)
2863                 {
2864                         /* These other guys should be dead already */
2865                         Assert(StartupPID == 0);
2866                         Assert(BgWriterPID == 0);
2867                         Assert(WalWriterPID == 0);
2868                         Assert(AutoVacPID == 0);
2869                         /* syslogger is not considered here */
2870                         pmState = PM_NO_CHILDREN;
2871                 }
2872         }
2873
2874         /*
2875          * If we've been told to shut down, we exit as soon as there are no
2876          * remaining children.  If there was a crash, cleanup will occur at the
2877          * next startup.  (Before PostgreSQL 8.3, we tried to recover from the
2878          * crash before exiting, but that seems unwise if we are quitting because
2879          * we got SIGTERM from init --- there may well not be time for recovery
2880          * before init decides to SIGKILL us.)
2881          *
2882          * Note that the syslogger continues to run.  It will exit when it sees
2883          * EOF on its input pipe, which happens when there are no more upstream
2884          * processes.
2885          */
2886         if (Shutdown > NoShutdown && pmState == PM_NO_CHILDREN)
2887         {
2888                 if (FatalError)
2889                 {
2890                         ereport(LOG, (errmsg("abnormal database system shutdown")));
2891                         ExitPostmaster(1);
2892                 }
2893                 else
2894                 {
2895                         /*
2896                          * Terminate backup mode to avoid recovery after a clean fast
2897                          * shutdown.
2898                          */
2899                         CancelBackup();
2900
2901                         /* Normal exit from the postmaster is here */
2902                         ExitPostmaster(0);
2903                 }
2904         }
2905
2906         /*
2907          * If recovery failed, wait for all non-syslogger children to exit, and
2908          * then exit postmaster. We don't try to reinitialize when recovery fails,
2909          * because more than likely it will just fail again and we will keep
2910          * trying forever.
2911          */
2912         if (RecoveryError && pmState == PM_NO_CHILDREN)
2913                 ExitPostmaster(1);
2914
2915         /*
2916          * If we need to recover from a crash, wait for all non-syslogger children
2917          * to exit, then reset shmem and StartupDataBase.
2918          */
2919         if (FatalError && pmState == PM_NO_CHILDREN)
2920         {
2921                 ereport(LOG,
2922                                 (errmsg("all server processes terminated; reinitializing")));
2923
2924                 shmem_exit(1);
2925                 reset_shared(PostPortNumber);
2926
2927                 StartupPID = StartupDataBase();
2928                 Assert(StartupPID != 0);
2929                 pmState = PM_STARTUP;
2930         }
2931 }
2932
2933
2934 /*
2935  * Send a signal to a postmaster child process
2936  *
2937  * On systems that have setsid(), each child process sets itself up as a
2938  * process group leader.  For signals that are generally interpreted in the
2939  * appropriate fashion, we signal the entire process group not just the
2940  * direct child process.  This allows us to, for example, SIGQUIT a blocked
2941  * archive_recovery script, or SIGINT a script being run by a backend via
2942  * system().
2943  *
2944  * There is a race condition for recently-forked children: they might not
2945  * have executed setsid() yet.  So we signal the child directly as well as
2946  * the group.  We assume such a child will handle the signal before trying
2947  * to spawn any grandchild processes.  We also assume that signaling the
2948  * child twice will not cause any problems.
2949  */
2950 static void
2951 signal_child(pid_t pid, int signal)
2952 {
2953         if (kill(pid, signal) < 0)
2954                 elog(DEBUG3, "kill(%ld,%d) failed: %m", (long) pid, signal);
2955 #ifdef HAVE_SETSID
2956         switch (signal)
2957         {
2958                 case SIGINT:
2959                 case SIGTERM:
2960                 case SIGQUIT:
2961                 case SIGSTOP:
2962                         if (kill(-pid, signal) < 0)
2963                                 elog(DEBUG3, "kill(%ld,%d) failed: %m", (long) (-pid), signal);
2964                         break;
2965                 default:
2966                         break;
2967         }
2968 #endif
2969 }
2970
2971 /*
2972  * Send a signal to all backend children, including autovacuum workers
2973  * (but NOT special children; dead_end children are never signaled, either).
2974  * If only_autovac is TRUE, only the autovacuum worker processes are signalled.
2975  */
2976 static void
2977 SignalSomeChildren(int signal, bool only_autovac)
2978 {
2979         Dlelem     *curr;
2980
2981         for (curr = DLGetHead(BackendList); curr; curr = DLGetSucc(curr))
2982         {
2983                 Backend    *bp = (Backend *) DLE_VAL(curr);
2984
2985                 if (bp->dead_end)
2986                         continue;
2987                 if (only_autovac && !bp->is_autovacuum)
2988                         continue;
2989
2990                 ereport(DEBUG4,
2991                                 (errmsg_internal("sending signal %d to process %d",
2992                                                                  signal, (int) bp->pid)));
2993                 signal_child(bp->pid, signal);
2994         }
2995 }
2996
2997 /*
2998  * BackendStartup -- start backend process
2999  *
3000  * returns: STATUS_ERROR if the fork failed, STATUS_OK otherwise.
3001  *
3002  * Note: if you change this code, also consider StartAutovacuumWorker.
3003  */
3004 static int
3005 BackendStartup(Port *port)
3006 {
3007         Backend    *bn;                         /* for backend cleanup */
3008         pid_t           pid;
3009
3010         /*
3011          * Create backend data structure.  Better before the fork() so we can
3012          * handle failure cleanly.
3013          */
3014         bn = (Backend *) malloc(sizeof(Backend));
3015         if (!bn)
3016         {
3017                 ereport(LOG,
3018                                 (errcode(ERRCODE_OUT_OF_MEMORY),
3019                                  errmsg("out of memory")));
3020                 return STATUS_ERROR;
3021         }
3022
3023         /*
3024          * Compute the cancel key that will be assigned to this backend. The
3025          * backend will have its own copy in the forked-off process' value of
3026          * MyCancelKey, so that it can transmit the key to the frontend.
3027          */
3028         MyCancelKey = PostmasterRandom();
3029         bn->cancel_key = MyCancelKey;
3030
3031         /* Pass down canAcceptConnections state */
3032         port->canAcceptConnections = canAcceptConnections();
3033         bn->dead_end = (port->canAcceptConnections != CAC_OK &&
3034                                         port->canAcceptConnections != CAC_WAITBACKUP);
3035
3036         /*
3037          * Unless it's a dead_end child, assign it a child slot number
3038          */
3039         if (!bn->dead_end)
3040                 bn->child_slot = MyPMChildSlot = AssignPostmasterChildSlot();
3041         else
3042                 bn->child_slot = 0;
3043
3044 #ifdef EXEC_BACKEND
3045         pid = backend_forkexec(port);
3046 #else                                                   /* !EXEC_BACKEND */
3047         pid = fork_process();
3048         if (pid == 0)                           /* child */
3049         {
3050                 free(bn);
3051
3052                 /*
3053                  * Let's clean up ourselves as the postmaster child, and close the
3054                  * postmaster's listen sockets.  (In EXEC_BACKEND case this is all
3055                  * done in SubPostmasterMain.)
3056                  */
3057                 IsUnderPostmaster = true;               /* we are a postmaster subprocess now */
3058
3059                 MyProcPid = getpid();   /* reset MyProcPid */
3060
3061                 MyStartTime = time(NULL);
3062
3063                 /* We don't want the postmaster's proc_exit() handlers */
3064                 on_exit_reset();
3065
3066                 /* Close the postmaster's sockets */
3067                 ClosePostmasterPorts(false);
3068
3069                 /* Perform additional initialization and collect startup packet */
3070                 BackendInitialize(port);
3071
3072                 /* And run the backend */
3073                 proc_exit(BackendRun(port));
3074         }
3075 #endif   /* EXEC_BACKEND */
3076
3077         if (pid < 0)
3078         {
3079                 /* in parent, fork failed */
3080                 int                     save_errno = errno;
3081
3082                 if (!bn->dead_end)
3083                         (void) ReleasePostmasterChildSlot(bn->child_slot);
3084                 free(bn);
3085                 errno = save_errno;
3086                 ereport(LOG,
3087                                 (errmsg("could not fork new process for connection: %m")));
3088                 report_fork_failure_to_client(port, save_errno);
3089                 return STATUS_ERROR;
3090         }
3091
3092         /* in parent, successful fork */
3093         ereport(DEBUG2,
3094                         (errmsg_internal("forked new backend, pid=%d socket=%d",
3095                                                          (int) pid, port->sock)));
3096
3097         /*
3098          * Everything's been successful, it's safe to add this backend to our list
3099          * of backends.
3100          */
3101         bn->pid = pid;
3102         bn->is_autovacuum = false;
3103         DLInitElem(&bn->elem, bn);
3104         DLAddHead(BackendList, &bn->elem);
3105 #ifdef EXEC_BACKEND
3106         if (!bn->dead_end)
3107                 ShmemBackendArrayAdd(bn);
3108 #endif
3109
3110         return STATUS_OK;
3111 }
3112
3113 /*
3114  * Try to report backend fork() failure to client before we close the
3115  * connection.  Since we do not care to risk blocking the postmaster on
3116  * this connection, we set the connection to non-blocking and try only once.
3117  *
3118  * This is grungy special-purpose code; we cannot use backend libpq since
3119  * it's not up and running.
3120  */
3121 static void
3122 report_fork_failure_to_client(Port *port, int errnum)
3123 {
3124         char            buffer[1000];
3125         int                     rc;
3126
3127         /* Format the error message packet (always V2 protocol) */
3128         snprintf(buffer, sizeof(buffer), "E%s%s\n",
3129                          _("could not fork new process for connection: "),
3130                          strerror(errnum));
3131
3132         /* Set port to non-blocking.  Don't do send() if this fails */
3133         if (!pg_set_noblock(port->sock))
3134                 return;
3135
3136         /* We'll retry after EINTR, but ignore all other failures */
3137         do
3138         {
3139                 rc = send(port->sock, buffer, strlen(buffer) + 1, 0);
3140         } while (rc < 0 && errno == EINTR);
3141 }
3142
3143
3144 /*
3145  * BackendInitialize -- initialize an interactive (postmaster-child)
3146  *                              backend process, and collect the client's startup packet.
3147  *
3148  * returns: nothing.  Will not return at all if there's any failure.
3149  *
3150  * Note: this code does not depend on having any access to shared memory.
3151  * In the EXEC_BACKEND case, we are physically attached to shared memory
3152  * but have not yet set up most of our local pointers to shmem structures.
3153  */
3154 static void
3155 BackendInitialize(Port *port)
3156 {
3157         int                     status;
3158         char            remote_host[NI_MAXHOST];
3159         char            remote_port[NI_MAXSERV];
3160         char            remote_ps_data[NI_MAXHOST];
3161
3162         /* Save port etc. for ps status */
3163         MyProcPort = port;
3164
3165         /*
3166          * PreAuthDelay is a debugging aid for investigating problems in the
3167          * authentication cycle: it can be set in postgresql.conf to allow time to
3168          * attach to the newly-forked backend with a debugger.  (See also
3169          * PostAuthDelay, which we allow clients to pass through PGOPTIONS, but
3170          * it is not honored until after authentication.)
3171          */
3172         if (PreAuthDelay > 0)
3173                 pg_usleep(PreAuthDelay * 1000000L);
3174
3175         /* This flag will remain set until InitPostgres finishes authentication */
3176         ClientAuthInProgress = true;    /* limit visibility of log messages */
3177
3178         /* save process start time */
3179         port->SessionStartTime = GetCurrentTimestamp();
3180         MyStartTime = timestamptz_to_time_t(port->SessionStartTime);
3181
3182         /* set these to empty in case they are needed before we set them up */
3183         port->remote_host = "";
3184         port->remote_port = "";
3185
3186         /*
3187          * Initialize libpq and enable reporting of ereport errors to the client.
3188          * Must do this now because authentication uses libpq to send messages.
3189          */
3190         pq_init();                                      /* initialize libpq to talk to client */
3191         whereToSendOutput = DestRemote;         /* now safe to ereport to client */
3192
3193         /*
3194          * If possible, make this process a group leader, so that the postmaster
3195          * can signal any child processes too.  (We do this now on the off chance
3196          * that something might spawn a child process during authentication.)
3197          */
3198 #ifdef HAVE_SETSID
3199         if (setsid() < 0)
3200                 elog(FATAL, "setsid() failed: %m");
3201 #endif
3202
3203         /*
3204          * We arrange for a simple exit(1) if we receive SIGTERM or SIGQUIT
3205          * or timeout while trying to collect the startup packet.  Otherwise the
3206          * postmaster cannot shutdown the database FAST or IMMED cleanly if a
3207          * buggy client fails to send the packet promptly.
3208          */
3209         pqsignal(SIGTERM, startup_die);
3210         pqsignal(SIGQUIT, startup_die);
3211         pqsignal(SIGALRM, startup_die);
3212         PG_SETMASK(&StartupBlockSig);
3213
3214         /*
3215          * Get the remote host name and port for logging and status display.
3216          */
3217         remote_host[0] = '\0';
3218         remote_port[0] = '\0';
3219         if (pg_getnameinfo_all(&port->raddr.addr, port->raddr.salen,
3220                                                    remote_host, sizeof(remote_host),
3221                                                    remote_port, sizeof(remote_port),
3222                                            (log_hostname ? 0 : NI_NUMERICHOST) | NI_NUMERICSERV))
3223         {
3224                 int                     ret = pg_getnameinfo_all(&port->raddr.addr, port->raddr.salen,
3225                                                                                          remote_host, sizeof(remote_host),
3226                                                                                          remote_port, sizeof(remote_port),
3227                                                                                          NI_NUMERICHOST | NI_NUMERICSERV);
3228
3229                 if (ret)
3230                         ereport(WARNING,
3231                                         (errmsg_internal("pg_getnameinfo_all() failed: %s",
3232                                                                          gai_strerror(ret))));
3233         }
3234         snprintf(remote_ps_data, sizeof(remote_ps_data),
3235                          remote_port[0] == '\0' ? "%s" : "%s(%s)",
3236                          remote_host, remote_port);
3237
3238         if (Log_connections)
3239                 ereport(LOG,
3240                                 (errmsg("connection received: host=%s%s%s",
3241                                                 remote_host, remote_port[0] ? " port=" : "",
3242                                                 remote_port)));
3243
3244         /*
3245          * save remote_host and remote_port in port structure
3246          */
3247         port->remote_host = strdup(remote_host);
3248         port->remote_port = strdup(remote_port);
3249
3250         /*
3251          * Ready to begin client interaction.  We will give up and exit(1) after a
3252          * time delay, so that a broken client can't hog a connection
3253          * indefinitely.  PreAuthDelay and any DNS interactions above don't count
3254          * against the time limit.
3255          */
3256         if (!enable_sig_alarm(AuthenticationTimeout * 1000, false))
3257                 elog(FATAL, "could not set timer for startup packet timeout");
3258
3259         /*
3260          * Receive the startup packet (which might turn out to be a cancel request
3261          * packet).
3262          */
3263         status = ProcessStartupPacket(port, false);
3264
3265         /*
3266          * Stop here if it was bad or a cancel packet.  ProcessStartupPacket
3267          * already did any appropriate error reporting.
3268          */
3269         if (status != STATUS_OK)
3270                 proc_exit(0);
3271
3272         /*
3273          * Now that we have the user and database name, we can set the process
3274          * title for ps.  It's good to do this as early as possible in startup.
3275          */
3276         init_ps_display(port->user_name, port->database_name, remote_ps_data,
3277                                         update_process_title ? "authentication" : "");
3278
3279         /*
3280          * Disable the timeout, and prevent SIGTERM/SIGQUIT again.
3281          */
3282         if (!disable_sig_alarm(false))
3283                 elog(FATAL, "could not disable timer for startup packet timeout");
3284         PG_SETMASK(&BlockSig);
3285 }
3286
3287
3288 /*
3289  * BackendRun -- set up the backend's argument list and invoke PostgresMain()
3290  *
3291  * returns:
3292  *              Shouldn't return at all.
3293  *              If PostgresMain() fails, return status.
3294  */
3295 static int
3296 BackendRun(Port *port)
3297 {
3298         char      **av;
3299         int                     maxac;
3300         int                     ac;
3301         long            secs;
3302         int                     usecs;
3303         int                     i;
3304
3305         /*
3306          * Don't want backend to be able to see the postmaster random number
3307          * generator state.  We have to clobber the static random_seed *and* start
3308          * a new random sequence in the random() library function.
3309          */
3310         random_seed = 0;
3311         random_start_time.tv_usec = 0;
3312         /* slightly hacky way to get integer microseconds part of timestamptz */
3313         TimestampDifference(0, port->SessionStartTime, &secs, &usecs);
3314         srandom((unsigned int) (MyProcPid ^ usecs));
3315
3316         /*
3317          * Now, build the argv vector that will be given to PostgresMain.
3318          *
3319          * The maximum possible number of commandline arguments that could come
3320          * from ExtraOptions is (strlen(ExtraOptions) + 1) / 2; see
3321          * pg_split_opts().
3322          */
3323         maxac = 5;                                      /* for fixed args supplied below */
3324         maxac += (strlen(ExtraOptions) + 1) / 2;
3325
3326         av = (char **) MemoryContextAlloc(TopMemoryContext,
3327                                                                           maxac * sizeof(char *));
3328         ac = 0;
3329
3330         av[ac++] = "postgres";
3331
3332         /*
3333          * Pass any backend switches specified with -o on the postmaster's own
3334          * command line.  We assume these are secure.  (It's OK to mangle
3335          * ExtraOptions now, since we're safely inside a subprocess.)
3336          */
3337         pg_split_opts(av, &ac, ExtraOptions);
3338
3339         /*
3340          * Tell the backend which database to use.
3341          */
3342         av[ac++] = port->database_name;
3343
3344         av[ac] = NULL;
3345
3346         Assert(ac < maxac);
3347
3348         /*
3349          * Debug: print arguments being passed to backend
3350          */
3351         ereport(DEBUG3,
3352                         (errmsg_internal("%s child[%d]: starting with (",
3353                                                          progname, (int) getpid())));
3354         for (i = 0; i < ac; ++i)
3355                 ereport(DEBUG3,
3356                                 (errmsg_internal("\t%s", av[i])));
3357         ereport(DEBUG3,
3358                         (errmsg_internal(")")));
3359
3360         /*
3361          * Make sure we aren't in PostmasterContext anymore.  (We can't delete it
3362          * just yet, though, because InitPostgres will need the HBA data.)
3363          */
3364         MemoryContextSwitchTo(TopMemoryContext);
3365
3366         return (PostgresMain(ac, av, port->user_name));
3367 }
3368
3369
3370 #ifdef EXEC_BACKEND
3371
3372 /*
3373  * postmaster_forkexec -- fork and exec a postmaster subprocess
3374  *
3375  * The caller must have set up the argv array already, except for argv[2]
3376  * which will be filled with the name of the temp variable file.
3377  *
3378  * Returns the child process PID, or -1 on fork failure (a suitable error
3379  * message has been logged on failure).
3380  *
3381  * All uses of this routine will dispatch to SubPostmasterMain in the
3382  * child process.
3383  */
3384 pid_t
3385 postmaster_forkexec(int argc, char *argv[])
3386 {
3387         Port            port;
3388
3389         /* This entry point passes dummy values for the Port variables */
3390         memset(&port, 0, sizeof(port));
3391         return internal_forkexec(argc, argv, &port);
3392 }
3393
3394 /*
3395  * backend_forkexec -- fork/exec off a backend process
3396  *
3397  * Some operating systems (WIN32) don't have fork() so we have to simulate
3398  * it by storing parameters that need to be passed to the child and
3399  * then create a new child process.
3400  *
3401  * returns the pid of the fork/exec'd process, or -1 on failure
3402  */
3403 static pid_t
3404 backend_forkexec(Port *port)
3405 {
3406         char       *av[4];
3407         int                     ac = 0;
3408
3409         av[ac++] = "postgres";
3410         av[ac++] = "--forkbackend";
3411         av[ac++] = NULL;                        /* filled in by internal_forkexec */
3412
3413         av[ac] = NULL;
3414         Assert(ac < lengthof(av));
3415
3416         return internal_forkexec(ac, av, port);
3417 }
3418
3419 #ifndef WIN32
3420
3421 /*
3422  * internal_forkexec non-win32 implementation
3423  *
3424  * - writes out backend variables to the parameter file
3425  * - fork():s, and then exec():s the child process
3426  */
3427 static pid_t
3428 internal_forkexec(int argc, char *argv[], Port *port)
3429 {
3430         static unsigned long tmpBackendFileNum = 0;
3431         pid_t           pid;
3432         char            tmpfilename[MAXPGPATH];
3433         BackendParameters param;
3434         FILE       *fp;
3435
3436         if (!save_backend_variables(&param, port))
3437                 return -1;                              /* log made by save_backend_variables */
3438
3439         /* Calculate name for temp file */
3440         snprintf(tmpfilename, MAXPGPATH, "%s/%s.backend_var.%d.%lu",
3441                          PG_TEMP_FILES_DIR, PG_TEMP_FILE_PREFIX,
3442                          MyProcPid, ++tmpBackendFileNum);
3443
3444         /* Open file */
3445         fp = AllocateFile(tmpfilename, PG_BINARY_W);
3446         if (!fp)
3447         {
3448                 /* As in OpenTemporaryFile, try to make the temp-file directory */
3449                 mkdir(PG_TEMP_FILES_DIR, S_IRWXU);
3450
3451                 fp = AllocateFile(tmpfilename, PG_BINARY_W);
3452                 if (!fp)
3453                 {
3454                         ereport(LOG,
3455                                         (errcode_for_file_access(),
3456                                          errmsg("could not create file \"%s\": %m",
3457                                                         tmpfilename)));
3458                         return -1;
3459                 }
3460         }
3461
3462         if (fwrite(&param, sizeof(param), 1, fp) != 1)
3463         {
3464                 ereport(LOG,
3465                                 (errcode_for_file_access(),
3466                                  errmsg("could not write to file \"%s\": %m", tmpfilename)));
3467                 FreeFile(fp);
3468                 return -1;
3469         }
3470
3471         /* Release file */
3472         if (FreeFile(fp))
3473         {
3474                 ereport(LOG,
3475                                 (errcode_for_file_access(),
3476                                  errmsg("could not write to file \"%s\": %m", tmpfilename)));
3477                 return -1;
3478         }
3479
3480         /* Make sure caller set up argv properly */
3481         Assert(argc >= 3);
3482         Assert(argv[argc] == NULL);
3483         Assert(strncmp(argv[1], "--fork", 6) == 0);
3484         Assert(argv[2] == NULL);
3485
3486         /* Insert temp file name after --fork argument */
3487         argv[2] = tmpfilename;
3488
3489         /* Fire off execv in child */
3490         if ((pid = fork_process()) == 0)
3491         {
3492                 if (execv(postgres_exec_path, argv) < 0)
3493                 {
3494                         ereport(LOG,
3495                                         (errmsg("could not execute server process \"%s\": %m",
3496                                                         postgres_exec_path)));
3497                         /* We're already in the child process here, can't return */
3498                         exit(1);
3499                 }
3500         }
3501
3502         return pid;                                     /* Parent returns pid, or -1 on fork failure */
3503 }
3504 #else                                                   /* WIN32 */
3505
3506 /*
3507  * internal_forkexec win32 implementation
3508  *
3509  * - starts backend using CreateProcess(), in suspended state
3510  * - writes out backend variables to the parameter file
3511  *      - during this, duplicates handles and sockets required for
3512  *        inheritance into the new process
3513  * - resumes execution of the new process once the backend parameter
3514  *       file is complete.
3515  */
3516 static pid_t
3517 internal_forkexec(int argc, char *argv[], Port *port)
3518 {
3519         STARTUPINFO si;
3520         PROCESS_INFORMATION pi;
3521         int                     i;
3522         int                     j;
3523         char            cmdLine[MAXPGPATH * 2];
3524         HANDLE          paramHandle;
3525         BackendParameters *param;
3526         SECURITY_ATTRIBUTES sa;
3527         char            paramHandleStr[32];
3528         win32_deadchild_waitinfo *childinfo;
3529
3530         /* Make sure caller set up argv properly */
3531         Assert(argc >= 3);
3532         Assert(argv[argc] == NULL);
3533         Assert(strncmp(argv[1], "--fork", 6) == 0);
3534         Assert(argv[2] == NULL);
3535
3536         /* Set up shared memory for parameter passing */
3537         ZeroMemory(&sa, sizeof(sa));
3538         sa.nLength = sizeof(sa);
3539         sa.bInheritHandle = TRUE;
3540         paramHandle = CreateFileMapping(INVALID_HANDLE_VALUE,
3541                                                                         &sa,
3542                                                                         PAGE_READWRITE,
3543                                                                         0,
3544                                                                         sizeof(BackendParameters),
3545                                                                         NULL);
3546         if (paramHandle == INVALID_HANDLE_VALUE)
3547         {
3548                 elog(LOG, "could not create backend parameter file mapping: error code %d",
3549                          (int) GetLastError());
3550                 return -1;
3551         }
3552
3553         param = MapViewOfFile(paramHandle, FILE_MAP_WRITE, 0, 0, sizeof(BackendParameters));
3554         if (!param)
3555         {
3556                 elog(LOG, "could not map backend parameter memory: error code %d",
3557                          (int) GetLastError());
3558                 CloseHandle(paramHandle);
3559                 return -1;
3560         }
3561
3562         /* Insert temp file name after --fork argument */
3563         sprintf(paramHandleStr, "%lu", (DWORD) paramHandle);
3564         argv[2] = paramHandleStr;
3565
3566         /* Format the cmd line */
3567         cmdLine[sizeof(cmdLine) - 1] = '\0';
3568         cmdLine[sizeof(cmdLine) - 2] = '\0';
3569         snprintf(cmdLine, sizeof(cmdLine) - 1, "\"%s\"", postgres_exec_path);
3570         i = 0;
3571         while (argv[++i] != NULL)
3572         {
3573                 j = strlen(cmdLine);
3574                 snprintf(cmdLine + j, sizeof(cmdLine) - 1 - j, " \"%s\"", argv[i]);
3575         }
3576         if (cmdLine[sizeof(cmdLine) - 2] != '\0')
3577         {
3578                 elog(LOG, "subprocess command line too long");
3579                 return -1;
3580         }
3581
3582         memset(&pi, 0, sizeof(pi));
3583         memset(&si, 0, sizeof(si));
3584         si.cb = sizeof(si);
3585
3586         /*
3587          * Create the subprocess in a suspended state. This will be resumed later,
3588          * once we have written out the parameter file.
3589          */
3590         if (!CreateProcess(NULL, cmdLine, NULL, NULL, TRUE, CREATE_SUSPENDED,
3591                                            NULL, NULL, &si, &pi))
3592         {
3593                 elog(LOG, "CreateProcess call failed: %m (error code %d)",
3594                          (int) GetLastError());
3595                 return -1;
3596         }
3597
3598         if (!save_backend_variables(param, port, pi.hProcess, pi.dwProcessId))
3599         {
3600                 /*
3601                  * log made by save_backend_variables, but we have to clean up the
3602                  * mess with the half-started process
3603                  */
3604                 if (!TerminateProcess(pi.hProcess, 255))
3605                         ereport(LOG,
3606                                         (errmsg_internal("could not terminate unstarted process: error code %d",
3607                                                                          (int) GetLastError())));
3608                 CloseHandle(pi.hProcess);
3609                 CloseHandle(pi.hThread);
3610                 return -1;                              /* log made by save_backend_variables */
3611         }
3612
3613         /* Drop the parameter shared memory that is now inherited to the backend */
3614         if (!UnmapViewOfFile(param))
3615                 elog(LOG, "could not unmap view of backend parameter file: error code %d",
3616                          (int) GetLastError());
3617         if (!CloseHandle(paramHandle))
3618                 elog(LOG, "could not close handle to backend parameter file: error code %d",
3619                          (int) GetLastError());
3620
3621         /*
3622          * Reserve the memory region used by our main shared memory segment before we
3623          * resume the child process.
3624          */
3625         if (!pgwin32_ReserveSharedMemoryRegion(pi.hProcess))
3626         {
3627                 /*
3628                  * Failed to reserve the memory, so terminate the newly created
3629                  * process and give up.
3630                  */
3631                 if (!TerminateProcess(pi.hProcess, 255))
3632                         ereport(LOG,
3633                                         (errmsg_internal("could not terminate process that failed to reserve memory: error code %d",
3634                                                                          (int) GetLastError())));
3635                 CloseHandle(pi.hProcess);
3636                 CloseHandle(pi.hThread);
3637                 return -1;                      /* logging done made by pgwin32_ReserveSharedMemoryRegion() */
3638         }
3639
3640         /*
3641          * Now that the backend variables are written out, we start the child
3642          * thread so it can start initializing while we set up the rest of the
3643          * parent state.
3644          */
3645         if (ResumeThread(pi.hThread) == -1)
3646         {
3647                 if (!TerminateProcess(pi.hProcess, 255))
3648                 {
3649                         ereport(LOG,
3650                                         (errmsg_internal("could not terminate unstartable process: error code %d",
3651                                                                          (int) GetLastError())));
3652                         CloseHandle(pi.hProcess);
3653                         CloseHandle(pi.hThread);
3654                         return -1;
3655                 }
3656                 CloseHandle(pi.hProcess);
3657                 CloseHandle(pi.hThread);
3658                 ereport(LOG,
3659                                 (errmsg_internal("could not resume thread of unstarted process: error code %d",
3660                                                                  (int) GetLastError())));
3661                 return -1;
3662         }
3663
3664         /*
3665          * Queue a waiter for to signal when this child dies. The wait will be
3666          * handled automatically by an operating system thread pool.
3667          *
3668          * Note: use malloc instead of palloc, since it needs to be thread-safe.
3669          * Struct will be free():d from the callback function that runs on a
3670          * different thread.
3671          */
3672         childinfo = malloc(sizeof(win32_deadchild_waitinfo));
3673         if (!childinfo)
3674                 ereport(FATAL,
3675                                 (errcode(ERRCODE_OUT_OF_MEMORY),
3676                                  errmsg("out of memory")));
3677
3678         childinfo->procHandle = pi.hProcess;
3679         childinfo->procId = pi.dwProcessId;
3680
3681         if (!RegisterWaitForSingleObject(&childinfo->waitHandle,
3682                                                                          pi.hProcess,
3683                                                                          pgwin32_deadchild_callback,
3684                                                                          childinfo,
3685                                                                          INFINITE,
3686                                                                 WT_EXECUTEONLYONCE | WT_EXECUTEINWAITTHREAD))
3687                 ereport(FATAL,
3688                 (errmsg_internal("could not register process for wait: error code %d",
3689                                                  (int) GetLastError())));
3690
3691         /* Don't close pi.hProcess here - the wait thread needs access to it */
3692
3693         CloseHandle(pi.hThread);
3694
3695         return pi.dwProcessId;
3696 }
3697 #endif   /* WIN32 */
3698
3699
3700 /*
3701  * SubPostmasterMain -- Get the fork/exec'd process into a state equivalent
3702  *                      to what it would be if we'd simply forked on Unix, and then
3703  *                      dispatch to the appropriate place.
3704  *
3705  * The first two command line arguments are expected to be "--forkFOO"
3706  * (where FOO indicates which postmaster child we are to become), and
3707  * the name of a variables file that we can read to load data that would
3708  * have been inherited by fork() on Unix.  Remaining arguments go to the
3709  * subprocess FooMain() routine.
3710  */
3711 int
3712 SubPostmasterMain(int argc, char *argv[])
3713 {
3714         Port            port;
3715
3716         /* Do this sooner rather than later... */
3717         IsUnderPostmaster = true;       /* we are a postmaster subprocess now */
3718
3719         MyProcPid = getpid();           /* reset MyProcPid */
3720
3721         MyStartTime = time(NULL);
3722
3723         /*
3724          * make sure stderr is in binary mode before anything can possibly be
3725          * written to it, in case it's actually the syslogger pipe, so the pipe
3726          * chunking protocol isn't disturbed. Non-logpipe data gets translated on
3727          * redirection (e.g. via pg_ctl -l) anyway.
3728          */
3729 #ifdef WIN32
3730         _setmode(fileno(stderr), _O_BINARY);
3731 #endif
3732
3733         /* Lose the postmaster's on-exit routines (really a no-op) */
3734         on_exit_reset();
3735
3736         /* In EXEC_BACKEND case we will not have inherited these settings */
3737         IsPostmasterEnvironment = true;
3738         whereToSendOutput = DestNone;
3739
3740         /* Setup essential subsystems (to ensure elog() behaves sanely) */
3741         MemoryContextInit();
3742         InitializeGUCOptions();
3743
3744         /* Read in the variables file */
3745         memset(&port, 0, sizeof(Port));
3746         read_backend_variables(argv[2], &port);
3747
3748         /*
3749          * Set up memory area for GSS information. Mirrors the code in ConnCreate
3750          * for the non-exec case.
3751          */
3752 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
3753         port.gss = (pg_gssinfo *) calloc(1, sizeof(pg_gssinfo));
3754         if (!port.gss)
3755                 ereport(FATAL,
3756                                 (errcode(ERRCODE_OUT_OF_MEMORY),
3757                                  errmsg("out of memory")));
3758 #endif
3759
3760         /* Check we got appropriate args */
3761         if (argc < 3)
3762                 elog(FATAL, "invalid subpostmaster invocation");
3763
3764         /*
3765          * If appropriate, physically re-attach to shared memory segment. We want
3766          * to do this before going any further to ensure that we can attach at the
3767          * same address the postmaster used.
3768          */
3769         if (strcmp(argv[1], "--forkbackend") == 0 ||
3770                 strcmp(argv[1], "--forkavlauncher") == 0 ||
3771                 strcmp(argv[1], "--forkavworker") == 0 ||
3772                 strcmp(argv[1], "--forkboot") == 0)
3773                 PGSharedMemoryReAttach();
3774
3775         /* autovacuum needs this set before calling InitProcess */
3776         if (strcmp(argv[1], "--forkavlauncher") == 0)
3777                 AutovacuumLauncherIAm();
3778         if (strcmp(argv[1], "--forkavworker") == 0)
3779                 AutovacuumWorkerIAm();
3780
3781         /*
3782          * Start our win32 signal implementation. This has to be done after we
3783          * read the backend variables, because we need to pick up the signal pipe
3784          * from the parent process.
3785          */
3786 #ifdef WIN32
3787         pgwin32_signal_initialize();
3788 #endif
3789
3790         /* In EXEC_BACKEND case we will not have inherited these settings */
3791         pqinitmask();
3792         PG_SETMASK(&BlockSig);
3793
3794         /* Read in remaining GUC variables */
3795         read_nondefault_variables();
3796
3797         /*
3798          * Reload any libraries that were preloaded by the postmaster.  Since we
3799          * exec'd this process, those libraries didn't come along with us; but we
3800          * should load them into all child processes to be consistent with the
3801          * non-EXEC_BACKEND behavior.
3802          */
3803         process_shared_preload_libraries();
3804
3805         /* Run backend or appropriate child */
3806         if (strcmp(argv[1], "--forkbackend") == 0)
3807         {
3808                 Assert(argc == 3);              /* shouldn't be any more args */
3809
3810                 /* Close the postmaster's sockets */
3811                 ClosePostmasterPorts(false);
3812
3813                 /*
3814                  * Need to reinitialize the SSL library in the backend, since the
3815                  * context structures contain function pointers and cannot be passed
3816                  * through the parameter file.
3817                  *
3818                  * XXX should we do this in all child processes?  For the moment it's
3819                  * enough to do it in backend children.
3820                  */
3821 #ifdef USE_SSL
3822                 if (EnableSSL)
3823                         secure_initialize();
3824 #endif
3825
3826                 /*
3827                  * Perform additional initialization and collect startup packet.
3828                  *
3829                  * We want to do this before InitProcess() for a couple of reasons: 1.
3830                  * so that we aren't eating up a PGPROC slot while waiting on the
3831                  * client. 2. so that if InitProcess() fails due to being out of
3832                  * PGPROC slots, we have already initialized libpq and are able to
3833                  * report the error to the client.
3834                  */
3835                 BackendInitialize(&port);
3836
3837                 /* Restore basic shared memory pointers */
3838                 InitShmemAccess(UsedShmemSegAddr);
3839
3840                 /* Need a PGPROC to run CreateSharedMemoryAndSemaphores */
3841                 InitProcess();
3842
3843                 /*
3844                  * Attach process to shared data structures.  If testing EXEC_BACKEND
3845                  * on Linux, you must run this as root before starting the postmaster:
3846                  *
3847                  * echo 0 >/proc/sys/kernel/randomize_va_space
3848                  *
3849                  * This prevents a randomized stack base address that causes child
3850                  * shared memory to be at a different address than the parent, making
3851                  * it impossible to attached to shared memory.  Return the value to
3852                  * '1' when finished.
3853                  */
3854                 CreateSharedMemoryAndSemaphores(false, 0);
3855
3856                 /* And run the backend */
3857                 proc_exit(BackendRun(&port));
3858         }
3859         if (strcmp(argv[1], "--forkboot") == 0)
3860         {
3861                 /* Close the postmaster's sockets */
3862                 ClosePostmasterPorts(false);
3863
3864                 /* Restore basic shared memory pointers */
3865                 InitShmemAccess(UsedShmemSegAddr);
3866
3867                 /* Need a PGPROC to run CreateSharedMemoryAndSemaphores */
3868                 InitAuxiliaryProcess();
3869
3870                 /* Attach process to shared data structures */
3871                 CreateSharedMemoryAndSemaphores(false, 0);
3872
3873                 AuxiliaryProcessMain(argc - 2, argv + 2);
3874                 proc_exit(0);
3875         }
3876         if (strcmp(argv[1], "--forkavlauncher") == 0)
3877         {
3878                 /* Close the postmaster's sockets */
3879                 ClosePostmasterPorts(false);
3880
3881                 /* Restore basic shared memory pointers */
3882                 InitShmemAccess(UsedShmemSegAddr);
3883
3884                 /* Need a PGPROC to run CreateSharedMemoryAndSemaphores */
3885                 InitProcess();
3886
3887                 /* Attach process to shared data structures */
3888                 CreateSharedMemoryAndSemaphores(false, 0);
3889
3890                 AutoVacLauncherMain(argc - 2, argv + 2);
3891                 proc_exit(0);
3892         }
3893         if (strcmp(argv[1], "--forkavworker") == 0)
3894         {
3895                 /* Close the postmaster's sockets */
3896                 ClosePostmasterPorts(false);
3897
3898                 /* Restore basic shared memory pointers */
3899                 InitShmemAccess(UsedShmemSegAddr);
3900
3901                 /* Need a PGPROC to run CreateSharedMemoryAndSemaphores */
3902                 InitProcess();
3903
3904                 /* Attach process to shared data structures */
3905                 CreateSharedMemoryAndSemaphores(false, 0);
3906
3907                 AutoVacWorkerMain(argc - 2, argv + 2);
3908                 proc_exit(0);
3909         }
3910         if (strcmp(argv[1], "--forkarch") == 0)
3911         {
3912                 /* Close the postmaster's sockets */
3913                 ClosePostmasterPorts(false);
3914
3915                 /* Do not want to attach to shared memory */
3916
3917                 PgArchiverMain(argc, argv);
3918                 proc_exit(0);
3919         }
3920         if (strcmp(argv[1], "--forkcol") == 0)
3921         {
3922                 /* Close the postmaster's sockets */
3923                 ClosePostmasterPorts(false);
3924
3925                 /* Do not want to attach to shared memory */
3926
3927                 PgstatCollectorMain(argc, argv);
3928                 proc_exit(0);
3929         }
3930         if (strcmp(argv[1], "--forklog") == 0)
3931         {
3932                 /* Close the postmaster's sockets */
3933                 ClosePostmasterPorts(true);
3934
3935                 /* Do not want to attach to shared memory */
3936
3937                 SysLoggerMain(argc, argv);
3938                 proc_exit(0);
3939         }
3940
3941         return 1;                                       /* shouldn't get here */
3942 }
3943 #endif   /* EXEC_BACKEND */
3944
3945
3946 /*
3947  * ExitPostmaster -- cleanup
3948  *
3949  * Do NOT call exit() directly --- always go through here!
3950  */
3951 static void
3952 ExitPostmaster(int status)
3953 {
3954         /* should cleanup shared memory and kill all backends */
3955
3956         /*
3957          * Not sure of the semantics here.      When the Postmaster dies, should the
3958          * backends all be killed? probably not.
3959          *
3960          * MUST         -- vadim 05-10-1999
3961          */
3962
3963         proc_exit(status);
3964 }
3965
3966 /*
3967  * sigusr1_handler - handle signal conditions from child processes
3968  */
3969 static void
3970 sigusr1_handler(SIGNAL_ARGS)
3971 {
3972         int                     save_errno = errno;
3973
3974         PG_SETMASK(&BlockSig);
3975
3976         /*
3977          * RECOVERY_STARTED and RECOVERY_CONSISTENT signals are ignored in
3978          * unexpected states. If the startup process quickly starts up, completes
3979          * recovery, exits, we might process the death of the startup process
3980          * first. We don't want to go back to recovery in that case.
3981          */
3982         if (CheckPostmasterSignal(PMSIGNAL_RECOVERY_STARTED) &&
3983                 pmState == PM_STARTUP)
3984         {
3985                 /* WAL redo has started. We're out of reinitialization. */
3986                 FatalError = false;
3987
3988                 /*
3989                  * Crank up the background writer.      It doesn't matter if this fails,
3990                  * we'll just try again later.
3991                  */
3992                 Assert(BgWriterPID == 0);
3993                 BgWriterPID = StartBackgroundWriter();
3994
3995                 pmState = PM_RECOVERY;
3996         }
3997         if (CheckPostmasterSignal(PMSIGNAL_RECOVERY_CONSISTENT) &&
3998                 pmState == PM_RECOVERY)
3999         {
4000                 /*
4001                  * Likewise, start other special children as needed.
4002                  */
4003                 Assert(PgStatPID == 0);
4004                 PgStatPID = pgstat_start();
4005
4006                 /* XXX at this point we could accept read-only connections */
4007                 ereport(DEBUG1,
4008                                 (errmsg("database system is in consistent recovery mode")));
4009
4010                 pmState = PM_RECOVERY_CONSISTENT;
4011         }
4012
4013         if (CheckPostmasterSignal(PMSIGNAL_WAKEN_ARCHIVER) &&
4014                 PgArchPID != 0)
4015         {
4016                 /*
4017                  * Send SIGUSR1 to archiver process, to wake it up and begin archiving
4018                  * next transaction log file.
4019                  */
4020                 signal_child(PgArchPID, SIGUSR1);
4021         }
4022
4023         if (CheckPostmasterSignal(PMSIGNAL_ROTATE_LOGFILE) &&
4024                 SysLoggerPID != 0)
4025         {
4026                 /* Tell syslogger to rotate logfile */
4027                 signal_child(SysLoggerPID, SIGUSR1);
4028         }
4029
4030         if (CheckPostmasterSignal(PMSIGNAL_START_AUTOVAC_LAUNCHER))
4031         {
4032                 /*
4033                  * Start one iteration of the autovacuum daemon, even if autovacuuming
4034                  * is nominally not enabled.  This is so we can have an active defense
4035                  * against transaction ID wraparound.  We set a flag for the main loop
4036                  * to do it rather than trying to do it here --- this is because the
4037                  * autovac process itself may send the signal, and we want to handle
4038                  * that by launching another iteration as soon as the current one
4039                  * completes.
4040                  */
4041                 start_autovac_launcher = true;
4042         }
4043
4044         if (CheckPostmasterSignal(PMSIGNAL_START_AUTOVAC_WORKER))
4045         {
4046                 /* The autovacuum launcher wants us to start a worker process. */
4047                 StartAutovacuumWorker();
4048         }
4049
4050         PG_SETMASK(&UnBlockSig);
4051
4052         errno = save_errno;
4053 }
4054
4055 /*
4056  * Timeout or shutdown signal from postmaster while processing startup packet.
4057  * Cleanup and exit(1).
4058  *
4059  * XXX: possible future improvement: try to send a message indicating
4060  * why we are disconnecting.  Problem is to be sure we don't block while
4061  * doing so, nor mess up SSL initialization.  In practice, if the client
4062  * has wedged here, it probably couldn't do anything with the message anyway.
4063  */
4064 static void
4065 startup_die(SIGNAL_ARGS)
4066 {
4067         proc_exit(1);
4068 }
4069
4070 /*
4071  * Dummy signal handler
4072  *
4073  * We use this for signals that we don't actually use in the postmaster,
4074  * but we do use in backends.  If we were to SIG_IGN such signals in the
4075  * postmaster, then a newly started backend might drop a signal that arrives
4076  * before it's able to reconfigure its signal processing.  (See notes in
4077  * tcop/postgres.c.)
4078  */
4079 static void
4080 dummy_handler(SIGNAL_ARGS)
4081 {
4082 }
4083
4084 /*
4085  * RandomSalt
4086  */
4087 static void
4088 RandomSalt(char *md5Salt)
4089 {
4090         long            rand;
4091
4092         /*
4093          * We use % 255, sacrificing one possible byte value, so as to ensure that
4094          * all bits of the random() value participate in the result. While at it,
4095          * add one to avoid generating any null bytes.
4096          */
4097         rand = PostmasterRandom();
4098         md5Salt[0] = (rand % 255) + 1;
4099         rand = PostmasterRandom();
4100         md5Salt[1] = (rand % 255) + 1;
4101         rand = PostmasterRandom();
4102         md5Salt[2] = (rand % 255) + 1;
4103         rand = PostmasterRandom();
4104         md5Salt[3] = (rand % 255) + 1;
4105 }
4106
4107 /*
4108  * PostmasterRandom
4109  */
4110 static long
4111 PostmasterRandom(void)
4112 {
4113         /*
4114          * Select a random seed at the time of first receiving a request.
4115          */
4116         if (random_seed == 0)
4117         {
4118                 do
4119                 {
4120                         struct timeval random_stop_time;
4121
4122                         gettimeofday(&random_stop_time, NULL);
4123
4124                         /*
4125                          * We are not sure how much precision is in tv_usec, so we swap
4126                          * the high and low 16 bits of 'random_stop_time' and XOR them
4127                          * with 'random_start_time'. On the off chance that the result is
4128                          * 0, we loop until it isn't.
4129                          */
4130                         random_seed = random_start_time.tv_usec ^
4131                                 ((random_stop_time.tv_usec << 16) |
4132                                  ((random_stop_time.tv_usec >> 16) & 0xffff));
4133                 }
4134                 while (random_seed == 0);
4135
4136                 srandom(random_seed);
4137         }
4138
4139         return random();
4140 }
4141
4142 /*
4143  * Count up number of child processes (excluding special children and
4144  * dead_end children)
4145  */
4146 static int
4147 CountChildren(void)
4148 {
4149         Dlelem     *curr;
4150         int                     cnt = 0;
4151
4152         for (curr = DLGetHead(BackendList); curr; curr = DLGetSucc(curr))
4153         {
4154                 Backend    *bp = (Backend *) DLE_VAL(curr);
4155
4156                 if (!bp->dead_end)
4157                         cnt++;
4158         }
4159         return cnt;
4160 }
4161
4162
4163 /*
4164  * StartChildProcess -- start an auxiliary process for the postmaster
4165  *
4166  * xlop determines what kind of child will be started.  All child types
4167  * initially go to AuxiliaryProcessMain, which will handle common setup.
4168  *
4169  * Return value of StartChildProcess is subprocess' PID, or 0 if failed
4170  * to start subprocess.
4171  */
4172 static pid_t
4173 StartChildProcess(AuxProcType type)
4174 {
4175         pid_t           pid;
4176         char       *av[10];
4177         int                     ac = 0;
4178         char            typebuf[32];
4179
4180         /*
4181          * Set up command-line arguments for subprocess
4182          */
4183         av[ac++] = "postgres";
4184
4185 #ifdef EXEC_BACKEND
4186         av[ac++] = "--forkboot";
4187         av[ac++] = NULL;                        /* filled in by postmaster_forkexec */
4188 #endif
4189
4190         snprintf(typebuf, sizeof(typebuf), "-x%d", type);
4191         av[ac++] = typebuf;
4192
4193         av[ac] = NULL;
4194         Assert(ac < lengthof(av));
4195
4196 #ifdef EXEC_BACKEND
4197         pid = postmaster_forkexec(ac, av);
4198 #else                                                   /* !EXEC_BACKEND */
4199         pid = fork_process();
4200
4201         if (pid == 0)                           /* child */
4202         {
4203                 IsUnderPostmaster = true;               /* we are a postmaster subprocess now */
4204
4205                 /* Close the postmaster's sockets */
4206                 ClosePostmasterPorts(false);
4207
4208                 /* Lose the postmaster's on-exit routines and port connections */
4209                 on_exit_reset();
4210
4211                 /* Release postmaster's working memory context */
4212                 MemoryContextSwitchTo(TopMemoryContext);
4213                 MemoryContextDelete(PostmasterContext);
4214                 PostmasterContext = NULL;
4215
4216                 AuxiliaryProcessMain(ac, av);
4217                 ExitPostmaster(0);
4218         }
4219 #endif   /* EXEC_BACKEND */
4220
4221         if (pid < 0)
4222         {
4223                 /* in parent, fork failed */
4224                 int                     save_errno = errno;
4225
4226                 errno = save_errno;
4227                 switch (type)
4228                 {
4229                         case StartupProcess:
4230                                 ereport(LOG,
4231                                                 (errmsg("could not fork startup process: %m")));
4232                                 break;
4233                         case BgWriterProcess:
4234                                 ereport(LOG,
4235                                    (errmsg("could not fork background writer process: %m")));
4236                                 break;
4237                         case WalWriterProcess:
4238                                 ereport(LOG,
4239                                                 (errmsg("could not fork WAL writer process: %m")));
4240                                 break;
4241                         default:
4242                                 ereport(LOG,
4243                                                 (errmsg("could not fork process: %m")));
4244                                 break;
4245                 }
4246
4247                 /*
4248                  * fork failure is fatal during startup, but there's no need to choke
4249                  * immediately if starting other child types fails.
4250                  */
4251                 if (type == StartupProcess)
4252                         ExitPostmaster(1);
4253                 return 0;
4254         }
4255
4256         /*
4257          * in parent, successful fork
4258          */
4259         return pid;
4260 }
4261
4262 /*
4263  * StartAutovacuumWorker
4264  *              Start an autovac worker process.
4265  *
4266  * This function is here because it enters the resulting PID into the
4267  * postmaster's private backends list.
4268  *
4269  * NB -- this code very roughly matches BackendStartup.
4270  */
4271 static void
4272 StartAutovacuumWorker(void)
4273 {
4274         Backend    *bn;
4275
4276         /*
4277          * If not in condition to run a process, don't try, but handle it like a
4278          * fork failure.  This does not normally happen, since the signal is only
4279          * supposed to be sent by autovacuum launcher when it's OK to do it, but
4280          * we have to check to avoid race-condition problems during DB state
4281          * changes.
4282          */
4283         if (canAcceptConnections() == CAC_OK)
4284         {
4285                 bn = (Backend *) malloc(sizeof(Backend));
4286                 if (bn)
4287                 {
4288                         /*
4289                          * Compute the cancel key that will be assigned to this session.
4290                          * We probably don't need cancel keys for autovac workers, but
4291                          * we'd better have something random in the field to prevent
4292                          * unfriendly people from sending cancels to them.
4293                          */
4294                         MyCancelKey = PostmasterRandom();
4295                         bn->cancel_key = MyCancelKey;
4296
4297                         /* Autovac workers are not dead_end and need a child slot */
4298                         bn->dead_end = false;
4299                         bn->child_slot = MyPMChildSlot = AssignPostmasterChildSlot();
4300
4301                         bn->pid = StartAutoVacWorker();
4302                         if (bn->pid > 0)
4303                         {
4304                                 bn->is_autovacuum = true;
4305                                 DLInitElem(&bn->elem, bn);
4306                                 DLAddHead(BackendList, &bn->elem);
4307 #ifdef EXEC_BACKEND
4308                                 ShmemBackendArrayAdd(bn);
4309 #endif
4310                                 /* all OK */
4311                                 return;
4312                         }
4313
4314                         /*
4315                          * fork failed, fall through to report -- actual error message was
4316                          * logged by StartAutoVacWorker
4317                          */
4318                         (void) ReleasePostmasterChildSlot(bn->child_slot);
4319                         free(bn);
4320                 }
4321                 else
4322                         ereport(LOG,
4323                                         (errcode(ERRCODE_OUT_OF_MEMORY),
4324                                          errmsg("out of memory")));
4325         }
4326
4327         /*
4328          * Report the failure to the launcher, if it's running.  (If it's not, we
4329          * might not even be connected to shared memory, so don't try to call
4330          * AutoVacWorkerFailed.)  Note that we also need to signal it so that it
4331          * responds to the condition, but we don't do that here, instead waiting
4332          * for ServerLoop to do it.  This way we avoid a ping-pong signalling in
4333          * quick succession between the autovac launcher and postmaster in case
4334          * things get ugly.
4335          */
4336         if (AutoVacPID != 0)
4337         {
4338                 AutoVacWorkerFailed();
4339                 avlauncher_needs_signal = true;
4340         }
4341 }
4342
4343 /*
4344  * Create the opts file
4345  */
4346 static bool
4347 CreateOptsFile(int argc, char *argv[], char *fullprogname)
4348 {
4349         FILE       *fp;
4350         int                     i;
4351
4352 #define OPTS_FILE       "postmaster.opts"
4353
4354         if ((fp = fopen(OPTS_FILE, "w")) == NULL)
4355         {
4356                 elog(LOG, "could not create file \"%s\": %m", OPTS_FILE);
4357                 return false;
4358         }
4359
4360         fprintf(fp, "%s", fullprogname);
4361         for (i = 1; i < argc; i++)
4362                 fprintf(fp, " \"%s\"", argv[i]);
4363         fputs("\n", fp);
4364
4365         if (fclose(fp))
4366         {
4367                 elog(LOG, "could not write file \"%s\": %m", OPTS_FILE);
4368                 return false;
4369         }
4370
4371         return true;
4372 }
4373
4374
4375 /*
4376  * MaxLivePostmasterChildren
4377  *
4378  * This reports the number of entries needed in per-child-process arrays
4379  * (the PMChildFlags array, and if EXEC_BACKEND the ShmemBackendArray).
4380  * These arrays include regular backends and autovac workers, but not special
4381  * children nor dead_end children.      This allows the arrays to have a fixed
4382  * maximum size, to wit the same too-many-children limit enforced by
4383  * canAcceptConnections().      The exact value isn't too critical as long as
4384  * it's more than MaxBackends.
4385  */
4386 int
4387 MaxLivePostmasterChildren(void)
4388 {
4389         return 2 * MaxBackends;
4390 }
4391
4392
4393 #ifdef EXEC_BACKEND
4394
4395 /*
4396  * The following need to be available to the save/restore_backend_variables
4397  * functions
4398  */
4399 extern slock_t *ShmemLock;
4400 extern LWLock *LWLockArray;
4401 extern slock_t *ProcStructLock;
4402 extern PROC_HDR *ProcGlobal;
4403 extern PGPROC *AuxiliaryProcs;
4404 extern PMSignalData *PMSignalState;
4405 extern int      pgStatSock;
4406
4407 #ifndef WIN32
4408 #define write_inheritable_socket(dest, src, childpid) ((*(dest) = (src)), true)
4409 #define read_inheritable_socket(dest, src) (*(dest) = *(src))
4410 #else
4411 static bool write_duplicated_handle(HANDLE *dest, HANDLE src, HANDLE child);
4412 static bool write_inheritable_socket(InheritableSocket *dest, SOCKET src,
4413                                                  pid_t childPid);
4414 static void read_inheritable_socket(SOCKET *dest, InheritableSocket *src);
4415 #endif
4416
4417
4418 /* Save critical backend variables into the BackendParameters struct */
4419 #ifndef WIN32
4420 static bool
4421 save_backend_variables(BackendParameters *param, Port *port)
4422 #else
4423 static bool
4424 save_backend_variables(BackendParameters *param, Port *port,
4425                                            HANDLE childProcess, pid_t childPid)
4426 #endif
4427 {
4428         memcpy(&param->port, port, sizeof(Port));
4429         if (!write_inheritable_socket(&param->portsocket, port->sock, childPid))
4430                 return false;
4431
4432         strlcpy(param->DataDir, DataDir, MAXPGPATH);
4433
4434         memcpy(&param->ListenSocket, &ListenSocket, sizeof(ListenSocket));
4435
4436         param->MyCancelKey = MyCancelKey;
4437         param->MyPMChildSlot = MyPMChildSlot;
4438
4439         param->UsedShmemSegID = UsedShmemSegID;
4440         param->UsedShmemSegAddr = UsedShmemSegAddr;
4441
4442         param->ShmemLock = ShmemLock;
4443         param->ShmemVariableCache = ShmemVariableCache;
4444         param->ShmemBackendArray = ShmemBackendArray;
4445
4446         param->LWLockArray = LWLockArray;
4447         param->ProcStructLock = ProcStructLock;
4448         param->ProcGlobal = ProcGlobal;
4449         param->AuxiliaryProcs = AuxiliaryProcs;
4450         param->PMSignalState = PMSignalState;
4451         if (!write_inheritable_socket(&param->pgStatSock, pgStatSock, childPid))
4452                 return false;
4453
4454         param->PostmasterPid = PostmasterPid;
4455         param->PgStartTime = PgStartTime;
4456         param->PgReloadTime = PgReloadTime;
4457
4458         param->redirection_done = redirection_done;
4459
4460 #ifdef WIN32
4461         param->PostmasterHandle = PostmasterHandle;
4462         if (!write_duplicated_handle(&param->initial_signal_pipe,
4463                                                         pgwin32_create_signal_listener(childPid),
4464                                                         childProcess))
4465                 return false;
4466 #endif
4467
4468         memcpy(&param->syslogPipe, &syslogPipe, sizeof(syslogPipe));
4469
4470         strlcpy(param->my_exec_path, my_exec_path, MAXPGPATH);
4471
4472         strlcpy(param->pkglib_path, pkglib_path, MAXPGPATH);
4473
4474         strlcpy(param->ExtraOptions, ExtraOptions, MAXPGPATH);
4475
4476         return true;
4477 }
4478
4479
4480 #ifdef WIN32
4481 /*
4482  * Duplicate a handle for usage in a child process, and write the child
4483  * process instance of the handle to the parameter file.
4484  */
4485 static bool
4486 write_duplicated_handle(HANDLE *dest, HANDLE src, HANDLE childProcess)
4487 {
4488         HANDLE          hChild = INVALID_HANDLE_VALUE;
4489
4490         if (!DuplicateHandle(GetCurrentProcess(),
4491                                                  src,
4492                                                  childProcess,
4493                                                  &hChild,
4494                                                  0,
4495                                                  TRUE,
4496                                                  DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS))
4497         {
4498                 ereport(LOG,
4499                                 (errmsg_internal("could not duplicate handle to be written to backend parameter file: error code %d",
4500                                                                  (int) GetLastError())));
4501                 return false;
4502         }
4503
4504         *dest = hChild;
4505         return true;
4506 }
4507
4508 /*
4509  * Duplicate a socket for usage in a child process, and write the resulting
4510  * structure to the parameter file.
4511  * This is required because a number of LSPs (Layered Service Providers) very
4512  * common on Windows (antivirus, firewalls, download managers etc) break
4513  * straight socket inheritance.
4514  */
4515 static bool
4516 write_inheritable_socket(InheritableSocket *dest, SOCKET src, pid_t childpid)
4517 {
4518         dest->origsocket = src;
4519         if (src != 0 && src != -1)
4520         {
4521                 /* Actual socket */
4522                 if (WSADuplicateSocket(src, childpid, &dest->wsainfo) != 0)
4523                 {
4524                         ereport(LOG,
4525                                         (errmsg("could not duplicate socket %d for use in backend: error code %d",
4526                                                         src, WSAGetLastError())));
4527                         return false;
4528                 }
4529         }
4530         return true;
4531 }
4532
4533 /*
4534  * Read a duplicate socket structure back, and get the socket descriptor.
4535  */
4536 static void
4537 read_inheritable_socket(SOCKET *dest, InheritableSocket *src)
4538 {
4539         SOCKET          s;
4540
4541         if (src->origsocket == -1 || src->origsocket == 0)
4542         {
4543                 /* Not a real socket! */
4544                 *dest = src->origsocket;
4545         }
4546         else
4547         {
4548                 /* Actual socket, so create from structure */
4549                 s = WSASocket(FROM_PROTOCOL_INFO,
4550                                           FROM_PROTOCOL_INFO,
4551                                           FROM_PROTOCOL_INFO,
4552                                           &src->wsainfo,
4553                                           0,
4554                                           0);
4555                 if (s == INVALID_SOCKET)
4556                 {
4557                         write_stderr("could not create inherited socket: error code %d\n",
4558                                                  WSAGetLastError());
4559                         exit(1);
4560                 }
4561                 *dest = s;
4562
4563                 /*
4564                  * To make sure we don't get two references to the same socket, close
4565                  * the original one. (This would happen when inheritance actually
4566                  * works..
4567                  */
4568                 closesocket(src->origsocket);
4569         }
4570 }
4571 #endif
4572
4573 static void
4574 read_backend_variables(char *id, Port *port)
4575 {
4576         BackendParameters param;
4577
4578 #ifndef WIN32
4579         /* Non-win32 implementation reads from file */
4580         FILE       *fp;
4581
4582         /* Open file */
4583         fp = AllocateFile(id, PG_BINARY_R);
4584         if (!fp)
4585         {
4586                 write_stderr("could not read from backend variables file \"%s\": %s\n",
4587                                          id, strerror(errno));
4588                 exit(1);
4589         }
4590
4591         if (fread(&param, sizeof(param), 1, fp) != 1)
4592         {
4593                 write_stderr("could not read from backend variables file \"%s\": %s\n",
4594                                          id, strerror(errno));
4595                 exit(1);
4596         }
4597
4598         /* Release file */
4599         FreeFile(fp);
4600         if (unlink(id) != 0)
4601         {
4602                 write_stderr("could not remove file \"%s\": %s\n",
4603                                          id, strerror(errno));
4604                 exit(1);
4605         }
4606 #else
4607         /* Win32 version uses mapped file */
4608         HANDLE          paramHandle;
4609         BackendParameters *paramp;
4610
4611         paramHandle = (HANDLE) atol(id);
4612         paramp = MapViewOfFile(paramHandle, FILE_MAP_READ, 0, 0, 0);
4613         if (!paramp)
4614         {
4615                 write_stderr("could not map view of backend variables: error code %d\n",
4616                                          (int) GetLastError());
4617                 exit(1);
4618         }
4619
4620         memcpy(&param, paramp, sizeof(BackendParameters));
4621
4622         if (!UnmapViewOfFile(paramp))
4623         {
4624                 write_stderr("could not unmap view of backend variables: error code %d\n",
4625                                          (int) GetLastError());
4626                 exit(1);
4627         }
4628
4629         if (!CloseHandle(paramHandle))
4630         {
4631                 write_stderr("could not close handle to backend parameter variables: error code %d\n",
4632                                          (int) GetLastError());
4633                 exit(1);
4634         }
4635 #endif
4636
4637         restore_backend_variables(&param, port);
4638 }
4639
4640 /* Restore critical backend variables from the BackendParameters struct */
4641 static void
4642 restore_backend_variables(BackendParameters *param, Port *port)
4643 {
4644         memcpy(port, &param->port, sizeof(Port));
4645         read_inheritable_socket(&port->sock, &param->portsocket);
4646
4647         SetDataDir(param->DataDir);
4648
4649         memcpy(&ListenSocket, &param->ListenSocket, sizeof(ListenSocket));
4650
4651         MyCancelKey = param->MyCancelKey;
4652         MyPMChildSlot = param->MyPMChildSlot;
4653
4654         UsedShmemSegID = param->UsedShmemSegID;
4655         UsedShmemSegAddr = param->UsedShmemSegAddr;
4656
4657         ShmemLock = param->ShmemLock;
4658         ShmemVariableCache = param->ShmemVariableCache;
4659         ShmemBackendArray = param->ShmemBackendArray;
4660
4661         LWLockArray = param->LWLockArray;
4662         ProcStructLock = param->ProcStructLock;
4663         ProcGlobal = param->ProcGlobal;
4664         AuxiliaryProcs = param->AuxiliaryProcs;
4665         PMSignalState = param->PMSignalState;
4666         read_inheritable_socket(&pgStatSock, &param->pgStatSock);
4667
4668         PostmasterPid = param->PostmasterPid;
4669         PgStartTime = param->PgStartTime;
4670         PgReloadTime = param->PgReloadTime;
4671
4672         redirection_done = param->redirection_done;
4673
4674 #ifdef WIN32
4675         PostmasterHandle = param->PostmasterHandle;
4676         pgwin32_initial_signal_pipe = param->initial_signal_pipe;
4677 #endif
4678
4679         memcpy(&syslogPipe, &param->syslogPipe, sizeof(syslogPipe));
4680
4681         strlcpy(my_exec_path, param->my_exec_path, MAXPGPATH);
4682
4683         strlcpy(pkglib_path, param->pkglib_path, MAXPGPATH);
4684
4685         strlcpy(ExtraOptions, param->ExtraOptions, MAXPGPATH);
4686 }
4687
4688
4689 Size
4690 ShmemBackendArraySize(void)
4691 {
4692         return mul_size(MaxLivePostmasterChildren(), sizeof(Backend));
4693 }
4694
4695 void
4696 ShmemBackendArrayAllocation(void)
4697 {
4698         Size            size = ShmemBackendArraySize();
4699
4700         ShmemBackendArray = (Backend *) ShmemAlloc(size);
4701         /* Mark all slots as empty */
4702         memset(ShmemBackendArray, 0, size);
4703 }
4704
4705 static void
4706 ShmemBackendArrayAdd(Backend *bn)
4707 {
4708         /* The array slot corresponding to my PMChildSlot should be free */
4709         int                     i = bn->child_slot - 1;
4710
4711         Assert(ShmemBackendArray[i].pid == 0);
4712         ShmemBackendArray[i] = *bn;
4713 }
4714
4715 static void
4716 ShmemBackendArrayRemove(Backend *bn)
4717 {
4718         int                     i = bn->child_slot - 1;
4719
4720         Assert(ShmemBackendArray[i].pid == bn->pid);
4721         /* Mark the slot as empty */
4722         ShmemBackendArray[i].pid = 0;
4723 }
4724 #endif   /* EXEC_BACKEND */
4725
4726
4727 #ifdef WIN32
4728
4729 static pid_t
4730 win32_waitpid(int *exitstatus)
4731 {
4732         DWORD           dwd;
4733         ULONG_PTR       key;
4734         OVERLAPPED *ovl;
4735
4736         /*
4737          * Check if there are any dead children. If there are, return the pid of
4738          * the first one that died.
4739          */
4740         if (GetQueuedCompletionStatus(win32ChildQueue, &dwd, &key, &ovl, 0))
4741         {
4742                 *exitstatus = (int) key;
4743                 return dwd;
4744         }
4745
4746         return -1;
4747 }
4748
4749 /*
4750  * Note! Code below executes on a thread pool! All operations must
4751  * be thread safe! Note that elog() and friends must *not* be used.
4752  */
4753 static void WINAPI
4754 pgwin32_deadchild_callback(PVOID lpParameter, BOOLEAN TimerOrWaitFired)
4755 {
4756         win32_deadchild_waitinfo *childinfo = (win32_deadchild_waitinfo *) lpParameter;
4757         DWORD           exitcode;
4758
4759         if (TimerOrWaitFired)
4760                 return;                                 /* timeout. Should never happen, since we use
4761                                                                  * INFINITE as timeout value. */
4762
4763         /*
4764          * Remove handle from wait - required even though it's set to wait only
4765          * once
4766          */
4767         UnregisterWaitEx(childinfo->waitHandle, NULL);
4768
4769         if (!GetExitCodeProcess(childinfo->procHandle, &exitcode))
4770         {
4771                 /*
4772                  * Should never happen. Inform user and set a fixed exitcode.
4773                  */
4774                 write_stderr("could not read exit code for process\n");
4775                 exitcode = 255;
4776         }
4777
4778         if (!PostQueuedCompletionStatus(win32ChildQueue, childinfo->procId, (ULONG_PTR) exitcode, NULL))
4779                 write_stderr("could not post child completion status\n");
4780
4781         /*
4782          * Handle is per-process, so we close it here instead of in the
4783          * originating thread
4784          */
4785         CloseHandle(childinfo->procHandle);
4786
4787         /*
4788          * Free struct that was allocated before the call to
4789          * RegisterWaitForSingleObject()
4790          */
4791         free(childinfo);
4792
4793         /* Queue SIGCHLD signal */
4794         pg_queue_signal(SIGCHLD);
4795 }
4796
4797 #endif   /* WIN32 */