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