]> granicus.if.org Git - postgresql/blob - src/backend/postmaster/postmaster.c
For application to HEAD, following community review.
[postgresql] / src / backend / postmaster / postmaster.c
1 /*-------------------------------------------------------------------------
2  *
3  * postmaster.c
4  *        This program acts as a clearing house for requests to the
5  *        POSTGRES system.      Frontend programs send a startup message
6  *        to the Postmaster and the postmaster uses the info in the
7  *        message to setup a backend process.
8  *
9  *        The postmaster also manages system-wide operations such as
10  *        startup, shutdown, and periodic checkpoints.  The postmaster
11  *        itself doesn't do those operations, mind you --- it just forks
12  *        off a subprocess to do them at the right times.  It also takes
13  *        care of resetting the system 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-2003, 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.369 2004/02/25 19:41:22 momjian Exp $
41  *
42  * NOTES
43  *
44  * Initialization:
45  *              The Postmaster sets up a few shared memory data structures
46  *              for the backends.  It should at the very least initialize the
47  *              lock manager.
48  *
49  * Synchronization:
50  *              The Postmaster shares memory with the backends but should avoid
51  *              touching shared memory, so as not to become stuck if a crashing
52  *              backend screws up locks or shared memory.  Likewise, the Postmaster
53  *              should never block on messages from frontend clients.
54  *
55  * Garbage Collection:
56  *              The Postmaster cleans up after backends if they have an emergency
57  *              exit and/or core dump.
58  *
59  *-------------------------------------------------------------------------
60  */
61
62 #include "postgres.h"
63
64 #include <unistd.h>
65 #include <signal.h>
66 #include <sys/wait.h>
67 #include <ctype.h>
68 #include <sys/stat.h>
69 #include <sys/time.h>
70 #include <sys/socket.h>
71 #include <errno.h>
72 #include <fcntl.h>
73 #include <time.h>
74 #include <sys/param.h>
75 #include <netinet/in.h>
76 #include <arpa/inet.h>
77 #include <netdb.h>
78 #include <limits.h>
79
80 #ifdef HAVE_SYS_SELECT_H
81 #include <sys/select.h>
82 #endif
83
84 #ifdef HAVE_GETOPT_H
85 #include <getopt.h>
86 #endif
87
88 #ifdef USE_RENDEZVOUS
89 #include <DNSServiceDiscovery/DNSServiceDiscovery.h>
90 #endif
91
92 #include "catalog/pg_database.h"
93 #include "commands/async.h"
94 #include "lib/dllist.h"
95 #include "libpq/auth.h"
96 #include "libpq/crypt.h"
97 #include "libpq/libpq.h"
98 #include "libpq/pqcomm.h"
99 #include "libpq/pqsignal.h"
100 #include "miscadmin.h"
101 #include "nodes/nodes.h"
102 #include "storage/fd.h"
103 #include "storage/ipc.h"
104 #include "storage/pg_shmem.h"
105 #include "storage/pmsignal.h"
106 #include "storage/proc.h"
107 #include "storage/bufmgr.h"
108 #include "access/xlog.h"
109 #include "tcop/tcopprot.h"
110 #include "utils/guc.h"
111 #include "utils/memutils.h"
112 #include "utils/ps_status.h"
113 #include "bootstrap/bootstrap.h"
114 #include "pgstat.h"
115
116
117 #define INVALID_SOCK    (-1)
118
119 #ifdef HAVE_SIGPROCMASK
120 sigset_t        UnBlockSig,
121                         BlockSig,
122                         AuthBlockSig;
123
124 #else
125 int                     UnBlockSig,
126                         BlockSig,
127                         AuthBlockSig;
128 #endif
129
130 /*
131  * List of active backends (or child processes anyway; we don't actually
132  * know whether a given child has become a backend or is still in the
133  * authorization phase).  This is used mainly to keep track of how many
134  * children we have and send them appropriate signals when necessary.
135  */
136 typedef struct bkend
137 {
138         pid_t           pid;                    /* process id of backend */
139         long            cancel_key;             /* cancel key for cancels for this backend */
140 } Backend;
141
142 static Dllist *BackendList;
143
144 #ifdef EXEC_BACKEND
145 #define NUM_BACKENDARRAY_ELEMS (2*MaxBackends)
146 static Backend *ShmemBackendArray;
147 #endif
148
149 /* The socket number we are listening for connections on */
150 int                     PostPortNumber;
151 char       *UnixSocketDir;
152 char       *VirtualHost;
153
154 /*
155  * MaxBackends is the limit on the number of backends we can start.
156  * Note that a larger MaxBackends value will increase the size of the
157  * shared memory area as well as cause the postmaster to grab more
158  * kernel semaphores, even if you never actually use that many
159  * backends.
160  */
161 int                     MaxBackends;
162
163 /*
164  * ReservedBackends is the number of backends reserved for superuser use.
165  * This number is taken out of the pool size given by MaxBackends so
166  * number of backend slots available to non-superusers is
167  * (MaxBackends - ReservedBackends).  Note what this really means is
168  * "if there are <= ReservedBackends connections available, only superusers
169  * can make new connections" --- pre-existing superuser connections don't
170  * count against the limit.
171  */
172 int                     ReservedBackends;
173
174
175 static char *progname = NULL;
176
177 /* The socket(s) we're listening to. */
178 #define MAXLISTEN       10
179 static int      ListenSocket[MAXLISTEN];
180
181 /* Used to reduce macros tests */
182 #ifdef EXEC_BACKEND
183 const bool      ExecBackend = true;
184
185 #else
186 const bool      ExecBackend = false;
187 #endif
188
189 /*
190  * Set by the -o option
191  */
192 static char ExtraOptions[MAXPGPATH];
193
194 /*
195  * These globals control the behavior of the postmaster in case some
196  * backend dumps core.  Normally, it kills all peers of the dead backend
197  * and reinitializes shared memory.  By specifying -s or -n, we can have
198  * the postmaster stop (rather than kill) peers and not reinitialize
199  * shared data structures.
200  */
201 static bool Reinit = true;
202 static int      SendStop = false;
203
204 /* still more option variables */
205 bool            NetServer = false;      /* listen on TCP/IP */
206 bool            EnableSSL = false;
207 bool            SilentMode = false; /* silent mode (-S) */
208
209 int                     PreAuthDelay = 0;
210 int                     AuthenticationTimeout = 60;
211 int                     CheckPointTimeout = 300;
212 int                     CheckPointWarning = 30;
213 time_t          LastSignalledCheckpoint = 0;
214
215 bool            log_hostname;           /* for ps display */
216 bool            LogSourcePort;
217 bool            Log_connections = false;
218 bool            Db_user_namespace = false;
219
220 char       *rendezvous_name;
221
222 /* For FNCTL_NONBLOCK */
223 #if defined(WIN32) || defined(__BEOS__)
224 long            ioctlsocket_ret=1;
225 #endif
226
227 /* list of library:init-function to be preloaded */
228 char       *preload_libraries_string = NULL;
229
230 /* Startup/shutdown state */
231 static pid_t StartupPID = 0,
232                         ShutdownPID = 0,
233                         CheckPointPID = 0,
234                         BgWriterPID = 0;
235 static time_t checkpointed = 0;
236
237 #define                 NoShutdown              0
238 #define                 SmartShutdown   1
239 #define                 FastShutdown    2
240
241 static int      Shutdown = NoShutdown;
242
243 static bool FatalError = false; /* T if recovering from backend crash */
244
245 bool            ClientAuthInProgress = false;           /* T during new-client
246                                                                                                  * authentication */
247
248 /*
249  * State for assigning random salts and cancel keys.
250  * Also, the global MyCancelKey passes the cancel key assigned to a given
251  * backend from the postmaster to that backend (via fork).
252  */
253
254 static unsigned int random_seed = 0;
255
256 static int      debug_flag = 0;
257
258 extern char *optarg;
259 extern int      optind,
260                         opterr;
261
262 #ifdef HAVE_INT_OPTRESET
263 extern int      optreset;
264 #endif
265
266 /*
267  * postmaster.c - function prototypes
268  */
269 static void pmdaemonize(int argc, char *argv[]);
270 static Port *ConnCreate(int serverFd);
271 static void ConnFree(Port *port);
272 static void reset_shared(unsigned short port);
273 static void SIGHUP_handler(SIGNAL_ARGS);
274 static void pmdie(SIGNAL_ARGS);
275 static void reaper(SIGNAL_ARGS);
276 static void sigusr1_handler(SIGNAL_ARGS);
277 static void dummy_handler(SIGNAL_ARGS);
278 static void CleanupProc(int pid, int exitstatus);
279 static void LogChildExit(int lev, const char *procname,
280                          int pid, int exitstatus);
281 static void BackendInit(Port *port);
282 static int  BackendRun(Port *port);
283 static void ExitPostmaster(int status);
284 static void usage(const char *);
285 static int      ServerLoop(void);
286 static int      BackendStartup(Port *port);
287 static int      ProcessStartupPacket(Port *port, bool SSLdone);
288 static void processCancelRequest(Port *port, void *pkt);
289 static int      initMasks(fd_set *rmask);
290 static void report_fork_failure_to_client(Port *port, int errnum);
291 static enum CAC_state canAcceptConnections(void);
292 static long PostmasterRandom(void);
293 static void RandomSalt(char *cryptSalt, char *md5Salt);
294 static void SignalChildren(int signal);
295 static int      CountChildren(void);
296 static bool CreateOptsFile(int argc, char *argv[]);
297 NON_EXEC_STATIC void SSDataBaseInit(int xlop);
298 static pid_t SSDataBase(int xlop);
299 static void
300 postmaster_error(const char *fmt,...)
301 /* This lets gcc check the format string for consistency. */
302 __attribute__((format(printf, 1, 2)));
303
304 #ifdef EXEC_BACKEND
305 #ifdef WIN32
306 pid_t win32_forkexec(const char* path, char *argv[]);
307
308 static void  win32_AddChild(pid_t pid, HANDLE handle);
309 static void  win32_RemoveChild(pid_t pid);
310 static pid_t win32_waitpid(int *exitstatus);
311 static DWORD WINAPI win32_sigchld_waiter(LPVOID param);
312
313 static pid_t  *win32_childPIDArray;
314 static HANDLE *win32_childHNDArray;
315 static unsigned long win32_numChildren = 0;
316 #endif
317
318 static pid_t Backend_forkexec(Port *port);
319
320 static unsigned long tmpBackendFileNum = 0;
321 void read_backend_variables(unsigned long id, Port *port);
322 static bool write_backend_variables(Port *port);
323
324 size_t          ShmemBackendArraySize(void);
325 void            ShmemBackendArrayAllocation(void);
326 static void     ShmemBackendArrayAdd(Backend *bn);
327 static void ShmemBackendArrayRemove(pid_t pid);
328 #endif
329
330 #define StartupDataBase()               SSDataBase(BS_XLOG_STARTUP)
331 #define CheckPointDataBase()    SSDataBase(BS_XLOG_CHECKPOINT)
332 #define StartBackgroundWriter() SSDataBase(BS_XLOG_BGWRITER)
333 #define ShutdownDataBase()              SSDataBase(BS_XLOG_SHUTDOWN)
334
335
336 static void
337 checkDataDir(const char *checkdir)
338 {
339         char            path[MAXPGPATH];
340         FILE       *fp;
341         struct stat stat_buf;
342
343         if (checkdir == NULL)
344         {
345                 fprintf(stderr,
346                                 gettext("%s does not know where to find the database system data.\n"
347                                                 "You must specify the directory that contains the database system\n"
348                                                 "either by specifying the -D invocation option or by setting the\n"
349                                                 "PGDATA environment variable.\n"),
350                                 progname);
351                 ExitPostmaster(2);
352         }
353
354         if (stat(checkdir, &stat_buf) == -1)
355         {
356                 if (errno == ENOENT)
357                         ereport(FATAL,
358                                         (errcode_for_file_access(),
359                                          errmsg("data directory \"%s\" does not exist",
360                                                         checkdir)));
361                 else
362                         ereport(FATAL,
363                                         (errcode_for_file_access(),
364                          errmsg("could not read permissions of directory \"%s\": %m",
365                                         checkdir)));
366         }
367
368         /*
369          * Check if the directory has group or world access.  If so, reject.
370          *
371          * XXX temporarily suppress check when on Windows, because there may not
372          * be proper support for Unix-y file permissions.  Need to think of a
373          * reasonable check to apply on Windows.
374          */
375 #if !defined(__CYGWIN__) && !defined(WIN32)
376         if (stat_buf.st_mode & (S_IRWXG | S_IRWXO))
377                 ereport(FATAL,
378                                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
379                                  errmsg("data directory \"%s\" has group or world access",
380                                                 checkdir),
381                                  errdetail("Permissions should be u=rwx (0700).")));
382 #endif
383
384         /* Look for PG_VERSION before looking for pg_control */
385         ValidatePgVersion(checkdir);
386
387         snprintf(path, sizeof(path), "%s/global/pg_control", checkdir);
388
389         fp = AllocateFile(path, PG_BINARY_R);
390         if (fp == NULL)
391         {
392                 fprintf(stderr,
393                                 gettext("%s: could not find the database system\n"
394                                                 "Expected to find it in the directory \"%s\",\n"
395                                                 "but could not open file \"%s\": %s\n"),
396                                 progname, checkdir, path, strerror(errno));
397                 ExitPostmaster(2);
398         }
399         FreeFile(fp);
400 }
401
402
403 #ifdef USE_RENDEZVOUS
404
405 /* reg_reply -- empty callback function for DNSServiceRegistrationCreate() */
406 static void
407 reg_reply(DNSServiceRegistrationReplyErrorType errorCode, void *context)
408 {
409
410 }
411 #endif
412
413 int
414 PostmasterMain(int argc, char *argv[])
415 {
416         int                     opt;
417         int                     status;
418         char            original_extraoptions[MAXPGPATH];
419         char       *potential_DataDir = NULL;
420         int                     i;
421
422         *original_extraoptions = '\0';
423
424         progname = argv[0];
425
426         IsPostmasterEnvironment = true;
427
428         /*
429          * Catch standard options before doing much else.  This even works on
430          * systems without getopt_long.
431          */
432         if (argc > 1)
433         {
434                 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
435                 {
436                         usage(progname);
437                         ExitPostmaster(0);
438                 }
439                 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
440                 {
441                         puts("postmaster (PostgreSQL) " PG_VERSION);
442                         ExitPostmaster(0);
443                 }
444         }
445
446         /*
447          * for security, no dir or file created can be group or other
448          * accessible
449          */
450         umask((mode_t) 0077);
451
452         MyProcPid = PostmasterPid = getpid();
453
454         /*
455          * Fire up essential subsystems: memory management
456          */
457         MemoryContextInit();
458
459         /*
460          * By default, palloc() requests in the postmaster will be allocated
461          * in the PostmasterContext, which is space that can be recycled by
462          * backends.  Allocated data that needs to be available to backends
463          * should be allocated in TopMemoryContext.
464          */
465         PostmasterContext = AllocSetContextCreate(TopMemoryContext,
466                                                                                           "Postmaster",
467                                                                                           ALLOCSET_DEFAULT_MINSIZE,
468                                                                                           ALLOCSET_DEFAULT_INITSIZE,
469                                                                                           ALLOCSET_DEFAULT_MAXSIZE);
470         MemoryContextSwitchTo(PostmasterContext);
471
472         IgnoreSystemIndexes(false);
473
474         /*
475          * Options setup
476          */
477         InitializeGUCOptions();
478
479         potential_DataDir = getenv("PGDATA");           /* default value */
480
481         opterr = 1;
482
483         while ((opt = getopt(argc, argv, "A:a:B:b:c:D:d:Fh:ik:lm:MN:no:p:Ss-:")) != -1)
484         {
485                 switch (opt)
486                 {
487                         case 'A':
488 #ifdef USE_ASSERT_CHECKING
489                                 SetConfigOption("debug_assertions", optarg, PGC_POSTMASTER, PGC_S_ARGV);
490 #else
491                                 postmaster_error("assert checking is not compiled in");
492 #endif
493                                 break;
494                         case 'a':
495                                 /* Can no longer set authentication method. */
496                                 break;
497                         case 'B':
498                                 SetConfigOption("shared_buffers", optarg, PGC_POSTMASTER, PGC_S_ARGV);
499                                 break;
500                         case 'b':
501                                 /* Can no longer set the backend executable file to use. */
502                                 break;
503                         case 'D':
504                                 potential_DataDir = optarg;
505                                 break;
506                         case 'd':
507                                 {
508                                         /* Turn on debugging for the postmaster. */
509                                         char       *debugstr = palloc(strlen("debug") + strlen(optarg) + 1);
510
511                                         sprintf(debugstr, "debug%s", optarg);
512                                         SetConfigOption("log_min_messages", debugstr,
513                                                                         PGC_POSTMASTER, PGC_S_ARGV);
514                                         pfree(debugstr);
515                                         debug_flag = atoi(optarg);
516                                         break;
517                                 }
518                         case 'F':
519                                 SetConfigOption("fsync", "false", PGC_POSTMASTER, PGC_S_ARGV);
520                                 break;
521                         case 'h':
522                                 SetConfigOption("virtual_host", optarg, PGC_POSTMASTER, PGC_S_ARGV);
523                                 break;
524                         case 'i':
525                                 SetConfigOption("tcpip_socket", "true", PGC_POSTMASTER, PGC_S_ARGV);
526                                 break;
527                         case 'k':
528                                 SetConfigOption("unix_socket_directory", optarg, PGC_POSTMASTER, PGC_S_ARGV);
529                                 break;
530 #ifdef USE_SSL
531                         case 'l':
532                                 SetConfigOption("ssl", "true", PGC_POSTMASTER, PGC_S_ARGV);
533                                 break;
534 #endif
535                         case 'm':
536                                 /* Multiplexed backends no longer supported. */
537                                 break;
538                         case 'M':
539
540                                 /*
541                                  * ignore this flag.  This may be passed in because the
542                                  * program was run as 'postgres -M' instead of
543                                  * 'postmaster'
544                                  */
545                                 break;
546                         case 'N':
547                                 /* The max number of backends to start. */
548                                 SetConfigOption("max_connections", optarg, PGC_POSTMASTER, PGC_S_ARGV);
549                                 break;
550                         case 'n':
551                                 /* Don't reinit shared mem after abnormal exit */
552                                 Reinit = false;
553                                 break;
554                         case 'o':
555
556                                 /*
557                                  * Other options to pass to the backend on the command
558                                  * line -- useful only for debugging.
559                                  */
560                                 strcat(ExtraOptions, " ");
561                                 strcat(ExtraOptions, optarg);
562                                 strcpy(original_extraoptions, optarg);
563                                 break;
564                         case 'p':
565                                 SetConfigOption("port", optarg, PGC_POSTMASTER, PGC_S_ARGV);
566                                 break;
567                         case 'S':
568
569                                 /*
570                                  * Start in 'S'ilent mode (disassociate from controlling
571                                  * tty). You may also think of this as 'S'ysV mode since
572                                  * it's most badly needed on SysV-derived systems like
573                                  * SVR4 and HP-UX.
574                                  */
575                                 SetConfigOption("silent_mode", "true", PGC_POSTMASTER, PGC_S_ARGV);
576                                 break;
577                         case 's':
578
579                                 /*
580                                  * In the event that some backend dumps core, send
581                                  * SIGSTOP, rather than SIGQUIT, to all its peers.      This
582                                  * lets the wily post_hacker collect core dumps from
583                                  * everyone.
584                                  */
585                                 SendStop = true;
586                                 break;
587                         case 'c':
588                         case '-':
589                                 {
590                                         char       *name,
591                                                            *value;
592
593                                         ParseLongOption(optarg, &name, &value);
594                                         if (!value)
595                                         {
596                                                 if (opt == '-')
597                                                         ereport(ERROR,
598                                                                         (errcode(ERRCODE_SYNTAX_ERROR),
599                                                                          errmsg("--%s requires a value",
600                                                                                         optarg)));
601                                                 else
602                                                         ereport(ERROR,
603                                                                         (errcode(ERRCODE_SYNTAX_ERROR),
604                                                                          errmsg("-c %s requires a value",
605                                                                                         optarg)));
606                                         }
607
608                                         SetConfigOption(name, value, PGC_POSTMASTER, PGC_S_ARGV);
609                                         free(name);
610                                         if (value)
611                                                 free(value);
612                                         break;
613                                 }
614
615                         default:
616                                 fprintf(stderr,
617                                           gettext("Try \"%s --help\" for more information.\n"),
618                                                 progname);
619                                 ExitPostmaster(1);
620                 }
621         }
622
623         /*
624          * Postmaster accepts no non-option switch arguments.
625          */
626         if (optind < argc)
627         {
628                 postmaster_error("invalid argument: \"%s\"", argv[optind]);
629                 fprintf(stderr,
630                                 gettext("Try \"%s --help\" for more information.\n"),
631                                 progname);
632                 ExitPostmaster(1);
633         }
634
635         /*
636          * Now we can set the data directory, and then read postgresql.conf.
637          */
638         checkDataDir(potential_DataDir);        /* issues error messages */
639         SetDataDir(potential_DataDir);
640
641         ProcessConfigFile(PGC_POSTMASTER);
642 #ifdef EXEC_BACKEND
643         write_nondefault_variables(PGC_POSTMASTER);
644 #endif
645
646         /*
647          * Check for invalid combinations of GUC settings.
648          */
649         if (NBuffers < 2 * MaxBackends || NBuffers < 16)
650         {
651                 /*
652                  * Do not accept -B so small that backends are likely to starve
653                  * for lack of buffers.  The specific choices here are somewhat
654                  * arbitrary.
655                  */
656                 postmaster_error("the number of buffers (-B) must be at least twice the number of allowed connections (-N) and at least 16");
657                 ExitPostmaster(1);
658         }
659
660         if (ReservedBackends >= MaxBackends)
661         {
662                 postmaster_error("superuser_reserved_connections must be less than max_connections");
663                 ExitPostmaster(1);
664         }
665
666         /*
667          * Other one-time internal sanity checks can go here.
668          */
669         if (!CheckDateTokenTables())
670         {
671                 postmaster_error("invalid datetoken tables, please fix");
672                 ExitPostmaster(1);
673         }
674
675         /*
676          * Now that we are done processing the postmaster arguments, reset
677          * getopt(3) library so that it will work correctly in subprocesses.
678          */
679         optind = 1;
680 #ifdef HAVE_INT_OPTRESET
681         optreset = 1;                           /* some systems need this too */
682 #endif
683
684         /* For debugging: display postmaster environment */
685         {
686                 extern char **environ;
687                 char      **p;
688
689                 ereport(DEBUG3,
690                                 (errmsg_internal("%s: PostmasterMain: initial environ dump:",
691                                                                  progname)));
692                 ereport(DEBUG3,
693                                 (errmsg_internal("-----------------------------------------")));
694                 for (p = environ; *p; ++p)
695                         ereport(DEBUG3,
696                                         (errmsg_internal("\t%s", *p)));
697                 ereport(DEBUG3,
698                                 (errmsg_internal("-----------------------------------------")));
699         }
700
701         /*
702          * On some systems our dynloader code needs the executable's pathname.
703          */
704         if (FindExec(pg_pathname, progname, "postgres") < 0)
705                 ereport(FATAL,
706                                 (errmsg("%s: could not locate postgres executable",
707                                                 progname)));
708
709         /*
710          * Initialize SSL library, if specified.
711          */
712 #ifdef USE_SSL
713         if (EnableSSL && !NetServer)
714         {
715                 postmaster_error("TCP/IP connections must be enabled for SSL");
716                 ExitPostmaster(1);
717         }
718         if (EnableSSL)
719                 secure_initialize();
720 #endif
721
722         /*
723          * process any libraries that should be preloaded and optionally
724          * pre-initialized
725          */
726         if (preload_libraries_string)
727                 process_preload_libraries(preload_libraries_string);
728
729         /*
730          * Fork away from controlling terminal, if -S specified.
731          *
732          * Must do this before we grab any interlock files, else the interlocks
733          * will show the wrong PID.
734          */
735         if (SilentMode)
736                 pmdaemonize(argc, argv);
737
738         /*
739          * Create lockfile for data directory.
740          *
741          * We want to do this before we try to grab the input sockets, because
742          * the data directory interlock is more reliable than the socket-file
743          * interlock (thanks to whoever decided to put socket files in /tmp
744          * :-(). For the same reason, it's best to grab the TCP socket before
745          * the Unix socket.
746          */
747         CreateDataDirLockFile(DataDir, true);
748
749         /*
750          * Remove old temporary files.  At this point there can be no other
751          * Postgres processes running in this directory, so this should be
752          * safe.
753          */
754         RemovePgTempFiles();
755
756         /*
757          * Establish input sockets.
758          */
759         for (i = 0; i < MAXLISTEN; i++)
760                 ListenSocket[i] = -1;
761
762         if (NetServer)
763         {
764                 if (VirtualHost && VirtualHost[0])
765                 {
766                         char       *curhost,
767                                            *endptr;
768                         char            c = 0;
769
770                         curhost = VirtualHost;
771                         for (;;)
772                         {
773                                 while (*curhost == ' ') /* skip any extra spaces */
774                                         curhost++;
775                                 if (*curhost == '\0')
776                                         break;
777                                 endptr = strchr(curhost, ' ');
778                                 if (endptr)
779                                 {
780                                         c = *endptr;
781                                         *endptr = '\0';
782                                 }
783                                 status = StreamServerPort(AF_UNSPEC, curhost,
784                                                                                   (unsigned short) PostPortNumber,
785                                                                                   UnixSocketDir,
786                                                                                   ListenSocket, MAXLISTEN);
787                                 if (status != STATUS_OK)
788                                         ereport(FATAL,
789                                          (errmsg("could not create listen socket for \"%s\"",
790                                                          curhost)));
791                                 if (endptr)
792                                 {
793                                         *endptr = c;
794                                         curhost = endptr + 1;
795                                 }
796                                 else
797                                         break;
798                         }
799                 }
800                 else
801                 {
802                         status = StreamServerPort(AF_UNSPEC, NULL,
803                                                                           (unsigned short) PostPortNumber,
804                                                                           UnixSocketDir,
805                                                                           ListenSocket, MAXLISTEN);
806                         if (status != STATUS_OK)
807                                 ereport(FATAL,
808                                           (errmsg("could not create TCP/IP listen socket")));
809                 }
810
811 #ifdef USE_RENDEZVOUS
812                 if (rendezvous_name != NULL)
813                 {
814                         DNSServiceRegistrationCreate(rendezvous_name,
815                                                                                  "_postgresql._tcp.",
816                                                                                  "",
817                                                                                  htonl(PostPortNumber),
818                                                                                  "",
819                                                                  (DNSServiceRegistrationReply) reg_reply,
820                                                                                  NULL);
821                 }
822 #endif
823         }
824
825 #ifdef HAVE_UNIX_SOCKETS
826         status = StreamServerPort(AF_UNIX, NULL,
827                                                           (unsigned short) PostPortNumber,
828                                                           UnixSocketDir,
829                                                           ListenSocket, MAXLISTEN);
830         if (status != STATUS_OK)
831                 ereport(FATAL,
832                                 (errmsg("could not create Unix-domain socket")));
833 #endif
834
835         XLOGPathInit();
836
837         /*
838          * Set up shared memory and semaphores.
839          */
840         reset_shared(PostPortNumber);
841
842         /*
843          * Estimate number of openable files.  This must happen after setting up
844          * semaphores, because on some platforms semaphores count as open files.
845          */
846         set_max_safe_fds();
847
848         /*
849          * Initialize the list of active backends.
850          */
851         BackendList = DLNewList();
852
853 #ifdef WIN32
854         /*
855          * Initialize the child pid/HANDLE arrays
856          */
857         win32_childPIDArray = (pid_t*)malloc(NUM_BACKENDARRAY_ELEMS*sizeof(pid_t));
858         win32_childHNDArray = (HANDLE*)malloc(NUM_BACKENDARRAY_ELEMS*sizeof(HANDLE));
859         if (!win32_childPIDArray || !win32_childHNDArray)
860                 ereport(FATAL,
861                                 (errcode(ERRCODE_OUT_OF_MEMORY),
862                                  errmsg("out of memory")));
863 #endif
864
865         /*
866          * Record postmaster options.  We delay this till now to avoid
867          * recording bogus options (eg, NBuffers too high for available
868          * memory).
869          */
870         if (!CreateOptsFile(argc, argv))
871                 ExitPostmaster(1);
872
873         /*
874          * Set up signal handlers for the postmaster process.
875          *
876          * CAUTION: when changing this list, check for side-effects on the signal
877          * handling setup of child processes.  See tcop/postgres.c,
878          * bootstrap/bootstrap.c, and postmaster/pgstat.c.
879          */
880         pqinitmask();
881         PG_SETMASK(&BlockSig);
882
883         pqsignal(SIGHUP, SIGHUP_handler);       /* reread config file and have
884                                                                                  * children do same */
885         pqsignal(SIGINT, pmdie);        /* send SIGTERM and ShutdownDataBase */
886         pqsignal(SIGQUIT, pmdie);       /* send SIGQUIT and die */
887         pqsignal(SIGTERM, pmdie);       /* wait for children and ShutdownDataBase */
888         pqsignal(SIGALRM, SIG_IGN); /* ignored */
889         pqsignal(SIGPIPE, SIG_IGN); /* ignored */
890         pqsignal(SIGUSR1, sigusr1_handler); /* message from child process */
891         pqsignal(SIGUSR2, dummy_handler);       /* unused, reserve for children */
892         pqsignal(SIGCHLD, reaper);      /* handle child termination */
893         pqsignal(SIGTTIN, SIG_IGN); /* ignored */
894         pqsignal(SIGTTOU, SIG_IGN); /* ignored */
895         /* ignore SIGXFSZ, so that ulimit violations work like disk full */
896 #ifdef SIGXFSZ
897         pqsignal(SIGXFSZ, SIG_IGN); /* ignored */
898 #endif
899
900         /*
901          * Reset whereToSendOutput from Debug (its starting state) to None.
902          * This prevents ereport from sending log messages to stderr unless
903          * the syslog/stderr switch permits.  We don't do this until the
904          * postmaster is fully launched, since startup failures may as well be
905          * reported to stderr.
906          */
907         whereToSendOutput = None;
908
909         /*
910          * On many platforms, the first call of localtime() incurs significant
911          * overhead to load timezone info from the system configuration files.
912          * By doing it once in the postmaster, we avoid having to do it in
913          * every started child process.  The savings are not huge, but they
914          * add up...
915          */
916         {
917                 time_t          now = time(NULL);
918
919                 (void) localtime(&now);
920         }
921
922         /*
923          * Initialize and try to startup the statistics collector process
924          */
925         pgstat_init();
926         pgstat_start();
927
928         /*
929          * Load cached files for client authentication.
930          */
931         load_hba();
932         load_ident();
933         load_user();
934         load_group();
935
936         /*
937          * We're ready to rock and roll...
938          */
939         StartupPID = StartupDataBase();
940
941         status = ServerLoop();
942
943         /*
944          * ServerLoop probably shouldn't ever return, but if it does, close
945          * down.
946          */
947         ExitPostmaster(status != STATUS_OK);
948
949         return 0;                                       /* not reached */
950 }
951
952 static void
953 pmdaemonize(int argc, char *argv[])
954 {
955         int                     i;
956         pid_t           pid;
957
958 #ifdef LINUX_PROFILE
959         struct itimerval prof_itimer;
960 #endif
961
962 #ifdef LINUX_PROFILE
963         /* see comments in BackendRun */
964         getitimer(ITIMER_PROF, &prof_itimer);
965 #endif
966
967 #ifdef WIN32
968         /* FIXME: [fork/exec] to be implemented? */
969         abort();
970 #else
971         pid = fork();
972 #endif
973         if (pid == (pid_t) -1)
974         {
975                 postmaster_error("could not fork background process: %s",
976                                                  strerror(errno));
977                 ExitPostmaster(1);
978         }
979         else if (pid)
980         {                                                       /* parent */
981                 /* Parent should just exit, without doing any atexit cleanup */
982                 _exit(0);
983         }
984
985 #ifdef LINUX_PROFILE
986         setitimer(ITIMER_PROF, &prof_itimer, NULL);
987 #endif
988
989         MyProcPid = getpid();           /* reset MyProcPid to child */
990
991 /* GH: If there's no setsid(), we hopefully don't need silent mode.
992  * Until there's a better solution.
993  */
994 #ifdef HAVE_SETSID
995         if (setsid() < 0)
996         {
997                 postmaster_error("could not dissociate from controlling TTY: %s",
998                                                  strerror(errno));
999                 ExitPostmaster(1);
1000         }
1001 #endif
1002         i = open(NULL_DEV, O_RDWR | PG_BINARY);
1003         dup2(i, 0);
1004         dup2(i, 1);
1005         dup2(i, 2);
1006         close(i);
1007 }
1008
1009
1010
1011 /*
1012  * Print out help message
1013  */
1014 static void
1015 usage(const char *progname)
1016 {
1017         printf(gettext("%s is the PostgreSQL server.\n\n"), progname);
1018         printf(gettext("Usage:\n  %s [OPTION]...\n\n"), progname);
1019         printf(gettext("Options:\n"));
1020 #ifdef USE_ASSERT_CHECKING
1021         printf(gettext("  -A 1|0          enable/disable run-time assert checking\n"));
1022 #endif
1023         printf(gettext("  -B NBUFFERS     number of shared buffers\n"));
1024         printf(gettext("  -c NAME=VALUE   set run-time parameter\n"));
1025         printf(gettext("  -d 1-5          debugging level\n"));
1026         printf(gettext("  -D DATADIR      database directory\n"));
1027         printf(gettext("  -F              turn fsync off\n"));
1028         printf(gettext("  -h HOSTNAME     host name or IP address to listen on\n"));
1029         printf(gettext("  -i              enable TCP/IP connections\n"));
1030         printf(gettext("  -k DIRECTORY    Unix-domain socket location\n"));
1031 #ifdef USE_SSL
1032         printf(gettext("  -l              enable SSL connections\n"));
1033 #endif
1034         printf(gettext("  -N MAX-CONNECT  maximum number of allowed connections\n"));
1035         printf(gettext("  -o OPTIONS      pass \"OPTIONS\" to each server process\n"));
1036         printf(gettext("  -p PORT         port number to listen on\n"));
1037         printf(gettext("  -S              silent mode (start in background without logging output)\n"));
1038         printf(gettext("  --help          show this help, then exit\n"));
1039         printf(gettext("  --version       output version information, then exit\n"));
1040
1041         printf(gettext("\nDeveloper options:\n"));
1042         printf(gettext("  -n              do not reinitialize shared memory after abnormal exit\n"));
1043         printf(gettext("  -s              send SIGSTOP to all backend servers if one dies\n"));
1044
1045         printf(gettext("\nPlease read the documentation for the complete list of run-time\n"
1046                                    "configuration settings and how to set them on the command line or in\n"
1047                                    "the configuration file.\n\n"
1048                                    "Report bugs to <pgsql-bugs@postgresql.org>.\n"));
1049 }
1050
1051 static int
1052 ServerLoop(void)
1053 {
1054         fd_set          readmask;
1055         int                     nSockets;
1056         struct timeval now,
1057                                 later;
1058         struct timezone tz;
1059         int                     i;
1060
1061         gettimeofday(&now, &tz);
1062
1063         nSockets = initMasks(&readmask);
1064
1065         for (;;)
1066         {
1067                 Port       *port;
1068                 fd_set          rmask;
1069                 struct timeval timeout;
1070
1071                 /*
1072                  * The timeout for the select() below is normally set on the basis
1073                  * of the time to the next checkpoint.  However, if for some
1074                  * reason we don't have a next-checkpoint time, time out after 60
1075                  * seconds. This keeps checkpoint scheduling from locking up when
1076                  * we get new connection requests infrequently (since we are
1077                  * likely to detect checkpoint completion just after enabling
1078                  * signals below, after we've already made the decision about how
1079                  * long to wait this time).
1080                  */
1081                 timeout.tv_sec = 60;
1082                 timeout.tv_usec = 0;
1083
1084                 if (CheckPointPID == 0 && checkpointed &&
1085                         StartupPID == 0 && Shutdown == NoShutdown &&
1086                         !FatalError && random_seed != 0)
1087                 {
1088                         time_t          now = time(NULL);
1089
1090                         if (CheckPointTimeout + checkpointed > now)
1091                         {
1092                                 /*
1093                                  * Not time for checkpoint yet, so set select timeout
1094                                  */
1095                                 timeout.tv_sec = CheckPointTimeout + checkpointed - now;
1096                         }
1097                         else
1098                         {
1099                                 /* Time to make the checkpoint... */
1100                                 CheckPointPID = CheckPointDataBase();
1101
1102                                 /*
1103                                  * if fork failed, schedule another try at 0.1 normal
1104                                  * delay
1105                                  */
1106                                 if (CheckPointPID == 0)
1107                                 {
1108                                         timeout.tv_sec = CheckPointTimeout / 10;
1109                                         checkpointed = now + timeout.tv_sec - CheckPointTimeout;
1110                                 }
1111                         }
1112                 }
1113
1114                 /*
1115                  * If no background writer process is running and we should
1116                  * do background writing, start one. It doesn't matter if
1117                  * this fails, we'll just try again later.
1118                  */
1119                 if (BgWriterPID == 0 && BgWriterPercent > 0 &&
1120                         StartupPID == 0 && Shutdown == NoShutdown &&
1121                         !FatalError && random_seed != 0)
1122                 {
1123                         BgWriterPID = StartBackgroundWriter();
1124                 }
1125
1126                 /*
1127                  * Wait for something to happen.
1128                  */
1129                 memcpy((char *) &rmask, (char *) &readmask, sizeof(fd_set));
1130
1131                 PG_SETMASK(&UnBlockSig);
1132
1133                 if (select(nSockets, &rmask, NULL, NULL, &timeout) < 0)
1134                 {
1135                         PG_SETMASK(&BlockSig);
1136                         if (errno == EINTR || errno == EWOULDBLOCK)
1137                                 continue;
1138                         ereport(LOG,
1139                                         (errcode_for_socket_access(),
1140                                          errmsg("select() failed in postmaster: %m")));
1141                         return STATUS_ERROR;
1142                 }
1143
1144                 /*
1145                  * Block all signals until we wait again.  (This makes it safe for
1146                  * our signal handlers to do nontrivial work.)
1147                  */
1148                 PG_SETMASK(&BlockSig);
1149
1150                 /*
1151                  * Select a random seed at the time of first receiving a request.
1152                  */
1153                 while (random_seed == 0)
1154                 {
1155                         gettimeofday(&later, &tz);
1156
1157                         /*
1158                          * We are not sure how much precision is in tv_usec, so we
1159                          * swap the nibbles of 'later' and XOR them with 'now'. On the
1160                          * off chance that the result is 0, we loop until it isn't.
1161                          */
1162                         random_seed = now.tv_usec ^
1163                                 ((later.tv_usec << 16) |
1164                                  ((later.tv_usec >> 16) & 0xffff));
1165                 }
1166
1167                 /*
1168                  * New connection pending on any of our sockets? If so, fork a
1169                  * child process to deal with it.
1170                  */
1171                 for (i = 0; i < MAXLISTEN; i++)
1172                 {
1173                         if (ListenSocket[i] == -1)
1174                                 break;
1175                         if (FD_ISSET(ListenSocket[i], &rmask))
1176                         {
1177                                 port = ConnCreate(ListenSocket[i]);
1178                                 if (port)
1179                                 {
1180                                         BackendStartup(port);
1181
1182                                         /*
1183                                          * We no longer need the open socket or port structure
1184                                          * in this process
1185                                          */
1186                                         StreamClose(port->sock);
1187                                         ConnFree(port);
1188                                 }
1189                         }
1190                 }
1191
1192                 /* If we have lost the stats collector, try to start a new one */
1193                 if (!pgstat_is_running)
1194                         pgstat_start();
1195         }
1196 }
1197
1198
1199 /*
1200  * Initialise the masks for select() for the ports
1201  * we are listening on.  Return the number of sockets to listen on.
1202  */
1203
1204 static int
1205 initMasks(fd_set *rmask)
1206 {
1207         int                     nsocks = -1;
1208         int                     i;
1209
1210         FD_ZERO(rmask);
1211
1212         for (i = 0; i < MAXLISTEN; i++)
1213         {
1214                 int                     fd = ListenSocket[i];
1215
1216                 if (fd == -1)
1217                         break;
1218                 FD_SET(fd, rmask);
1219                 if (fd > nsocks)
1220                         nsocks = fd;
1221         }
1222
1223         return nsocks + 1;
1224 }
1225
1226
1227 /*
1228  * Read the startup packet and do something according to it.
1229  *
1230  * Returns STATUS_OK or STATUS_ERROR, or might call ereport(FATAL) and
1231  * not return at all.
1232  *
1233  * (Note that ereport(FATAL) stuff is sent to the client, so only use it
1234  * if that's what you want.  Return STATUS_ERROR if you don't want to
1235  * send anything to the client, which would typically be appropriate
1236  * if we detect a communications failure.)
1237  */
1238 static int
1239 ProcessStartupPacket(Port *port, bool SSLdone)
1240 {
1241         int32           len;
1242         void       *buf;
1243         ProtocolVersion proto;
1244         MemoryContext oldcontext;
1245
1246         if (pq_getbytes((char *) &len, 4) == EOF)
1247         {
1248                 /*
1249                  * EOF after SSLdone probably means the client didn't like our
1250                  * response to NEGOTIATE_SSL_CODE.      That's not an error condition,
1251                  * so don't clutter the log with a complaint.
1252                  */
1253                 if (!SSLdone)
1254                         ereport(COMMERROR,
1255                                         (errcode(ERRCODE_PROTOCOL_VIOLATION),
1256                                          errmsg("incomplete startup packet")));
1257                 return STATUS_ERROR;
1258         }
1259
1260         len = ntohl(len);
1261         len -= 4;
1262
1263         if (len < (int32) sizeof(ProtocolVersion) ||
1264                 len > MAX_STARTUP_PACKET_LENGTH)
1265         {
1266                 ereport(COMMERROR,
1267                                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1268                                  errmsg("invalid length of startup packet")));
1269                 return STATUS_ERROR;
1270         }
1271
1272         /*
1273          * Allocate at least the size of an old-style startup packet, plus one
1274          * extra byte, and make sure all are zeroes.  This ensures we will
1275          * have null termination of all strings, in both fixed- and
1276          * variable-length packet layouts.
1277          */
1278         if (len <= (int32) sizeof(StartupPacket))
1279                 buf = palloc0(sizeof(StartupPacket) + 1);
1280         else
1281                 buf = palloc0(len + 1);
1282
1283         if (pq_getbytes(buf, len) == EOF)
1284         {
1285                 ereport(COMMERROR,
1286                                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1287                                  errmsg("incomplete startup packet")));
1288                 return STATUS_ERROR;
1289         }
1290
1291         /*
1292          * The first field is either a protocol version number or a special
1293          * request code.
1294          */
1295         port->proto = proto = ntohl(*((ProtocolVersion *) buf));
1296
1297         if (proto == CANCEL_REQUEST_CODE)
1298         {
1299                 processCancelRequest(port, buf);
1300                 return 127;                             /* XXX */
1301         }
1302
1303         if (proto == NEGOTIATE_SSL_CODE && !SSLdone)
1304         {
1305                 char            SSLok;
1306
1307 #ifdef USE_SSL
1308                 /* No SSL when disabled or on Unix sockets */
1309                 if (!EnableSSL || IS_AF_UNIX(port->laddr.addr.ss_family))
1310                         SSLok = 'N';
1311                 else
1312                         SSLok = 'S';            /* Support for SSL */
1313 #else
1314                 SSLok = 'N';                    /* No support for SSL */
1315 #endif
1316                 if (send(port->sock, &SSLok, 1, 0) != 1)
1317                 {
1318                         ereport(COMMERROR,
1319                                         (errcode_for_socket_access(),
1320                                  errmsg("failed to send SSL negotiation response: %m")));
1321                         return STATUS_ERROR;    /* close the connection */
1322                 }
1323
1324 #ifdef USE_SSL
1325                 if (SSLok == 'S' && secure_open_server(port) == -1)
1326                         return STATUS_ERROR;
1327 #endif
1328                 /* regular startup packet, cancel, etc packet should follow... */
1329                 /* but not another SSL negotiation request */
1330                 return ProcessStartupPacket(port, true);
1331         }
1332
1333         /* Could add additional special packet types here */
1334
1335         /*
1336          * Set FrontendProtocol now so that ereport() knows what format to
1337          * send if we fail during startup.
1338          */
1339         FrontendProtocol = proto;
1340
1341         /* Check we can handle the protocol the frontend is using. */
1342
1343         if (PG_PROTOCOL_MAJOR(proto) < PG_PROTOCOL_MAJOR(PG_PROTOCOL_EARLIEST) ||
1344           PG_PROTOCOL_MAJOR(proto) > PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST) ||
1345         (PG_PROTOCOL_MAJOR(proto) == PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST) &&
1346          PG_PROTOCOL_MINOR(proto) > PG_PROTOCOL_MINOR(PG_PROTOCOL_LATEST)))
1347                 ereport(FATAL,
1348                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1349                                  errmsg("unsupported frontend protocol %u.%u: server supports %u.0 to %u.%u",
1350                                           PG_PROTOCOL_MAJOR(proto), PG_PROTOCOL_MINOR(proto),
1351                                                 PG_PROTOCOL_MAJOR(PG_PROTOCOL_EARLIEST),
1352                                                 PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST),
1353                                                 PG_PROTOCOL_MINOR(PG_PROTOCOL_LATEST))));
1354
1355         /*
1356          * Now fetch parameters out of startup packet and save them into the
1357          * Port structure.      All data structures attached to the Port struct
1358          * must be allocated in TopMemoryContext so that they won't disappear
1359          * when we pass them to PostgresMain (see BackendRun).  We need not
1360          * worry about leaking this storage on failure, since we aren't in the
1361          * postmaster process anymore.
1362          */
1363         oldcontext = MemoryContextSwitchTo(TopMemoryContext);
1364
1365         if (PG_PROTOCOL_MAJOR(proto) >= 3)
1366         {
1367                 int32           offset = sizeof(ProtocolVersion);
1368
1369                 /*
1370                  * Scan packet body for name/option pairs.      We can assume any
1371                  * string beginning within the packet body is null-terminated,
1372                  * thanks to zeroing extra byte above.
1373                  */
1374                 port->guc_options = NIL;
1375
1376                 while (offset < len)
1377                 {
1378                         char       *nameptr = ((char *) buf) + offset;
1379                         int32           valoffset;
1380                         char       *valptr;
1381
1382                         if (*nameptr == '\0')
1383                                 break;                  /* found packet terminator */
1384                         valoffset = offset + strlen(nameptr) + 1;
1385                         if (valoffset >= len)
1386                                 break;                  /* missing value, will complain below */
1387                         valptr = ((char *) buf) + valoffset;
1388
1389                         if (strcmp(nameptr, "database") == 0)
1390                                 port->database_name = pstrdup(valptr);
1391                         else if (strcmp(nameptr, "user") == 0)
1392                                 port->user_name = pstrdup(valptr);
1393                         else if (strcmp(nameptr, "options") == 0)
1394                                 port->cmdline_options = pstrdup(valptr);
1395                         else
1396                         {
1397                                 /* Assume it's a generic GUC option */
1398                                 port->guc_options = lappend(port->guc_options,
1399                                                                                         pstrdup(nameptr));
1400                                 port->guc_options = lappend(port->guc_options,
1401                                                                                         pstrdup(valptr));
1402                         }
1403                         offset = valoffset + strlen(valptr) + 1;
1404                 }
1405
1406                 /*
1407                  * If we didn't find a packet terminator exactly at the end of the
1408                  * given packet length, complain.
1409                  */
1410                 if (offset != len - 1)
1411                         ereport(FATAL,
1412                                         (errcode(ERRCODE_PROTOCOL_VIOLATION),
1413                                          errmsg("invalid startup packet layout: expected terminator as last byte")));
1414         }
1415         else
1416         {
1417                 /*
1418                  * Get the parameters from the old-style, fixed-width-fields
1419                  * startup packet as C strings.  The packet destination was
1420                  * cleared first so a short packet has zeros silently added.  We
1421                  * have to be prepared to truncate the pstrdup result for oversize
1422                  * fields, though.
1423                  */
1424                 StartupPacket *packet = (StartupPacket *) buf;
1425
1426                 port->database_name = pstrdup(packet->database);
1427                 if (strlen(port->database_name) > sizeof(packet->database))
1428                         port->database_name[sizeof(packet->database)] = '\0';
1429                 port->user_name = pstrdup(packet->user);
1430                 if (strlen(port->user_name) > sizeof(packet->user))
1431                         port->user_name[sizeof(packet->user)] = '\0';
1432                 port->cmdline_options = pstrdup(packet->options);
1433                 if (strlen(port->cmdline_options) > sizeof(packet->options))
1434                         port->cmdline_options[sizeof(packet->options)] = '\0';
1435                 port->guc_options = NIL;
1436         }
1437
1438         /* Check a user name was given. */
1439         if (port->user_name == NULL || port->user_name[0] == '\0')
1440                 ereport(FATAL,
1441                                 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
1442                  errmsg("no PostgreSQL user name specified in startup packet")));
1443
1444         /* The database defaults to the user name. */
1445         if (port->database_name == NULL || port->database_name[0] == '\0')
1446                 port->database_name = pstrdup(port->user_name);
1447
1448         if (Db_user_namespace)
1449         {
1450                 /*
1451                  * If user@, it is a global user, remove '@'. We only want to do
1452                  * this if there is an '@' at the end and no earlier in the user
1453                  * string or they may fake as a local user of another database
1454                  * attaching to this database.
1455                  */
1456                 if (strchr(port->user_name, '@') ==
1457                         port->user_name + strlen(port->user_name) - 1)
1458                         *strchr(port->user_name, '@') = '\0';
1459                 else
1460                 {
1461                         /* Append '@' and dbname */
1462                         char       *db_user;
1463
1464                         db_user = palloc(strlen(port->user_name) +
1465                                                          strlen(port->database_name) + 2);
1466                         sprintf(db_user, "%s@%s", port->user_name, port->database_name);
1467                         port->user_name = db_user;
1468                 }
1469         }
1470
1471         /*
1472          * Truncate given database and user names to length of a Postgres
1473          * name.  This avoids lookup failures when overlength names are given.
1474          */
1475         if (strlen(port->database_name) >= NAMEDATALEN)
1476                 port->database_name[NAMEDATALEN - 1] = '\0';
1477         if (strlen(port->user_name) >= NAMEDATALEN)
1478                 port->user_name[NAMEDATALEN - 1] = '\0';
1479
1480         /*
1481          * Done putting stuff in TopMemoryContext.
1482          */
1483         MemoryContextSwitchTo(oldcontext);
1484
1485         /*
1486          * If we're going to reject the connection due to database state, say
1487          * so now instead of wasting cycles on an authentication exchange.
1488          * (This also allows a pg_ping utility to be written.)
1489          */
1490         switch (port->canAcceptConnections)
1491         {
1492                 case CAC_STARTUP:
1493                         ereport(FATAL,
1494                                         (errcode(ERRCODE_CANNOT_CONNECT_NOW),
1495                                          errmsg("the database system is starting up")));
1496                         break;
1497                 case CAC_SHUTDOWN:
1498                         ereport(FATAL,
1499                                         (errcode(ERRCODE_CANNOT_CONNECT_NOW),
1500                                          errmsg("the database system is shutting down")));
1501                         break;
1502                 case CAC_RECOVERY:
1503                         ereport(FATAL,
1504                                         (errcode(ERRCODE_CANNOT_CONNECT_NOW),
1505                                          errmsg("the database system is in recovery mode")));
1506                         break;
1507                 case CAC_TOOMANY:
1508                         ereport(FATAL,
1509                                         (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
1510                                          errmsg("sorry, too many clients already")));
1511                         break;
1512                 case CAC_OK:
1513                 default:
1514                         break;
1515         }
1516
1517         return STATUS_OK;
1518 }
1519
1520
1521 /*
1522  * The client has sent a cancel request packet, not a normal
1523  * start-a-new-connection packet.  Perform the necessary processing.
1524  * Nothing is sent back to the client.
1525  */
1526 static void
1527 processCancelRequest(Port *port, void *pkt)
1528 {
1529         CancelRequestPacket *canc = (CancelRequestPacket *) pkt;
1530         int                     backendPID;
1531         long            cancelAuthCode;
1532         Backend    *bp;
1533 #ifndef EXEC_BACKEND
1534         Dlelem     *curr;
1535 #else
1536         int i;
1537 #endif
1538
1539         backendPID = (int) ntohl(canc->backendPID);
1540         cancelAuthCode = (long) ntohl(canc->cancelAuthCode);
1541
1542         if (backendPID == CheckPointPID)
1543         {
1544                 ereport(DEBUG2,
1545                                 (errmsg_internal("ignoring cancel request for checkpoint process %d",
1546                                                                  backendPID)));
1547                 return;
1548         }
1549         else if (backendPID == BgWriterPID)
1550         {
1551                 ereport(DEBUG2,
1552                                 (errmsg_internal("ignoring cancel request for bgwriter process %d",
1553                                                                  backendPID)));
1554                 return;
1555         }
1556
1557         /* See if we have a matching backend */
1558 #ifndef EXEC_BACKEND
1559         for (curr = DLGetHead(BackendList); curr; curr = DLGetSucc(curr))
1560         {
1561                 bp = (Backend *) DLE_VAL(curr);
1562 #else
1563         for (i = 0; i < NUM_BACKENDARRAY_ELEMS; i++)
1564         {
1565                 bp = (Backend*) &ShmemBackendArray[i];
1566 #endif
1567                 if (bp->pid == backendPID)
1568                 {
1569                         if (bp->cancel_key == cancelAuthCode)
1570                         {
1571                                 /* Found a match; signal that backend to cancel current op */
1572                                 ereport(DEBUG2,
1573                                                 (errmsg_internal("processing cancel request: sending SIGINT to process %d",
1574                                                                                  backendPID)));
1575                                 kill(bp->pid, SIGINT);
1576                         }
1577                         else
1578                                 /* Right PID, wrong key: no way, Jose */
1579                                 ereport(DEBUG2,
1580                                                 (errmsg_internal("bad key in cancel request for process %d",
1581                                                                                  backendPID)));
1582                         return;
1583                 }
1584         }
1585
1586         /* No matching backend */
1587         ereport(DEBUG2,
1588                         (errmsg_internal("bad pid in cancel request for process %d",
1589                                                          backendPID)));
1590 }
1591
1592 /*
1593  * canAcceptConnections --- check to see if database state allows connections.
1594  */
1595 static enum CAC_state
1596 canAcceptConnections(void)
1597 {
1598         /* Can't start backends when in startup/shutdown/recovery state. */
1599         if (Shutdown > NoShutdown)
1600                 return CAC_SHUTDOWN;
1601         if (StartupPID)
1602                 return CAC_STARTUP;
1603         if (FatalError)
1604                 return CAC_RECOVERY;
1605
1606         /*
1607          * Don't start too many children.
1608          *
1609          * We allow more connections than we can have backends here because some
1610          * might still be authenticating; they might fail auth, or some
1611          * existing backend might exit before the auth cycle is completed. The
1612          * exact MaxBackends limit is enforced when a new backend tries to
1613          * join the shared-inval backend array.
1614          */
1615         if (CountChildren() >= 2 * MaxBackends)
1616                 return CAC_TOOMANY;
1617
1618         return CAC_OK;
1619 }
1620
1621
1622 /*
1623  * ConnCreate -- create a local connection data structure
1624  */
1625 static Port *
1626 ConnCreate(int serverFd)
1627 {
1628         Port       *port;
1629
1630         if (!(port = (Port *) calloc(1, sizeof(Port))))
1631         {
1632                 ereport(LOG,
1633                                 (errcode(ERRCODE_OUT_OF_MEMORY),
1634                                  errmsg("out of memory")));
1635                 ExitPostmaster(1);
1636         }
1637
1638         if (StreamConnection(serverFd, port) != STATUS_OK)
1639         {
1640                 StreamClose(port->sock);
1641                 ConnFree(port);
1642                 port = NULL;
1643         }
1644         else
1645         {
1646                 /*
1647                  * Precompute password salt values to use for this connection.
1648                  * It's slightly annoying to do this long in advance of knowing
1649                  * whether we'll need 'em or not, but we must do the random()
1650                  * calls before we fork, not after.  Else the postmaster's random
1651                  * sequence won't get advanced, and all backends would end up
1652                  * using the same salt...
1653                  */
1654                 RandomSalt(port->cryptSalt, port->md5Salt);
1655         }
1656
1657         return port;
1658 }
1659
1660
1661 /*
1662  * ConnFree -- free a local connection data structure
1663  */
1664 static void
1665 ConnFree(Port *conn)
1666 {
1667 #ifdef USE_SSL
1668         secure_close(conn);
1669 #endif
1670         free(conn);
1671 }
1672
1673
1674 /*
1675  * ClosePostmasterPorts -- close all the postmaster's open sockets
1676  *
1677  * This is called during child process startup to release file descriptors
1678  * that are not needed by that child process.  The postmaster still has
1679  * them open, of course.
1680  */
1681 void
1682 ClosePostmasterPorts(bool pgstat_too)
1683 {
1684         int                     i;
1685
1686         /* Close the listen sockets */
1687         for (i = 0; i < MAXLISTEN; i++)
1688         {
1689                 if (ListenSocket[i] != -1)
1690                 {
1691                         StreamClose(ListenSocket[i]);
1692                         ListenSocket[i] = -1;
1693                 }
1694         }
1695
1696         /* Close pgstat control sockets, unless we're starting pgstat itself */
1697         if (pgstat_too)
1698                 pgstat_close_sockets();
1699 }
1700
1701
1702 /*
1703  * reset_shared -- reset shared memory and semaphores
1704  */
1705 static void
1706 reset_shared(unsigned short port)
1707 {
1708         /*
1709          * Create or re-create shared memory and semaphores.
1710          *
1711          * Note: in each "cycle of life" we will normally assign the same IPC
1712          * keys (if using SysV shmem and/or semas), since the port number is
1713          * used to determine IPC keys.  This helps ensure that we will clean
1714          * up dead IPC objects if the postmaster crashes and is restarted.
1715          */
1716         CreateSharedMemoryAndSemaphores(false, MaxBackends, port);
1717 }
1718
1719
1720 /*
1721  * SIGHUP -- reread config files, and tell children to do same
1722  */
1723 static void
1724 SIGHUP_handler(SIGNAL_ARGS)
1725 {
1726         int                     save_errno = errno;
1727
1728         PG_SETMASK(&BlockSig);
1729
1730         if (Shutdown <= SmartShutdown)
1731         {
1732                 ereport(LOG,
1733                          (errmsg("received SIGHUP, reloading configuration files")));
1734                 ProcessConfigFile(PGC_SIGHUP);
1735 #ifdef EXEC_BACKEND
1736                 write_nondefault_variables(PGC_SIGHUP);
1737 #endif
1738                 SignalChildren(SIGHUP);
1739                 load_hba();
1740                 load_ident();
1741
1742                 /*
1743                  * Tell the background writer to terminate so that we
1744                  * will start a new one with a possibly changed config
1745                  */
1746                 if (BgWriterPID != 0)
1747                         kill(BgWriterPID, SIGTERM);
1748         }
1749
1750         PG_SETMASK(&UnBlockSig);
1751
1752         errno = save_errno;
1753 }
1754
1755
1756
1757 /*
1758  * pmdie -- signal handler for processing various postmaster signals.
1759  */
1760 static void
1761 pmdie(SIGNAL_ARGS)
1762 {
1763         int                     save_errno = errno;
1764
1765         PG_SETMASK(&BlockSig);
1766
1767         ereport(DEBUG2,
1768                         (errmsg_internal("postmaster received signal %d",
1769                                                          postgres_signal_arg)));
1770
1771         switch (postgres_signal_arg)
1772         {
1773                 case SIGTERM:
1774
1775                         /*
1776                          * Smart Shutdown:
1777                          *
1778                          * Wait for children to end their work and ShutdownDataBase.
1779                          */
1780                         if (Shutdown >= SmartShutdown)
1781                                 break;
1782                         Shutdown = SmartShutdown;
1783                         ereport(LOG,
1784                                         (errmsg("received smart shutdown request")));
1785
1786                         /* Must tell bgwriter to quit, or it never will... */
1787                         if (BgWriterPID != 0)
1788                                 kill(BgWriterPID, SIGTERM);
1789
1790                         if (DLGetHead(BackendList)) /* let reaper() handle this */
1791                                 break;
1792
1793                         /*
1794                          * No children left. Shutdown data base system.
1795                          */
1796                         if (StartupPID > 0 || FatalError)       /* let reaper() handle
1797                                                                                                  * this */
1798                                 break;
1799                         if (ShutdownPID > 0)
1800                         {
1801                                 elog(PANIC, "shutdown process %d already running",
1802                                          (int) ShutdownPID);
1803                                 abort();
1804                         }
1805
1806                         ShutdownPID = ShutdownDataBase();
1807                         break;
1808
1809                 case SIGINT:
1810
1811                         /*
1812                          * Fast Shutdown:
1813                          *
1814                          * Abort all children with SIGTERM (rollback active transactions
1815                          * and exit) and ShutdownDataBase when they are gone.
1816                          */
1817                         if (Shutdown >= FastShutdown)
1818                                 break;
1819                         Shutdown = FastShutdown;
1820                         ereport(LOG,
1821                                         (errmsg("received fast shutdown request")));
1822
1823                         if (DLGetHead(BackendList))
1824                         {
1825                                 if (!FatalError)
1826                                 {
1827                                         ereport(LOG,
1828                                                         (errmsg("aborting any active transactions")));
1829                                         SignalChildren(SIGTERM);
1830                                         /* reaper() does the rest */
1831                                 }
1832                                 break;
1833                         }
1834
1835                         /*
1836                          * No children left. Shutdown data base system.
1837                          *
1838                          * Unlike the previous case, it is not an error for the shutdown
1839                          * process to be running already (we could get SIGTERM followed
1840                          * shortly later by SIGINT).
1841                          */
1842                         if (StartupPID > 0 || FatalError)       /* let reaper() handle
1843                                                                                                  * this */
1844                                 break;
1845                         if (ShutdownPID == 0)
1846                                 ShutdownPID = ShutdownDataBase();
1847                         break;
1848
1849                 case SIGQUIT:
1850
1851                         /*
1852                          * Immediate Shutdown:
1853                          *
1854                          * abort all children with SIGQUIT and exit without attempt to
1855                          * properly shutdown data base system.
1856                          */
1857                         ereport(LOG,
1858                                         (errmsg("received immediate shutdown request")));
1859                         if (ShutdownPID > 0)
1860                                 kill(ShutdownPID, SIGQUIT);
1861                         if (StartupPID > 0)
1862                                 kill(StartupPID, SIGQUIT);
1863                         if (DLGetHead(BackendList))
1864                                 SignalChildren(SIGQUIT);
1865                         ExitPostmaster(0);
1866                         break;
1867         }
1868
1869         PG_SETMASK(&UnBlockSig);
1870
1871         errno = save_errno;
1872 }
1873
1874 /*
1875  * Reaper -- signal handler to cleanup after a backend (child) dies.
1876  */
1877 static void
1878 reaper(SIGNAL_ARGS)
1879 {
1880         int                     save_errno = errno;
1881
1882 #ifdef HAVE_WAITPID
1883         int                     status;                 /* backend exit status */
1884 #else
1885 #ifndef WIN32
1886         union wait      status;                 /* backend exit status */
1887 #endif
1888 #endif
1889         int                     exitstatus;
1890         int                     pid;                    /* process id of dead backend */
1891
1892         PG_SETMASK(&BlockSig);
1893
1894         ereport(DEBUG4,
1895                         (errmsg_internal("reaping dead processes")));
1896 #ifdef HAVE_WAITPID
1897         while ((pid = waitpid(-1, &status, WNOHANG)) > 0)
1898         {
1899                 exitstatus = status;
1900 #else
1901 #ifndef WIN32
1902         while ((pid = wait3(&status, WNOHANG, NULL)) > 0)
1903         {
1904                 exitstatus = status.w_status;
1905 #else
1906         while ((pid = win32_waitpid(&exitstatus)) > 0)
1907         {
1908                 /*
1909                  * We need to do this here, and not in CleanupProc, since this
1910                  * is to be called on all children when we are done with them.
1911                  * Could move to LogChildExit, but that seems like asking for
1912                  * future trouble...
1913                  */
1914                 win32_RemoveChild(pid);
1915 #endif
1916 #endif
1917
1918                 /*
1919                  * Check if this child was the statistics collector. If so, try to
1920                  * start a new one.  (If fail, we'll try again in future cycles of
1921                  * the main loop.)
1922                  */
1923                 if (pgstat_ispgstat(pid))
1924                 {
1925                         LogChildExit(LOG, gettext("statistics collector process"),
1926                                                  pid, exitstatus);
1927                         pgstat_start();
1928                         continue;
1929                 }
1930
1931                 /*
1932                  * Check if this child was a shutdown or startup process.
1933                  */
1934                 if (ShutdownPID > 0 && pid == ShutdownPID)
1935                 {
1936                         if (exitstatus != 0)
1937                         {
1938                                 LogChildExit(LOG, gettext("shutdown process"),
1939                                                          pid, exitstatus);
1940                                 ExitPostmaster(1);
1941                         }
1942                         /* Normal postmaster exit is here */
1943                         ExitPostmaster(0);
1944                 }
1945
1946                 if (StartupPID > 0 && pid == StartupPID)
1947                 {
1948                         if (exitstatus != 0)
1949                         {
1950                                 LogChildExit(LOG, gettext("startup process"),
1951                                                          pid, exitstatus);
1952                                 ereport(LOG,
1953                                                 (errmsg("aborting startup due to startup process failure")));
1954                                 ExitPostmaster(1);
1955                         }
1956                         StartupPID = 0;
1957
1958                         /*
1959                          * Startup succeeded - remember its ID and RedoRecPtr.
1960                          *
1961                          * NB: this MUST happen before we fork a checkpoint or shutdown
1962                          * subprocess, else they will have wrong local ThisStartUpId.
1963                          */
1964                         SetThisStartUpID();
1965
1966                         FatalError = false; /* done with recovery */
1967
1968                         /*
1969                          * Arrange for first checkpoint to occur after standard delay.
1970                          */
1971                         CheckPointPID = 0;
1972                         checkpointed = time(NULL);
1973
1974                         /*
1975                          * Go to shutdown mode if a shutdown request was pending.
1976                          */
1977                         if (Shutdown > NoShutdown)
1978                         {
1979                                 if (ShutdownPID > 0)
1980                                 {
1981                                         elog(PANIC, "startup process %d died while shutdown process %d already running",
1982                                                  pid, (int) ShutdownPID);
1983                                         abort();
1984                                 }
1985                                 ShutdownPID = ShutdownDataBase();
1986                         }
1987
1988                         goto reaper_done;
1989                 }
1990
1991                 /*
1992                  * Else do standard child cleanup.
1993                  */
1994                 CleanupProc(pid, exitstatus);
1995
1996         }                                                       /* loop over pending child-death reports */
1997
1998         if (FatalError)
1999         {
2000                 /*
2001                  * Wait for all children exit, then reset shmem and
2002                  * StartupDataBase.
2003                  */
2004                 if (DLGetHead(BackendList) || StartupPID > 0 || ShutdownPID > 0)
2005                         goto reaper_done;
2006                 ereport(LOG,
2007                         (errmsg("all server processes terminated; reinitializing")));
2008
2009                 shmem_exit(0);
2010                 reset_shared(PostPortNumber);
2011
2012                 StartupPID = StartupDataBase();
2013
2014                 goto reaper_done;
2015         }
2016
2017         if (Shutdown > NoShutdown)
2018         {
2019                 if (DLGetHead(BackendList))
2020                         goto reaper_done;
2021                 if (StartupPID > 0 || ShutdownPID > 0)
2022                         goto reaper_done;
2023                 ShutdownPID = ShutdownDataBase();
2024         }
2025
2026 reaper_done:
2027         PG_SETMASK(&UnBlockSig);
2028
2029         errno = save_errno;
2030 }
2031
2032 /*
2033  * CleanupProc -- cleanup after terminated backend.
2034  *
2035  * Remove all local state associated with backend.
2036  */
2037 static void
2038 CleanupProc(int pid,
2039                         int exitstatus)         /* child's exit status. */
2040 {
2041         Dlelem     *curr,
2042                            *next;
2043         Backend    *bp;
2044
2045         LogChildExit(DEBUG2, gettext("child process"), pid, exitstatus);
2046
2047         /*
2048          * If a backend dies in an ugly way (i.e. exit status not 0) then we
2049          * must signal all other backends to quickdie.  If exit status is zero
2050          * we assume everything is hunky dory and simply remove the backend
2051          * from the active backend list.
2052          */
2053         if (exitstatus == 0)
2054         {
2055                 curr = DLGetHead(BackendList);
2056                 while (curr)
2057                 {
2058                         bp = (Backend *) DLE_VAL(curr);
2059                         if (bp->pid == pid)
2060                         {
2061 #ifdef EXEC_BACKEND
2062                                 ShmemBackendArrayRemove(bp->pid);
2063 #endif
2064                                 DLRemove(curr);
2065                                 free(bp);
2066                                 DLFreeElem(curr);
2067                                 break;
2068                         }
2069                         curr = DLGetSucc(curr);
2070                 }
2071
2072                 if (pid == CheckPointPID)
2073                 {
2074                         CheckPointPID = 0;
2075                         if (!FatalError)
2076                         {
2077                                 checkpointed = time(NULL);
2078                                 /* Update RedoRecPtr for future child backends */
2079                                 GetSavedRedoRecPtr();
2080                         }
2081                 }
2082                 else if (pid == BgWriterPID)
2083                         BgWriterPID = 0;
2084                 else
2085                         pgstat_beterm(pid);
2086
2087                 return;
2088         }
2089
2090         /* below here we're dealing with a non-normal exit */
2091
2092         /* Make log entry unless we did so already */
2093         if (!FatalError)
2094         {
2095                 LogChildExit(LOG,
2096                                          (pid == CheckPointPID) ? gettext("checkpoint process") :
2097                                          (pid == BgWriterPID) ? gettext("bgwriter process") :
2098                                          gettext("server process"),
2099                                          pid, exitstatus);
2100                 ereport(LOG,
2101                           (errmsg("terminating any other active server processes")));
2102         }
2103
2104         curr = DLGetHead(BackendList);
2105         while (curr)
2106         {
2107                 next = DLGetSucc(curr);
2108                 bp = (Backend *) DLE_VAL(curr);
2109                 if (bp->pid != pid)
2110                 {
2111                         /*
2112                          * This backend is still alive.  Unless we did so already,
2113                          * tell it to commit hara-kiri.
2114                          *
2115                          * SIGQUIT is the special signal that says exit without proc_exit
2116                          * and let the user know what's going on. But if SendStop is
2117                          * set (-s on command line), then we send SIGSTOP instead, so
2118                          * that we can get core dumps from all backends by hand.
2119                          */
2120                         if (!FatalError)
2121                         {
2122                                 ereport(DEBUG2,
2123                                                 (errmsg_internal("sending %s to process %d",
2124                                                                                  (SendStop ? "SIGSTOP" : "SIGQUIT"),
2125                                                                                  (int) bp->pid)));
2126                                 kill(bp->pid, (SendStop ? SIGSTOP : SIGQUIT));
2127                         }
2128                 }
2129                 else
2130                 {
2131                         /*
2132                          * Found entry for freshly-dead backend, so remove it.
2133                          */
2134 #ifdef EXEC_BACKEND
2135                         ShmemBackendArrayRemove(bp->pid);
2136 #endif
2137                         DLRemove(curr);
2138                         free(bp);
2139                         DLFreeElem(curr);
2140                 }
2141                 curr = next;
2142         }
2143
2144         if (pid == CheckPointPID)
2145         {
2146                 CheckPointPID = 0;
2147                 checkpointed = 0;
2148         }
2149         else if (pid == BgWriterPID)
2150         {
2151                 BgWriterPID = 0;
2152         }
2153         else
2154         {
2155                 /*
2156                  * Tell the collector about backend termination
2157                  */
2158                 pgstat_beterm(pid);
2159         }
2160
2161         FatalError = true;
2162 }
2163
2164 /*
2165  * Log the death of a child process.
2166  */
2167 static void
2168 LogChildExit(int lev, const char *procname, int pid, int exitstatus)
2169 {
2170         if (WIFEXITED(exitstatus))
2171                 ereport(lev,
2172
2173                 /*
2174                  * translator: %s is a noun phrase describing a child process,
2175                  * such as "server process"
2176                  */
2177                                 (errmsg("%s (PID %d) exited with exit code %d",
2178                                                 procname, pid, WEXITSTATUS(exitstatus))));
2179         else if (WIFSIGNALED(exitstatus))
2180                 ereport(lev,
2181
2182                 /*
2183                  * translator: %s is a noun phrase describing a child process,
2184                  * such as "server process"
2185                  */
2186                                 (errmsg("%s (PID %d) was terminated by signal %d",
2187                                                 procname, pid, WTERMSIG(exitstatus))));
2188         else
2189                 ereport(lev,
2190
2191                 /*
2192                  * translator: %s is a noun phrase describing a child process,
2193                  * such as "server process"
2194                  */
2195                                 (errmsg("%s (PID %d) exited with unexpected status %d",
2196                                                 procname, pid, exitstatus)));
2197 }
2198
2199 /*
2200  * Send a signal to all backend children.
2201  */
2202 static void
2203 SignalChildren(int signal)
2204 {
2205         Dlelem     *curr,
2206                            *next;
2207         Backend    *bp;
2208
2209         curr = DLGetHead(BackendList);
2210         while (curr)
2211         {
2212                 next = DLGetSucc(curr);
2213                 bp = (Backend *) DLE_VAL(curr);
2214
2215                 if (bp->pid != MyProcPid)
2216                 {
2217                         ereport(DEBUG2,
2218                                         (errmsg_internal("sending signal %d to process %d",
2219                                                                          signal,
2220                                                                          (int) bp->pid)));
2221                         kill(bp->pid, signal);
2222                 }
2223
2224                 curr = next;
2225         }
2226 }
2227
2228 /*
2229  * BackendStartup -- start backend process
2230  *
2231  * returns: STATUS_ERROR if the fork failed, STATUS_OK otherwise.
2232  */
2233 static int
2234 BackendStartup(Port *port)
2235 {
2236         Backend    *bn;                         /* for backend cleanup */
2237         pid_t           pid;
2238
2239 #ifdef LINUX_PROFILE
2240         struct itimerval prof_itimer;
2241 #endif
2242
2243         /*
2244          * Compute the cancel key that will be assigned to this backend. The
2245          * backend will have its own copy in the forked-off process' value of
2246          * MyCancelKey, so that it can transmit the key to the frontend.
2247          */
2248         MyCancelKey = PostmasterRandom();
2249
2250         /*
2251          * Make room for backend data structure.  Better before the fork() so
2252          * we can handle failure cleanly.
2253          */
2254         bn = (Backend *) malloc(sizeof(Backend));
2255         if (!bn)
2256         {
2257                 ereport(LOG,
2258                                 (errcode(ERRCODE_OUT_OF_MEMORY),
2259                                  errmsg("out of memory")));
2260                 return STATUS_ERROR;
2261         }
2262
2263         /*
2264          * Flush stdio channels just before fork, to avoid double-output
2265          * problems. Ideally we'd use fflush(NULL) here, but there are still a
2266          * few non-ANSI stdio libraries out there (like SunOS 4.1.x) that
2267          * coredump if we do. Presently stdout and stderr are the only stdio
2268          * output channels used by the postmaster, so fflush'ing them should
2269          * be sufficient.
2270          */
2271         fflush(stdout);
2272         fflush(stderr);
2273
2274 #ifdef LINUX_PROFILE
2275
2276         /*
2277          * Linux's fork() resets the profiling timer in the child process. If
2278          * we want to profile child processes then we need to save and restore
2279          * the timer setting.  This is a waste of time if not profiling,
2280          * however, so only do it if commanded by specific -DLINUX_PROFILE
2281          * switch.
2282          */
2283         getitimer(ITIMER_PROF, &prof_itimer);
2284 #endif
2285
2286 #ifdef __BEOS__
2287         /* Specific beos actions before backend startup */
2288         beos_before_backend_startup();
2289 #endif
2290
2291         port->canAcceptConnections = canAcceptConnections();
2292 #ifdef EXEC_BACKEND
2293         pid = Backend_forkexec(port);
2294 #else
2295         pid = fork();
2296
2297         if (pid == 0)                           /* child */
2298         {
2299 #ifdef LINUX_PROFILE
2300                 setitimer(ITIMER_PROF, &prof_itimer, NULL);
2301 #endif
2302
2303 #ifdef __BEOS__
2304                 /* Specific beos backend startup actions */
2305                 beos_backend_startup();
2306 #endif
2307                 free(bn);
2308
2309                 proc_exit(BackendRun(port));
2310         }
2311 #endif
2312
2313         /* in parent, error */
2314         if (pid < 0)
2315         {
2316                 int                     save_errno = errno;
2317
2318 #ifdef __BEOS__
2319                 /* Specific beos backend startup actions */
2320                 beos_backend_startup_failed();
2321 #endif
2322                 free(bn);
2323                 errno = save_errno;
2324                 ereport(LOG,
2325                           (errmsg("could not fork new process for connection: %m")));
2326                 report_fork_failure_to_client(port, save_errno);
2327                 return STATUS_ERROR;
2328         }
2329
2330         /* in parent, normal */
2331         ereport(DEBUG2,
2332                         (errmsg_internal("forked new backend, pid=%d socket=%d",
2333                                                          (int) pid, port->sock)));
2334
2335         /*
2336          * Everything's been successful, it's safe to add this backend to our
2337          * list of backends.
2338          */
2339         bn->pid = pid;
2340         bn->cancel_key = MyCancelKey;
2341 #ifdef EXEC_BACKEND
2342         ShmemBackendArrayAdd(bn);
2343 #endif
2344         DLAddHead(BackendList, DLNewElem(bn));
2345
2346         return STATUS_OK;
2347 }
2348
2349 /*
2350  * Try to report backend fork() failure to client before we close the
2351  * connection.  Since we do not care to risk blocking the postmaster on
2352  * this connection, we set the connection to non-blocking and try only once.
2353  *
2354  * This is grungy special-purpose code; we cannot use backend libpq since
2355  * it's not up and running.
2356  */
2357 static void
2358 report_fork_failure_to_client(Port *port, int errnum)
2359 {
2360         char            buffer[1000];
2361
2362         /* Format the error message packet (always V2 protocol) */
2363         snprintf(buffer, sizeof(buffer), "E%s%s\n",
2364                          gettext("could not fork new process for connection: "),
2365                          strerror(errnum));
2366
2367         /* Set port to non-blocking.  Don't do send() if this fails */
2368         if (FCNTL_NONBLOCK(port->sock) < 0)
2369                 return;
2370
2371         send(port->sock, buffer, strlen(buffer) + 1, 0);
2372 }
2373
2374
2375 /*
2376  * split_opts -- split a string of options and append it to an argv array
2377  *
2378  * NB: the string is destructively modified!
2379  *
2380  * Since no current POSTGRES arguments require any quoting characters,
2381  * we can use the simple-minded tactic of assuming each set of space-
2382  * delimited characters is a separate argv element.
2383  *
2384  * If you don't like that, well, we *used* to pass the whole option string
2385  * as ONE argument to execl(), which was even less intelligent...
2386  */
2387 static void
2388 split_opts(char **argv, int *argcp, char *s)
2389 {
2390         while (s && *s)
2391         {
2392                 while (isspace((unsigned char) *s))
2393                         ++s;
2394                 if (*s == '\0')
2395                         break;
2396                 argv[(*argcp)++] = s;
2397                 while (*s && !isspace((unsigned char) *s))
2398                         ++s;
2399                 if (*s)
2400                         *s++ = '\0';
2401         }
2402 }
2403
2404
2405 /*
2406  * BackendInit/Run -- perform authentication [BackendInit], and if successful,
2407  *              set up the backend's argument list [BackendRun] and invoke
2408  *              backend main()
2409  *
2410  * returns:
2411  *              Shouldn't return at all.
2412  *              If PostgresMain() fails, return status.
2413  */
2414 static void
2415 BackendInit(Port *port)
2416 {
2417         int                     status;
2418         struct timeval now;
2419         struct timezone tz;
2420         char            remote_host[NI_MAXHOST];
2421         char            remote_port[NI_MAXSERV];
2422
2423         IsUnderPostmaster = true;       /* we are a postmaster subprocess now */
2424
2425         ClientAuthInProgress = true;    /* limit visibility of log messages */
2426
2427         /* We don't want the postmaster's proc_exit() handlers */
2428         on_exit_reset();
2429
2430         /*
2431          * Signal handlers setting is moved to tcop/postgres...
2432          */
2433
2434         /* save start time for end of session reporting */
2435         gettimeofday(&(port->session_start),NULL);
2436
2437         /* set these to empty in case they are needed before we set them up */
2438         port->remote_host = "";
2439         port->remote_port = "";
2440
2441         /* Save port etc. for ps status */
2442         MyProcPort = port;
2443
2444         /* Reset MyProcPid to new backend's pid */
2445         MyProcPid = getpid();
2446
2447         /*
2448          * Initialize libpq and enable reporting of ereport errors to the
2449          * client. Must do this now because authentication uses libpq to send
2450          * messages.
2451          */
2452         pq_init();                                      /* initialize libpq to talk to client */
2453         whereToSendOutput = Remote; /* now safe to ereport to client */
2454
2455         /*
2456          * We arrange for a simple exit(0) if we receive SIGTERM or SIGQUIT
2457          * during any client authentication related communication. Otherwise
2458          * the postmaster cannot shutdown the database FAST or IMMED cleanly
2459          * if a buggy client blocks a backend during authentication.
2460          */
2461         pqsignal(SIGTERM, authdie);
2462         pqsignal(SIGQUIT, authdie);
2463         pqsignal(SIGALRM, authdie);
2464         PG_SETMASK(&AuthBlockSig);
2465
2466         /*
2467          * Get the remote host name and port for logging and status display.
2468          */
2469         remote_host[0] = '\0';
2470         remote_port[0] = '\0';
2471         if (getnameinfo_all(&port->raddr.addr, port->raddr.salen,
2472                                                 remote_host, sizeof(remote_host),
2473                                                 remote_port, sizeof(remote_port),
2474                                    (log_hostname ? 0 : NI_NUMERICHOST) | NI_NUMERICSERV))
2475         {
2476                 getnameinfo_all(&port->raddr.addr, port->raddr.salen,
2477                                                 remote_host, sizeof(remote_host),
2478                                                 remote_port, sizeof(remote_port),
2479                                                 NI_NUMERICHOST | NI_NUMERICSERV);
2480         }
2481
2482         if (Log_connections)
2483                 ereport(LOG,
2484                                 (errmsg("connection received: host=%s port=%s",
2485                                                 remote_host, remote_port)));
2486
2487         if (LogSourcePort)
2488         {
2489                 /* modify remote_host for use in ps status */
2490                 char            tmphost[NI_MAXHOST];
2491
2492                 snprintf(tmphost, sizeof(tmphost), "%s:%s", remote_host, remote_port);
2493                 StrNCpy(remote_host, tmphost, sizeof(remote_host));
2494         }
2495
2496         /*
2497          * save remote_host and remote_port in port stucture
2498          */
2499         port->remote_host = strdup(remote_host);
2500         port->remote_port = strdup(remote_port);
2501
2502         /*
2503          * Ready to begin client interaction.  We will give up and exit(0)
2504          * after a time delay, so that a broken client can't hog a connection
2505          * indefinitely.  PreAuthDelay doesn't count against the time limit.
2506          */
2507         if (!enable_sig_alarm(AuthenticationTimeout * 1000, false))
2508                 elog(FATAL, "could not set timer for authorization timeout");
2509
2510         /*
2511          * Receive the startup packet (which might turn out to be a cancel
2512          * request packet).
2513          */
2514         status = ProcessStartupPacket(port, false);
2515
2516         if (status != STATUS_OK)
2517                 proc_exit(0);
2518
2519         /*
2520          * Now that we have the user and database name, we can set the process
2521          * title for ps.  It's good to do this as early as possible in
2522          * startup.
2523          */
2524         init_ps_display(port->user_name, port->database_name, remote_host);
2525         set_ps_display("authentication");
2526
2527         /*
2528          * Now perform authentication exchange.
2529          */
2530         ClientAuthentication(port); /* might not return, if failure */
2531
2532         /*
2533          * Done with authentication.  Disable timeout, and prevent
2534          * SIGTERM/SIGQUIT again until backend startup is complete.
2535          */
2536         if (!disable_sig_alarm(false))
2537                 elog(FATAL, "could not disable timer for authorization timeout");
2538         PG_SETMASK(&BlockSig);
2539
2540         if (Log_connections)
2541                 ereport(LOG,
2542                                 (errmsg("connection authorized: user=%s database=%s",
2543                                                 port->user_name, port->database_name)));
2544
2545         /*
2546          * Don't want backend to be able to see the postmaster random number
2547          * generator state.  We have to clobber the static random_seed *and*
2548          * start a new random sequence in the random() library function.
2549          */
2550         random_seed = 0;
2551         gettimeofday(&now, &tz);
2552         srandom((unsigned int) now.tv_usec);
2553 }
2554
2555
2556 static int
2557 BackendRun(Port *port)
2558 {
2559         char      **av;
2560         int                     maxac;
2561         int                     ac;
2562         char            debugbuf[32];
2563         char            protobuf[32];
2564         int                     i;
2565
2566         /*
2567          * Let's clean up ourselves as the postmaster child, and
2568          * close the postmaster's other sockets
2569          */
2570         ClosePostmasterPorts(true);
2571
2572         /*
2573          * PreAuthDelay is a debugging aid for investigating problems in the
2574          * authentication cycle: it can be set in postgresql.conf to allow
2575          * time to attach to the newly-forked backend with a debugger. (See
2576          * also the -W backend switch, which we allow clients to pass through
2577          * PGOPTIONS, but it is not honored until after authentication.)
2578          */
2579         if (PreAuthDelay > 0)
2580                 sleep(PreAuthDelay);
2581
2582         /* Will exit on failure */
2583         BackendInit(port);
2584
2585
2586         /* ----------------
2587          * Now, build the argv vector that will be given to PostgresMain.
2588          *
2589          * The layout of the command line is
2590          *              postgres [secure switches] -p databasename [insecure switches]
2591          * where the switches after -p come from the client request.
2592          *
2593          * The maximum possible number of commandline arguments that could come
2594          * from ExtraOptions or port->cmdline_options is (strlen + 1) / 2; see
2595          * split_opts().
2596          * ----------------
2597          */
2598         maxac = 10;                                     /* for fixed args supplied below */
2599         maxac += (strlen(ExtraOptions) + 1) / 2;
2600         if (port->cmdline_options)
2601                 maxac += (strlen(port->cmdline_options) + 1) / 2;
2602
2603         av = (char **) MemoryContextAlloc(TopMemoryContext,
2604                                                                           maxac * sizeof(char *));
2605         ac = 0;
2606
2607         av[ac++] = "postgres";
2608
2609         /*
2610          * Pass the requested debugging level along to the backend.
2611          */
2612         if (debug_flag > 0)
2613         {
2614                 snprintf(debugbuf, sizeof(debugbuf), "-d%d", debug_flag);
2615                 av[ac++] = debugbuf;
2616         }
2617
2618         /*
2619          * Pass any backend switches specified with -o in the postmaster's own
2620          * command line.  We assume these are secure.
2621          */
2622         split_opts(av, &ac, ExtraOptions);
2623
2624         /* Tell the backend what protocol the frontend is using. */
2625         snprintf(protobuf, sizeof(protobuf), "-v%u", port->proto);
2626         av[ac++] = protobuf;
2627
2628 #ifdef EXEC_BACKEND
2629         /* pass data dir before end of secure switches (-p) */
2630         av[ac++] = "-D";
2631         av[ac++] = DataDir;
2632 #endif
2633
2634         /*
2635          * Tell the backend it is being called from the postmaster, and which
2636          * database to use.  -p marks the end of secure switches.
2637          */
2638         av[ac++] = "-p";
2639         av[ac++] = port->database_name;
2640
2641         /*
2642          * Pass the (insecure) option switches from the connection request.
2643          * (It's OK to mangle port->cmdline_options now.)
2644          */
2645         if (port->cmdline_options)
2646                 split_opts(av, &ac, port->cmdline_options);
2647
2648         av[ac] = NULL;
2649
2650         Assert(ac < maxac);
2651
2652         /*
2653          * Release postmaster's working memory context so that backend can
2654          * recycle the space.  Note this does not trash *MyProcPort, because
2655          * ConnCreate() allocated that space with malloc() ... else we'd need
2656          * to copy the Port data here.  Also, subsidiary data such as the
2657          * username isn't lost either; see ProcessStartupPacket().
2658          */
2659         MemoryContextSwitchTo(TopMemoryContext);
2660 #ifndef EXEC_BACKEND
2661         MemoryContextDelete(PostmasterContext);
2662 #endif
2663         PostmasterContext = NULL;
2664
2665         /*
2666          * Debug: print arguments being passed to backend
2667          */
2668         ereport(DEBUG3,
2669                         (errmsg_internal("%s child[%d]: starting with (",
2670                                                          progname, getpid())));
2671         for (i = 0; i < ac; ++i)
2672                 ereport(DEBUG3,
2673                                 (errmsg_internal("\t%s", av[i])));
2674         ereport(DEBUG3,
2675                         (errmsg_internal(")")));
2676
2677         ClientAuthInProgress = false;           /* client_min_messages is active
2678                                                                                  * now */
2679
2680         return (PostgresMain(ac, av, port->user_name));
2681 }
2682
2683
2684 #ifdef EXEC_BACKEND
2685
2686
2687 /*
2688  * SubPostmasterMain -- prepare the fork/exec'd process to be in an equivalent
2689  *                      state (for calling BackendRun) as a forked process.
2690  *
2691  * returns:
2692  *              Shouldn't return at all.
2693  */
2694 void
2695 SubPostmasterMain(int argc, char* argv[])
2696 {
2697         unsigned long   backendID;
2698         Port                    port;
2699
2700         memset((void*)&port, 0, sizeof(Port));
2701         Assert(argc == 2);
2702
2703         /* Do this sooner rather than later... */
2704         IsUnderPostmaster = true;       /* we are a postmaster subprocess now */
2705
2706         /* In EXEC case we will not have inherited these settings */
2707         IsPostmasterEnvironment = true;
2708         whereToSendOutput = None;
2709
2710         /* Setup global context */
2711         MemoryContextInit();
2712         InitializeGUCOptions();
2713
2714         /* Parse passed-in context */
2715         argc = 0;
2716         backendID               = (unsigned long)atol(argv[argc++]);
2717         DataDir                 = strdup(argv[argc++]);
2718
2719         /* Read in file-based context */
2720         read_nondefault_variables();
2721         read_backend_variables(backendID,&port);
2722
2723         /* FIXME: [fork/exec] Ugh */
2724         load_hba();
2725         load_ident();
2726         load_user();
2727         load_group();
2728
2729         /* Attach process to shared segments */
2730         CreateSharedMemoryAndSemaphores(false, MaxBackends, 0);
2731
2732         /* Run backend */
2733         proc_exit(BackendRun(&port));
2734 }
2735
2736
2737 /*
2738  * Backend_forkexec -- fork/exec off a backend process
2739  *
2740  * returns:
2741  *              the pid of the fork/exec'd process
2742  */
2743 static pid_t
2744 Backend_forkexec(Port *port)
2745 {
2746         pid_t pid;
2747         char *av[5];
2748         int ac = 0, bufc = 0, i;
2749         char buf[2][MAXPGPATH];
2750
2751         if (!write_backend_variables(port))
2752                 return -1; /* log made by write_backend_variables */
2753
2754         av[ac++] = "postgres";
2755         av[ac++] = "-forkexec";
2756
2757         /* Format up context to pass to exec'd process */
2758         snprintf(buf[bufc++],MAXPGPATH,"%lu",tmpBackendFileNum);
2759         /* FIXME: [fork/exec] whitespaces in directories? */
2760         snprintf(buf[bufc++],MAXPGPATH,"%s",DataDir);
2761
2762         /* Add to the arg list */
2763         Assert(bufc <= lengthof(buf));
2764         for (i = 0; i < bufc; i++)
2765                 av[ac++] = buf[i];
2766
2767         /* FIXME: [fork/exec] ExtraOptions? */
2768
2769         av[ac++] = NULL;
2770         Assert(ac <= lengthof(av));
2771
2772 #ifdef WIN32
2773         pid = win32_forkexec(pg_pathname,av); /* logs on error */
2774 #else
2775         /* Fire off execv in child */
2776         if ((pid = fork()) == 0 && (execv(pg_pathname,av) == -1))
2777                 /*
2778                  * FIXME: [fork/exec] suggestions for what to do here?
2779                  *  Probably OK to issue error (unlike pgstat case)
2780                  */
2781                 abort();
2782 #endif
2783         return pid; /* Parent returns pid */
2784 }
2785
2786 #endif
2787
2788
2789 /*
2790  * ExitPostmaster -- cleanup
2791  *
2792  * Do NOT call exit() directly --- always go through here!
2793  */
2794 static void
2795 ExitPostmaster(int status)
2796 {
2797         /* should cleanup shared memory and kill all backends */
2798
2799         /*
2800          * Not sure of the semantics here.      When the Postmaster dies, should
2801          * the backends all be killed? probably not.
2802          *
2803          * MUST         -- vadim 05-10-1999
2804          */
2805         /* Should I use true instead? */
2806         ClosePostmasterPorts(false);
2807
2808         proc_exit(status);
2809 }
2810
2811 /*
2812  * sigusr1_handler - handle signal conditions from child processes
2813  */
2814 static void
2815 sigusr1_handler(SIGNAL_ARGS)
2816 {
2817         int                     save_errno = errno;
2818
2819         PG_SETMASK(&BlockSig);
2820
2821         if (CheckPostmasterSignal(PMSIGNAL_DO_CHECKPOINT))
2822         {
2823                 if (CheckPointWarning != 0)
2824                 {
2825                         /*
2826                          * This only times checkpoints forced by running out of
2827                          * segment files.  Other checkpoints could reduce the
2828                          * frequency of forced checkpoints.
2829                          */
2830                         time_t          now = time(NULL);
2831
2832                         if (LastSignalledCheckpoint != 0)
2833                         {
2834                                 int                     elapsed_secs = now - LastSignalledCheckpoint;
2835
2836                                 if (elapsed_secs < CheckPointWarning)
2837                                         ereport(LOG,
2838                                                         (errmsg("checkpoints are occurring too frequently (%d seconds apart)",
2839                                                                         elapsed_secs),
2840                                         errhint("Consider increasing the configuration parameter \"checkpoint_segments\".")));
2841                         }
2842                         LastSignalledCheckpoint = now;
2843                 }
2844
2845                 /*
2846                  * Request to schedule a checkpoint
2847                  *
2848                  * Ignore request if checkpoint is already running or checkpointing
2849                  * is currently disabled
2850                  */
2851                 if (CheckPointPID == 0 && checkpointed &&
2852                         StartupPID == 0 && Shutdown == NoShutdown &&
2853                         !FatalError && random_seed != 0)
2854                 {
2855                         CheckPointPID = CheckPointDataBase();
2856                         /* note: if fork fails, CheckPointPID stays 0; nothing happens */
2857                 }
2858         }
2859
2860         if (CheckPostmasterSignal(PMSIGNAL_PASSWORD_CHANGE))
2861         {
2862                 /*
2863                  * Password or group file has changed.
2864                  */
2865                 load_user();
2866                 load_group();
2867         }
2868
2869         if (CheckPostmasterSignal(PMSIGNAL_WAKEN_CHILDREN))
2870         {
2871                 /*
2872                  * Send SIGUSR2 to all children (triggers AsyncNotifyHandler). See
2873                  * storage/ipc/sinvaladt.c for the use of this.
2874                  */
2875                 if (Shutdown == NoShutdown)
2876                         SignalChildren(SIGUSR2);
2877         }
2878
2879         PG_SETMASK(&UnBlockSig);
2880
2881         errno = save_errno;
2882 }
2883
2884
2885 /*
2886  * Dummy signal handler
2887  *
2888  * We use this for signals that we don't actually use in the postmaster,
2889  * but we do use in backends.  If we SIG_IGN such signals in the postmaster,
2890  * then a newly started backend might drop a signal that arrives before it's
2891  * able to reconfigure its signal processing.  (See notes in postgres.c.)
2892  */
2893 static void
2894 dummy_handler(SIGNAL_ARGS)
2895 {
2896 }
2897
2898
2899 /*
2900  * CharRemap: given an int in range 0..61, produce textual encoding of it
2901  * per crypt(3) conventions.
2902  */
2903 static char
2904 CharRemap(long ch)
2905 {
2906         if (ch < 0)
2907                 ch = -ch;
2908         ch = ch % 62;
2909
2910         if (ch < 26)
2911                 return 'A' + ch;
2912
2913         ch -= 26;
2914         if (ch < 26)
2915                 return 'a' + ch;
2916
2917         ch -= 26;
2918         return '0' + ch;
2919 }
2920
2921 /*
2922  * RandomSalt
2923  */
2924 static void
2925 RandomSalt(char *cryptSalt, char *md5Salt)
2926 {
2927         long            rand = PostmasterRandom();
2928
2929         cryptSalt[0] = CharRemap(rand % 62);
2930         cryptSalt[1] = CharRemap(rand / 62);
2931
2932         /*
2933          * It's okay to reuse the first random value for one of the MD5 salt
2934          * bytes, since only one of the two salts will be sent to the client.
2935          * After that we need to compute more random bits.
2936          *
2937          * We use % 255, sacrificing one possible byte value, so as to ensure
2938          * that all bits of the random() value participate in the result.
2939          * While at it, add one to avoid generating any null bytes.
2940          */
2941         md5Salt[0] = (rand % 255) + 1;
2942         rand = PostmasterRandom();
2943         md5Salt[1] = (rand % 255) + 1;
2944         rand = PostmasterRandom();
2945         md5Salt[2] = (rand % 255) + 1;
2946         rand = PostmasterRandom();
2947         md5Salt[3] = (rand % 255) + 1;
2948 }
2949
2950 /*
2951  * PostmasterRandom
2952  */
2953 static long
2954 PostmasterRandom(void)
2955 {
2956         static bool initialized = false;
2957
2958         if (!initialized)
2959         {
2960                 Assert(random_seed != 0);
2961                 srandom(random_seed);
2962                 initialized = true;
2963         }
2964
2965         return random();
2966 }
2967
2968 /*
2969  * Count up number of child processes.
2970  */
2971 static int
2972 CountChildren(void)
2973 {
2974         Dlelem     *curr;
2975         Backend    *bp;
2976         int                     cnt = 0;
2977
2978         for (curr = DLGetHead(BackendList); curr; curr = DLGetSucc(curr))
2979         {
2980                 bp = (Backend *) DLE_VAL(curr);
2981                 if (bp->pid != MyProcPid)
2982                         cnt++;
2983         }
2984         /* Checkpoint and bgwriter will be in the list, discount them */
2985         if (CheckPointPID != 0)
2986                 cnt--;
2987         if (BgWriterPID != 0)
2988                 cnt--;
2989         return cnt;
2990 }
2991
2992 /*
2993  * Fire off a subprocess for startup/shutdown/checkpoint/bgwriter.
2994  *
2995  * Return value of SSDataBase is subprocess' PID, or 0 if failed to start subprocess
2996  * (0 is returned only for checkpoint/bgwriter cases).
2997  *
2998  * note: in the EXEC_BACKEND case, we delay the fork until argument list has been
2999  *      established
3000  */
3001 NON_EXEC_STATIC void
3002 SSDataBaseInit(int xlop)
3003 {
3004         const char *statmsg;
3005
3006         IsUnderPostmaster = true;               /* we are a postmaster subprocess
3007                                                                          * now */
3008
3009 #ifdef EXEC_BACKEND
3010         /* In EXEC case we will not have inherited these settings */
3011         IsPostmasterEnvironment = true;
3012         whereToSendOutput = None;
3013 #endif
3014
3015         MyProcPid = getpid();           /* reset MyProcPid */
3016
3017         /* Lose the postmaster's on-exit routines and port connections */
3018         on_exit_reset();
3019
3020         /*
3021          * Identify myself via ps
3022          */
3023         switch (xlop)
3024         {
3025                 case BS_XLOG_STARTUP:
3026                         statmsg = "startup subprocess";
3027                         break;
3028                 case BS_XLOG_CHECKPOINT:
3029                         statmsg = "checkpoint subprocess";
3030                         break;
3031                 case BS_XLOG_BGWRITER:
3032                         statmsg = "bgwriter subprocess";
3033                         break;
3034                 case BS_XLOG_SHUTDOWN:
3035                         statmsg = "shutdown subprocess";
3036                         break;
3037                 default:
3038                         statmsg = "??? subprocess";
3039                         break;
3040         }
3041         init_ps_display(statmsg, "", "");
3042         set_ps_display("");
3043 }
3044
3045
3046 static pid_t
3047 SSDataBase(int xlop)
3048 {
3049         pid_t           pid;
3050         Backend    *bn;
3051 #ifndef EXEC_BACKEND
3052 #ifdef LINUX_PROFILE
3053         struct itimerval prof_itimer;
3054 #endif
3055 #else
3056         char            idbuf[32];
3057 #endif
3058
3059         fflush(stdout);
3060         fflush(stderr);
3061
3062 #ifndef EXEC_BACKEND
3063 #ifdef LINUX_PROFILE
3064         /* see comments in BackendRun */
3065         getitimer(ITIMER_PROF, &prof_itimer);
3066 #endif
3067
3068 #ifdef __BEOS__
3069         /* Specific beos actions before backend startup */
3070         beos_before_backend_startup();
3071 #endif
3072
3073         /* Non EXEC_BACKEND case; fork here */
3074         if ((pid = fork()) == 0)        /* child */
3075 #endif
3076         {
3077                 char       *av[10];
3078                 int                     ac = 0;
3079                 char            nbbuf[32];
3080                 char            xlbuf[32];
3081
3082 #ifndef EXEC_BACKEND
3083 #ifdef LINUX_PROFILE
3084                 setitimer(ITIMER_PROF, &prof_itimer, NULL);
3085 #endif
3086
3087 #ifdef __BEOS__
3088                 /* Specific beos actions after backend startup */
3089                 beos_backend_startup();
3090 #endif
3091
3092                 /* Close the postmaster's sockets */
3093                 ClosePostmasterPorts(true);
3094
3095                 SSDataBaseInit(xlop);
3096 #else
3097                 if (!write_backend_variables(NULL))
3098                         return -1; /* log issued by write_backend_variables */
3099 #endif
3100
3101                 /* Set up command-line arguments for subprocess */
3102                 av[ac++] = "postgres";
3103
3104 #ifdef EXEC_BACKEND
3105                 av[ac++] = "-boot";
3106 #endif
3107                 snprintf(nbbuf, sizeof(nbbuf), "-B%d", NBuffers);
3108                 av[ac++] = nbbuf;
3109
3110                 snprintf(xlbuf, sizeof(xlbuf), "-x%d", xlop);
3111                 av[ac++] = xlbuf;
3112
3113 #ifdef EXEC_BACKEND
3114                 /* pass data dir before end of secure switches (-p) */
3115                 av[ac++] = "-D";
3116                 av[ac++] = DataDir;
3117
3118                 /* and the backend identifier + dbname */
3119                 snprintf(idbuf, sizeof(idbuf), "-p%lu,template1", tmpBackendFileNum);
3120                 av[ac++] = idbuf;
3121 #else
3122                 av[ac++] = "-p";
3123                 av[ac++] = "template1";
3124 #endif
3125
3126                 av[ac] = NULL;
3127
3128                 Assert(ac < lengthof(av));
3129
3130 #ifdef EXEC_BACKEND
3131                 /* EXEC_BACKEND case; fork/exec here */
3132 #ifdef WIN32
3133                 pid = win32_forkexec(pg_pathname,av); /* logs on error */
3134 #else
3135                 if ((pid = fork()) == 0 && (execv(pg_pathname,av) == -1))
3136                 {
3137                         /* in child */
3138                         elog(ERROR,"unable to execv in SSDataBase: %m");
3139                         exit(0);
3140                 }
3141 #endif
3142 #else
3143                 BootstrapMain(ac, av);
3144                 ExitPostmaster(0);
3145 #endif
3146         }
3147
3148         /* in parent */
3149         if (pid < 0)
3150         {
3151 #ifndef EXEC_BACKEND
3152 #ifdef __BEOS__
3153                 /* Specific beos actions before backend startup */
3154                 beos_backend_startup_failed();
3155 #endif
3156 #endif
3157                 switch (xlop)
3158                 {
3159                         case BS_XLOG_STARTUP:
3160                                 ereport(LOG,
3161                                                 (errmsg("could not fork startup process: %m")));
3162                                 break;
3163                         case BS_XLOG_CHECKPOINT:
3164                                 ereport(LOG,
3165                                           (errmsg("could not fork checkpoint process: %m")));
3166                                 break;
3167                         case BS_XLOG_BGWRITER:
3168                                 ereport(LOG,
3169                                           (errmsg("could not fork bgwriter process: %m")));
3170                                 break;
3171                         case BS_XLOG_SHUTDOWN:
3172                                 ereport(LOG,
3173                                                 (errmsg("could not fork shutdown process: %m")));
3174                                 break;
3175                         default:
3176                                 ereport(LOG,
3177                                                 (errmsg("could not fork process: %m")));
3178                                 break;
3179                 }
3180
3181                 /*
3182                  * fork failure is fatal during startup/shutdown, but there's no
3183                  * need to choke if a routine checkpoint or starting a background
3184                  * writer fails.
3185                  */
3186                 if (xlop == BS_XLOG_CHECKPOINT)
3187                         return 0;
3188                 if (xlop == BS_XLOG_BGWRITER)
3189                         return 0;
3190                 ExitPostmaster(1);
3191         }
3192
3193         /*
3194          * The startup and shutdown processes are not considered normal
3195          * backends, but the checkpoint and bgwriter processes are.
3196          * They must be added to the list of backends.
3197          */
3198         if (xlop == BS_XLOG_CHECKPOINT || xlop == BS_XLOG_BGWRITER)
3199         {
3200                 if (!(bn = (Backend *) malloc(sizeof(Backend))))
3201                 {
3202                         ereport(LOG,
3203                                         (errcode(ERRCODE_OUT_OF_MEMORY),
3204                                          errmsg("out of memory")));
3205                         ExitPostmaster(1);
3206                 }
3207
3208                 bn->pid = pid;
3209                 bn->cancel_key = PostmasterRandom();
3210 #ifdef EXEC_BACKEND
3211                 ShmemBackendArrayAdd(bn);
3212 #endif
3213                 DLAddHead(BackendList, DLNewElem(bn));
3214
3215                 /*
3216                  * Since this code is executed periodically, it's a fine place to
3217                  * do other actions that should happen every now and then on no
3218                  * particular schedule.  Such as...
3219                  */
3220                 TouchSocketFile();
3221                 TouchSocketLockFile();
3222         }
3223
3224         return pid;
3225 }
3226
3227
3228 /*
3229  * Create the opts file
3230  */
3231 static bool
3232 CreateOptsFile(int argc, char *argv[])
3233 {
3234         char            fullprogname[MAXPGPATH];
3235         char            filename[MAXPGPATH];
3236         FILE       *fp;
3237         int                     i;
3238
3239         if (FindExec(fullprogname, argv[0], "postmaster") < 0)
3240                 return false;
3241
3242         snprintf(filename, sizeof(filename), "%s/postmaster.opts", DataDir);
3243
3244         if ((fp = fopen(filename, "w")) == NULL)
3245         {
3246                 elog(LOG, "could not create file \"%s\": %m", filename);
3247                 return false;
3248         }
3249
3250         fprintf(fp, "%s", fullprogname);
3251         for (i = 1; i < argc; i++)
3252                 fprintf(fp, " '%s'", argv[i]);
3253         fputs("\n", fp);
3254
3255         if (fclose(fp))
3256         {
3257                 elog(LOG, "could not write file \"%s\": %m", filename);
3258                 return false;
3259         }
3260
3261         return true;
3262 }
3263
3264 /*
3265  * This should be used only for reporting "interactive" errors (essentially,
3266  * bogus arguments on the command line).  Once the postmaster is launched,
3267  * use ereport.  In particular, don't use this for anything that occurs
3268  * after pmdaemonize.
3269  */
3270 static void
3271 postmaster_error(const char *fmt,...)
3272 {
3273         va_list         ap;
3274
3275         fprintf(stderr, "%s: ", progname);
3276         va_start(ap, fmt);
3277         vfprintf(stderr, gettext(fmt), ap);
3278         va_end(ap);
3279         fprintf(stderr, "\n");
3280 }
3281
3282
3283 #ifdef EXEC_BACKEND
3284
3285 /*
3286  * The following need to be available to the read/write_backend_variables
3287  * functions
3288  */
3289 #include "storage/spin.h"
3290 extern XLogRecPtr RedoRecPtr;
3291 extern XLogwrtResult LogwrtResult;
3292 extern slock_t *ShmemLock;
3293 extern slock_t *ShmemIndexLock;
3294 extern void *ShmemIndexAlloc;
3295 typedef struct LWLock LWLock;
3296 extern LWLock *LWLockArray;
3297 extern slock_t  *ProcStructLock;
3298 extern int      pgStatSock;
3299
3300 #define write_var(var,fp) fwrite((void*)&(var),sizeof(var),1,fp)
3301 #define read_var(var,fp)  fread((void*)&(var),sizeof(var),1,fp)
3302 #define get_tmp_backend_file_name(buf,id)       \
3303                 do {                                                            \
3304                         Assert(DataDir);                                \
3305                         sprintf((buf),                                  \
3306                                 "%s/%s/%s.backend_var.%lu",     \
3307                                 DataDir,                                        \
3308                                 PG_TEMP_FILES_DIR,                      \
3309                                 PG_TEMP_FILE_PREFIX,            \
3310                                 (id));                                          \
3311                 } while (0)
3312
3313 static bool
3314 write_backend_variables(Port *port)
3315 {
3316         char    filename[MAXPGPATH];
3317         FILE    *fp;
3318         get_tmp_backend_file_name(filename,++tmpBackendFileNum);
3319
3320         /* Open file */
3321         fp = AllocateFile(filename, PG_BINARY_W);
3322         if (!fp)
3323         {
3324                 /* As per OpenTemporaryFile... */
3325                 char dirname[MAXPGPATH];
3326                 sprintf(dirname,"%s/%s",DataDir,PG_TEMP_FILES_DIR);
3327                 mkdir(dirname, S_IRWXU);
3328
3329                 fp = AllocateFile(filename, PG_BINARY_W);
3330                 if (!fp)
3331                 {
3332                         ereport(ERROR,
3333                                 (errcode_for_file_access(),
3334                                 errmsg("could not write to file \"%s\": %m", filename)));
3335                         return false;
3336                 }
3337         }
3338
3339         /* Write vars */
3340         if (port)
3341         {
3342                 write_var(port->sock,fp);
3343                 write_var(port->proto,fp);
3344                 write_var(port->laddr,fp);
3345                 write_var(port->raddr,fp);
3346                 write_var(port->canAcceptConnections,fp);
3347                 write_var(port->cryptSalt,fp);
3348                 write_var(port->md5Salt,fp);
3349         }
3350         write_var(MyCancelKey,fp);
3351
3352         write_var(RedoRecPtr,fp);
3353         write_var(LogwrtResult,fp);
3354
3355         write_var(UsedShmemSegID,fp);
3356         write_var(UsedShmemSegAddr,fp);
3357
3358         write_var(ShmemLock,fp);
3359         write_var(ShmemIndexLock,fp);
3360         write_var(ShmemVariableCache,fp);
3361         write_var(ShmemIndexAlloc,fp);
3362         write_var(ShmemBackendArray,fp);
3363
3364         write_var(LWLockArray,fp);
3365         write_var(ProcStructLock,fp);
3366         write_var(pgStatSock,fp);
3367
3368         write_var(PreAuthDelay,fp);
3369         write_var(debug_flag,fp);
3370         write_var(PostmasterPid,fp);
3371
3372         /* Release file */
3373         if (FreeFile(fp))
3374         {
3375                 ereport(ERROR,
3376                                 (errcode_for_file_access(),
3377                                  errmsg("could not write to file \"%s\": %m", filename)));
3378                 return false;
3379         }
3380
3381         return true;
3382 }
3383
3384 void
3385 read_backend_variables(unsigned long id, Port *port)
3386 {
3387         char    filename[MAXPGPATH];
3388         FILE    *fp;
3389         get_tmp_backend_file_name(filename,id);
3390
3391         /* Open file */
3392         fp = AllocateFile(filename, PG_BINARY_R);
3393         if (!fp)
3394         {
3395                 ereport(ERROR,
3396                         (errcode_for_file_access(),
3397                         errmsg("could not read from backend_variables file \"%s\": %m", filename)));
3398                 return;
3399         }
3400
3401         /* Read vars */
3402         if (port)
3403         {
3404                 read_var(port->sock,fp);
3405                 read_var(port->proto,fp);
3406                 read_var(port->laddr,fp);
3407                 read_var(port->raddr,fp);
3408                 read_var(port->canAcceptConnections,fp);
3409                 read_var(port->cryptSalt,fp);
3410                 read_var(port->md5Salt,fp);
3411         }
3412         read_var(MyCancelKey,fp);
3413
3414         read_var(RedoRecPtr,fp);
3415         read_var(LogwrtResult,fp);
3416
3417         read_var(UsedShmemSegID,fp);
3418         read_var(UsedShmemSegAddr,fp);
3419
3420         read_var(ShmemLock,fp);
3421         read_var(ShmemIndexLock,fp);
3422         read_var(ShmemVariableCache,fp);
3423         read_var(ShmemIndexAlloc,fp);
3424         read_var(ShmemBackendArray,fp);
3425
3426         read_var(LWLockArray,fp);
3427         read_var(ProcStructLock,fp);
3428         read_var(pgStatSock,fp);
3429
3430         read_var(PreAuthDelay,fp);
3431         read_var(debug_flag,fp);
3432         read_var(PostmasterPid,fp);
3433
3434         /* Release file */
3435         FreeFile(fp);
3436         if (unlink(filename) != 0)
3437                 ereport(WARNING,
3438                                 (errcode_for_file_access(),
3439                                  errmsg("could not remove file \"%s\": %m", filename)));
3440 }
3441
3442
3443 size_t ShmemBackendArraySize(void)
3444 {
3445         return (NUM_BACKENDARRAY_ELEMS*sizeof(Backend));
3446 }
3447
3448 void ShmemBackendArrayAllocation(void)
3449 {
3450         size_t size = ShmemBackendArraySize();
3451         ShmemBackendArray = (Backend*)ShmemAlloc(size);
3452         memset(ShmemBackendArray, 0, size);
3453 }
3454
3455 static void ShmemBackendArrayAdd(Backend *bn)
3456 {
3457         int i;
3458         for (i = 0; i < NUM_BACKENDARRAY_ELEMS; i++)
3459         {
3460                 /* Find an empty slot */
3461                 if (ShmemBackendArray[i].pid == 0)
3462                 {
3463                         ShmemBackendArray[i] = *bn;
3464                         return;
3465                 }
3466         }
3467
3468         /* FIXME: [fork/exec] some sort of error */
3469         abort();
3470 }
3471
3472 static void ShmemBackendArrayRemove(pid_t pid)
3473 {
3474         int i;
3475         for (i = 0; i < NUM_BACKENDARRAY_ELEMS; i++)
3476         {
3477                 if (ShmemBackendArray[i].pid == pid)
3478                 {
3479                         /* Mark the slot as empty */
3480                         ShmemBackendArray[i].pid = 0;
3481                         return;
3482                 }
3483         }
3484
3485         /* Something stronger than WARNING here? */
3486         ereport(WARNING,
3487                         (errmsg_internal("unable to find backend entry with pid %d",
3488                                                          pid)));
3489 }
3490
3491 #endif
3492
3493 #ifdef WIN32
3494
3495 pid_t win32_forkexec(const char* path, char *argv[])
3496 {
3497         STARTUPINFO si;
3498         PROCESS_INFORMATION pi;
3499         char *p;
3500         int i;
3501         char cmdLine[MAXPGPATH];
3502         HANDLE childHandleCopy;
3503         HANDLE waiterThread;
3504
3505         /* Format the cmd line */
3506         snprintf(cmdLine,sizeof(cmdLine),"%s",path);
3507         i = 0;
3508         while (argv[++i] != NULL)
3509         {
3510                 /* FIXME: [fork/exec] some strlen checks might be prudent here */
3511                 strcat(cmdLine," ");
3512                 strcat(cmdLine,argv[i]);
3513         }
3514
3515         /*
3516          * The following snippet can disappear when we consistently
3517          * use forward slashes.
3518          */
3519         p = cmdLine;
3520         while (*(p++) != '\0')
3521                 if (*p == '/') *p = '\\';
3522
3523         memset(&pi,0,sizeof(pi));
3524         memset(&si,0,sizeof(si));
3525         si.cb = sizeof(si);
3526         if (!CreateProcess(NULL,cmdLine,NULL,NULL,TRUE,0,NULL,NULL,&si,&pi))
3527         {
3528                 elog(ERROR,"CreateProcess call failed (%d): %m",GetLastError());
3529                 return -1;
3530         }
3531
3532         if (!IsUnderPostmaster)
3533                 /* We are the Postmaster creating a child... */
3534                 win32_AddChild(pi.dwProcessId,pi.hProcess);
3535         
3536         if (!DuplicateHandle(GetCurrentProcess(),
3537                                                  pi.hProcess,
3538                                                  GetCurrentProcess(),
3539                                                  &childHandleCopy,
3540                                                  0,
3541                                                  FALSE,
3542                                                  DUPLICATE_SAME_ACCESS)) 
3543                 ereport(FATAL,
3544                                 (errmsg_internal("failed to duplicate child handle: %i",GetLastError())));
3545         waiterThread = CreateThread(NULL, 64*1024, win32_sigchld_waiter, (LPVOID)childHandleCopy, 0, NULL);
3546         if (!waiterThread)
3547                 ereport(FATAL,
3548                                 (errmsg_internal("failed to create sigchld waiter thread: %i",GetLastError())));
3549         CloseHandle(waiterThread);      
3550         
3551         if (IsUnderPostmaster)
3552                 CloseHandle(pi.hProcess);
3553         CloseHandle(pi.hThread);
3554
3555         return pi.dwProcessId;
3556 }
3557
3558 /*
3559  * Note: The following three functions must not be interrupted (eg. by signals).
3560  *  As the Postgres Win32 signalling architecture (currently) requires polling,
3561  *  or APC checking functions which aren't used here, this is not an issue.
3562  *
3563  *  We keep two separate arrays, instead of a single array of pid/HANDLE structs,
3564  *  to avoid having to re-create a handle array for WaitForMultipleObjects on
3565  *  each call to win32_waitpid.
3566  */
3567
3568 static void win32_AddChild(pid_t pid, HANDLE handle)
3569 {
3570         Assert(win32_childPIDArray && win32_childHNDArray);
3571         if (win32_numChildren < NUM_BACKENDARRAY_ELEMS)
3572         {
3573                 win32_childPIDArray[win32_numChildren] = pid;
3574                 win32_childHNDArray[win32_numChildren] = handle;
3575                 ++win32_numChildren;
3576         }
3577         else
3578                 /* FIXME: [fork/exec] some sort of error */
3579                 abort();
3580 }
3581
3582 static void win32_RemoveChild(pid_t pid)
3583 {
3584         int i;
3585         Assert(win32_childPIDArray && win32_childHNDArray);
3586
3587         for (i = 0; i < win32_numChildren; i++)
3588         {
3589                 if (win32_childPIDArray[i] == pid)
3590                 {
3591                         CloseHandle(win32_childHNDArray[i]);
3592
3593                         /* Swap last entry into the "removed" one */
3594                         --win32_numChildren;
3595                         win32_childPIDArray[i] = win32_childPIDArray[win32_numChildren];
3596                         win32_childHNDArray[i] = win32_childHNDArray[win32_numChildren];
3597                         return;
3598                 }
3599         }
3600
3601         /* Something stronger than WARNING here? */
3602         ereport(WARNING,
3603                         (errmsg_internal("unable to find child entry with pid %d",
3604                                                          pid)));
3605 }
3606
3607 static pid_t win32_waitpid(int *exitstatus)
3608 {
3609         Assert(win32_childPIDArray && win32_childHNDArray);
3610         elog(DEBUG3,"waiting on %d children",win32_numChildren);
3611
3612         if (win32_numChildren > 0)
3613         {
3614                 /*
3615                  * Note: Do NOT use WaitForMultipleObjectsEx, as we don't
3616                  * want to run queued APCs here.
3617                  */
3618                 int index;
3619                 DWORD exitCode;
3620                 DWORD ret = WaitForMultipleObjects(win32_numChildren,win32_childHNDArray,FALSE,0);
3621
3622                 switch (ret)
3623                 {
3624                         case WAIT_FAILED:
3625                                 ereport(ERROR,
3626                                                 (errmsg_internal("failed to wait on %d children: %i",
3627                                                                                  win32_numChildren,GetLastError())));
3628                                 /* Fall through to WAIT_TIMEOUTs return */
3629
3630                         case WAIT_TIMEOUT:
3631                                 /* No children have finished */
3632                                 return -1;
3633
3634                         default:
3635                                 /* Get the exit code, and return the PID of, the respective process */
3636                                 index = ret-WAIT_OBJECT_0;
3637                                 Assert(index >= 0 && index < win32_numChildren);
3638                                 if (!GetExitCodeProcess(win32_childHNDArray[index],&exitCode))
3639                                         /*
3640                                          * If we get this far, this should never happen, but, then again...
3641                                          * No choice other than to assume a catastrophic failure.
3642                                          */
3643                                         ereport(FATAL,
3644                                                         (errmsg_internal("failed to get exit code for child %d",
3645                                                                                          win32_childPIDArray[index])));
3646                                 *exitstatus = (int)exitCode;
3647                                 return win32_childPIDArray[index];
3648                 }
3649         }
3650
3651         /* No children */
3652         return -1;
3653 }
3654
3655 /* Note! Code belows executes on separate threads, one for
3656    each child process created */
3657 static DWORD WINAPI win32_sigchld_waiter(LPVOID param) {
3658         HANDLE procHandle = (HANDLE)param;
3659
3660         DWORD r = WaitForSingleObject(procHandle, INFINITE);
3661         if (r == WAIT_OBJECT_0)
3662                 pg_queue_signal(SIGCHLD);
3663         else
3664                 fprintf(stderr,"ERROR: Failed to wait on child process handle: %i\n",GetLastError());
3665         CloseHandle(procHandle);
3666         return 0;
3667 }
3668
3669 #endif