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