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