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