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