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