OSDN Git Service

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