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