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