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