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