]> granicus.if.org Git - postgresql/blob - src/backend/postmaster/postmaster.c
Code review for SSLKEY patch.
[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-2007, 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.525 2007/02/16 17:06:59 tgl 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 <fcntl.h>
77 #include <sys/param.h>
78 #include <netinet/in.h>
79 #include <arpa/inet.h>
80 #include <netdb.h>
81 #include <limits.h>
82
83 #ifdef HAVE_SYS_SELECT_H
84 #include <sys/select.h>
85 #endif
86
87 #ifdef HAVE_GETOPT_H
88 #include <getopt.h>
89 #endif
90
91 #ifdef USE_BONJOUR
92 #include <DNSServiceDiscovery/DNSServiceDiscovery.h>
93 #endif
94
95 #include "access/transam.h"
96 #include "bootstrap/bootstrap.h"
97 #include "catalog/pg_control.h"
98 #include "lib/dllist.h"
99 #include "libpq/auth.h"
100 #include "libpq/ip.h"
101 #include "libpq/libpq.h"
102 #include "libpq/pqsignal.h"
103 #include "miscadmin.h"
104 #include "pgstat.h"
105 #include "postmaster/autovacuum.h"
106 #include "postmaster/fork_process.h"
107 #include "postmaster/pgarch.h"
108 #include "postmaster/postmaster.h"
109 #include "postmaster/syslogger.h"
110 #include "storage/fd.h"
111 #include "storage/ipc.h"
112 #include "storage/pg_shmem.h"
113 #include "storage/pmsignal.h"
114 #include "storage/proc.h"
115 #include "tcop/tcopprot.h"
116 #include "utils/builtins.h"
117 #include "utils/datetime.h"
118 #include "utils/memutils.h"
119 #include "utils/ps_status.h"
120
121 #ifdef EXEC_BACKEND
122 #include "storage/spin.h"
123 #endif
124
125
126 /*
127  * List of active backends (or child processes anyway; we don't actually
128  * know whether a given child has become a backend or is still in the
129  * authorization phase).  This is used mainly to keep track of how many
130  * children we have and send them appropriate signals when necessary.
131  *
132  * "Special" children such as the startup, bgwriter and autovacuum launcher
133  * tasks are not in this list.  Autovacuum worker processes are on it.
134  */
135 typedef struct bkend
136 {
137         pid_t           pid;                    /* process id of backend */
138         long            cancel_key;             /* cancel key for cancels for this backend */
139         bool            is_autovacuum;  /* is it an autovacuum process */
140 } Backend;
141
142 static Dllist *BackendList;
143
144 #ifdef EXEC_BACKEND
145 /*
146  * Number of entries in the backend table. Twice the number of backends,
147  * plus four other subprocesses (stats, bgwriter, autovac, logger).
148  */
149 #define NUM_BACKENDARRAY_ELEMS (2*MaxBackends + 4)
150 static Backend *ShmemBackendArray;
151 #endif
152
153 /* The socket number we are listening for connections on */
154 int                     PostPortNumber;
155 char       *UnixSocketDir;
156 char       *ListenAddresses;
157
158 /*
159  * ReservedBackends is the number of backends reserved for superuser use.
160  * This number is taken out of the pool size given by MaxBackends so
161  * number of backend slots available to non-superusers is
162  * (MaxBackends - ReservedBackends).  Note what this really means is
163  * "if there are <= ReservedBackends connections available, only superusers
164  * can make new connections" --- pre-existing superuser connections don't
165  * count against the limit.
166  */
167 int                     ReservedBackends;
168
169 /* The socket(s) we're listening to. */
170 #define MAXLISTEN       64
171 static int      ListenSocket[MAXLISTEN];
172
173 /*
174  * Set by the -o option
175  */
176 static char ExtraOptions[MAXPGPATH];
177
178 /*
179  * These globals control the behavior of the postmaster in case some
180  * backend dumps core.  Normally, it kills all peers of the dead backend
181  * and reinitializes shared memory.  By specifying -s or -n, we can have
182  * the postmaster stop (rather than kill) peers and not reinitialize
183  * shared data structures.
184  */
185 static bool Reinit = true;
186 static int      SendStop = false;
187
188 /* still more option variables */
189 bool            EnableSSL = false;
190 bool            SilentMode = false; /* silent mode (-S) */
191
192 int                     PreAuthDelay = 0;
193 int                     AuthenticationTimeout = 60;
194
195 bool            log_hostname;           /* for ps display and logging */
196 bool            Log_connections = false;
197 bool            Db_user_namespace = false;
198
199 char       *bonjour_name;
200
201 /* PIDs of special child processes; 0 when not running */
202 static pid_t StartupPID = 0,
203                         BgWriterPID = 0,
204                         AutoVacPID = 0,
205                         PgArchPID = 0,
206                         PgStatPID = 0;
207 pid_t                   SysLoggerPID = 0; /* Needs to be accessed from elog.c */
208
209 /* Startup/shutdown state */
210 #define                 NoShutdown              0
211 #define                 SmartShutdown   1
212 #define                 FastShutdown    2
213
214 static int      Shutdown = NoShutdown;
215
216 static bool FatalError = false; /* T if recovering from backend crash */
217
218 bool            ClientAuthInProgress = false;           /* T during new-client
219                                                                                                  * authentication */
220
221 /* received START_AUTOVAC_LAUNCHER signal */
222 static bool start_autovac_launcher = false;
223
224 /*
225  * State for assigning random salts and cancel keys.
226  * Also, the global MyCancelKey passes the cancel key assigned to a given
227  * backend from the postmaster to that backend (via fork).
228  */
229 static unsigned int random_seed = 0;
230
231 extern char *optarg;
232 extern int      optind,
233                         opterr;
234
235 #ifdef HAVE_INT_OPTRESET
236 extern int      optreset;
237 #endif
238
239 /*
240  * postmaster.c - function prototypes
241  */
242 static void checkDataDir(void);
243
244 #ifdef USE_BONJOUR
245 static void reg_reply(DNSServiceRegistrationReplyErrorType errorCode,
246                   void *context);
247 #endif
248 static void pmdaemonize(void);
249 static Port *ConnCreate(int serverFd);
250 static void ConnFree(Port *port);
251 static void reset_shared(int port);
252 static void SIGHUP_handler(SIGNAL_ARGS);
253 static void pmdie(SIGNAL_ARGS);
254 static void reaper(SIGNAL_ARGS);
255 static void sigusr1_handler(SIGNAL_ARGS);
256 static void dummy_handler(SIGNAL_ARGS);
257 static void CleanupBackend(int pid, int exitstatus);
258 static void HandleChildCrash(int pid, int exitstatus, const char *procname);
259 static void LogChildExit(int lev, const char *procname,
260                          int pid, int exitstatus);
261 static void BackendInitialize(Port *port);
262 static int      BackendRun(Port *port);
263 static void ExitPostmaster(int status);
264 static int      ServerLoop(void);
265 static int      BackendStartup(Port *port);
266 static int      ProcessStartupPacket(Port *port, bool SSLdone);
267 static void processCancelRequest(Port *port, void *pkt);
268 static int      initMasks(fd_set *rmask);
269 static void report_fork_failure_to_client(Port *port, int errnum);
270 static enum CAC_state canAcceptConnections(void);
271 static long PostmasterRandom(void);
272 static void RandomSalt(char *cryptSalt, char *md5Salt);
273 static void signal_child(pid_t pid, int signal);
274 static void SignalChildren(int signal);
275 static void SignalSomeChildren(int signal, bool only_autovac);
276 static int      CountChildren(void);
277 static bool CreateOptsFile(int argc, char *argv[], char *fullprogname);
278 static pid_t StartChildProcess(int xlop);
279 static void StartAutovacuumWorker(void);
280
281 #ifdef EXEC_BACKEND
282
283 #ifdef WIN32
284 static void win32_AddChild(pid_t pid, HANDLE handle);
285 static void win32_RemoveChild(pid_t pid);
286 static pid_t win32_waitpid(int *exitstatus);
287 static DWORD WINAPI win32_sigchld_waiter(LPVOID param);
288
289 static pid_t *win32_childPIDArray;
290 static HANDLE *win32_childHNDArray;
291 static unsigned long win32_numChildren = 0;
292
293 HANDLE          PostmasterHandle;
294 #endif
295
296 static pid_t backend_forkexec(Port *port);
297 static pid_t internal_forkexec(int argc, char *argv[], Port *port);
298
299 /* Type for a socket that can be inherited to a client process */
300 #ifdef WIN32
301 typedef struct
302 {
303         SOCKET          origsocket;             /* Original socket value, or -1 if not a
304                                                                  * socket */
305         WSAPROTOCOL_INFO wsainfo;
306 }       InheritableSocket;
307 #else
308 typedef int InheritableSocket;
309 #endif
310
311 typedef struct LWLock LWLock;   /* ugly kluge */
312
313 /*
314  * Structure contains all variables passed to exec:ed backends
315  */
316 typedef struct
317 {
318         Port            port;
319         InheritableSocket portsocket;
320         char            DataDir[MAXPGPATH];
321         int                     ListenSocket[MAXLISTEN];
322         long            MyCancelKey;
323         unsigned long UsedShmemSegID;
324         void       *UsedShmemSegAddr;
325         slock_t    *ShmemLock;
326         VariableCache ShmemVariableCache;
327         Backend    *ShmemBackendArray;
328         LWLock     *LWLockArray;
329         slock_t    *ProcStructLock;
330         PROC_HDR   *ProcGlobal;
331         PGPROC     *DummyProcs;
332         InheritableSocket pgStatSock;
333         pid_t           PostmasterPid;
334         TimestampTz PgStartTime;
335 #ifdef WIN32
336         HANDLE          PostmasterHandle;
337         HANDLE          initial_signal_pipe;
338         HANDLE          syslogPipe[2];
339 #else
340         int                     syslogPipe[2];
341 #endif
342         char            my_exec_path[MAXPGPATH];
343         char            pkglib_path[MAXPGPATH];
344         char            ExtraOptions[MAXPGPATH];
345         char            lc_collate[LOCALE_NAME_BUFLEN];
346         char            lc_ctype[LOCALE_NAME_BUFLEN];
347 }       BackendParameters;
348
349 static void read_backend_variables(char *id, Port *port);
350 static void restore_backend_variables(BackendParameters * param, Port *port);
351
352 #ifndef WIN32
353 static bool save_backend_variables(BackendParameters * param, Port *port);
354 #else
355 static bool save_backend_variables(BackendParameters * param, Port *port,
356                                            HANDLE childProcess, pid_t childPid);
357 #endif
358
359 static void ShmemBackendArrayAdd(Backend *bn);
360 static void ShmemBackendArrayRemove(pid_t pid);
361 #endif   /* EXEC_BACKEND */
362
363 #define StartupDataBase()               StartChildProcess(BS_XLOG_STARTUP)
364 #define StartBackgroundWriter() StartChildProcess(BS_XLOG_BGWRITER)
365
366 /* Macros to check exit status of a child process */
367 #define EXIT_STATUS_0(st)  ((st) == 0)
368 #define EXIT_STATUS_1(st)  (WIFEXITED(st) && WEXITSTATUS(st) == 1)
369
370
371 /*
372  * Postmaster main entry point
373  */
374 int
375 PostmasterMain(int argc, char *argv[])
376 {
377         int                     opt;
378         int                     status;
379         char       *userDoption = NULL;
380         int                     i;
381
382         MyProcPid = PostmasterPid = getpid();
383
384         IsPostmasterEnvironment = true;
385
386         /*
387          * for security, no dir or file created can be group or other accessible
388          */
389         umask((mode_t) 0077);
390
391         /*
392          * Fire up essential subsystems: memory management
393          */
394         MemoryContextInit();
395
396         /*
397          * By default, palloc() requests in the postmaster will be allocated in
398          * the PostmasterContext, which is space that can be recycled by backends.
399          * Allocated data that needs to be available to backends should be
400          * allocated in TopMemoryContext.
401          */
402         PostmasterContext = AllocSetContextCreate(TopMemoryContext,
403                                                                                           "Postmaster",
404                                                                                           ALLOCSET_DEFAULT_MINSIZE,
405                                                                                           ALLOCSET_DEFAULT_INITSIZE,
406                                                                                           ALLOCSET_DEFAULT_MAXSIZE);
407         MemoryContextSwitchTo(PostmasterContext);
408
409         if (find_my_exec(argv[0], my_exec_path) < 0)
410                 elog(FATAL, "%s: could not locate my own executable path",
411                          argv[0]);
412
413         get_pkglib_path(my_exec_path, pkglib_path);
414
415         /*
416          * Options setup
417          */
418         InitializeGUCOptions();
419
420         opterr = 1;
421
422         /*
423          * Parse command-line options.  CAUTION: keep this in sync with
424          * tcop/postgres.c (the option sets should not conflict)
425          * and with the common help() function in main/main.c.
426          */
427         while ((opt = getopt(argc, argv, "A:B:c:D:d:EeFf:h:ijk:lN:nOo:Pp:r:S:sTt:W:-:")) != -1)
428         {
429                 switch (opt)
430                 {
431                         case 'A':
432                                 SetConfigOption("debug_assertions", optarg, PGC_POSTMASTER, PGC_S_ARGV);
433                                 break;
434
435                         case 'B':
436                                 SetConfigOption("shared_buffers", optarg, PGC_POSTMASTER, PGC_S_ARGV);
437                                 break;
438
439                         case 'D':
440                                 userDoption = optarg;
441                                 break;
442
443                         case 'd':
444                                 set_debug_options(atoi(optarg), PGC_POSTMASTER, PGC_S_ARGV);
445                                 break;
446
447                         case 'E':
448                                 SetConfigOption("log_statement", "all", PGC_POSTMASTER, PGC_S_ARGV);
449                                 break;
450
451                         case 'e':
452                                 SetConfigOption("datestyle", "euro", PGC_POSTMASTER, PGC_S_ARGV);
453                                 break;
454
455                         case 'F':
456                                 SetConfigOption("fsync", "false", PGC_POSTMASTER, PGC_S_ARGV);
457                                 break;
458
459                         case 'f':
460                                 if (!set_plan_disabling_options(optarg, PGC_POSTMASTER, PGC_S_ARGV))
461                                 {
462                                         write_stderr("%s: invalid argument for option -f: \"%s\"\n",
463                                                                  progname, optarg);
464                                         ExitPostmaster(1);
465                                 }
466                                 break;
467
468                         case 'h':
469                                 SetConfigOption("listen_addresses", optarg, PGC_POSTMASTER, PGC_S_ARGV);
470                                 break;
471
472                         case 'i':
473                                 SetConfigOption("listen_addresses", "*", PGC_POSTMASTER, PGC_S_ARGV);
474                                 break;
475
476                         case 'j':
477                                 /* only used by interactive backend */
478                                 break;
479
480                         case 'k':
481                                 SetConfigOption("unix_socket_directory", optarg, PGC_POSTMASTER, PGC_S_ARGV);
482                                 break;
483
484                         case 'l':
485                                 SetConfigOption("ssl", "true", PGC_POSTMASTER, PGC_S_ARGV);
486                                 break;
487
488                         case 'N':
489                                 SetConfigOption("max_connections", optarg, PGC_POSTMASTER, PGC_S_ARGV);
490                                 break;
491
492                         case 'n':
493                                 /* Don't reinit shared mem after abnormal exit */
494                                 Reinit = false;
495                                 break;
496
497                         case 'O':
498                                 SetConfigOption("allow_system_table_mods", "true", PGC_POSTMASTER, PGC_S_ARGV);
499                                 break;
500
501                         case 'o':
502                                 /* Other options to pass to the backend on the command line */
503                                 snprintf(ExtraOptions + strlen(ExtraOptions),
504                                                  sizeof(ExtraOptions) - strlen(ExtraOptions),
505                                                  " %s", optarg);
506                                 break;
507
508                         case 'P':
509                                 SetConfigOption("ignore_system_indexes", "true", PGC_POSTMASTER, PGC_S_ARGV);
510                                 break;
511
512                         case 'p':
513                                 SetConfigOption("port", optarg, PGC_POSTMASTER, PGC_S_ARGV);
514                                 break;
515
516                         case 'r':
517                                 /* only used by single-user backend */
518                                 break;
519
520                         case 'S':
521                                 SetConfigOption("work_mem", optarg, PGC_POSTMASTER, PGC_S_ARGV);
522                                 break;
523
524                         case 's':
525                                 SetConfigOption("log_statement_stats", "true", PGC_POSTMASTER, PGC_S_ARGV);
526                                 break;
527
528                         case 'T':
529
530                                 /*
531                                  * In the event that some backend dumps core, send SIGSTOP,
532                                  * rather than SIGQUIT, to all its peers.  This lets the wily
533                                  * post_hacker collect core dumps from everyone.
534                                  */
535                                 SendStop = true;
536                                 break;
537
538                         case 't':
539                                 {
540                                         const char *tmp = get_stats_option_name(optarg);
541
542                                         if (tmp)
543                                         {
544                                                 SetConfigOption(tmp, "true", PGC_POSTMASTER, PGC_S_ARGV);
545                                         }
546                                         else
547                                         {
548                                                 write_stderr("%s: invalid argument for option -t: \"%s\"\n",
549                                                                          progname, optarg);
550                                                 ExitPostmaster(1);
551                                         }
552                                         break;
553                                 }
554
555                         case 'W':
556                                 SetConfigOption("post_auth_delay", optarg, PGC_POSTMASTER, PGC_S_ARGV);
557                                 break;
558
559                         case 'c':
560                         case '-':
561                                 {
562                                         char       *name,
563                                                            *value;
564
565                                         ParseLongOption(optarg, &name, &value);
566                                         if (!value)
567                                         {
568                                                 if (opt == '-')
569                                                         ereport(ERROR,
570                                                                         (errcode(ERRCODE_SYNTAX_ERROR),
571                                                                          errmsg("--%s requires a value",
572                                                                                         optarg)));
573                                                 else
574                                                         ereport(ERROR,
575                                                                         (errcode(ERRCODE_SYNTAX_ERROR),
576                                                                          errmsg("-c %s requires a value",
577                                                                                         optarg)));
578                                         }
579
580                                         SetConfigOption(name, value, PGC_POSTMASTER, PGC_S_ARGV);
581                                         free(name);
582                                         if (value)
583                                                 free(value);
584                                         break;
585                                 }
586
587                         default:
588                                 write_stderr("Try \"%s --help\" for more information.\n",
589                                                          progname);
590                                 ExitPostmaster(1);
591                 }
592         }
593
594         /*
595          * Postmaster accepts no non-option switch arguments.
596          */
597         if (optind < argc)
598         {
599                 write_stderr("%s: invalid argument: \"%s\"\n",
600                                          progname, argv[optind]);
601                 write_stderr("Try \"%s --help\" for more information.\n",
602                                          progname);
603                 ExitPostmaster(1);
604         }
605
606 #ifdef EXEC_BACKEND
607         /* Locate executable backend before we change working directory */
608         if (find_other_exec(argv[0], "postgres", PG_VERSIONSTR,
609                                                 postgres_exec_path) < 0)
610                 ereport(FATAL,
611                                 (errmsg("%s: could not locate matching postgres executable",
612                                                 progname)));
613 #endif
614
615         /*
616          * Locate the proper configuration files and data directory, and read
617          * postgresql.conf for the first time.
618          */
619         if (!SelectConfigFiles(userDoption, progname))
620                 ExitPostmaster(2);
621
622         /* Verify that DataDir looks reasonable */
623         checkDataDir();
624
625         /* And switch working directory into it */
626         ChangeToDataDir();
627
628         /*
629          * Check for invalid combinations of GUC settings.
630          */
631         if (NBuffers < 2 * MaxBackends || NBuffers < 16)
632         {
633                 /*
634                  * Do not accept -B so small that backends are likely to starve for
635                  * lack of buffers.  The specific choices here are somewhat arbitrary.
636                  */
637                 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);
638                 ExitPostmaster(1);
639         }
640
641         if (ReservedBackends >= MaxBackends)
642         {
643                 write_stderr("%s: superuser_reserved_connections must be less than max_connections\n", progname);
644                 ExitPostmaster(1);
645         }
646
647         /*
648          * Other one-time internal sanity checks can go here, if they are fast.
649          * (Put any slow processing further down, after postmaster.pid creation.)
650          */
651         if (!CheckDateTokenTables())
652         {
653                 write_stderr("%s: invalid datetoken tables, please fix\n", progname);
654                 ExitPostmaster(1);
655         }
656
657         /*
658          * Now that we are done processing the postmaster arguments, reset
659          * getopt(3) library so that it will work correctly in subprocesses.
660          */
661         optind = 1;
662 #ifdef HAVE_INT_OPTRESET
663         optreset = 1;                           /* some systems need this too */
664 #endif
665
666         /* For debugging: display postmaster environment */
667         {
668                 extern char **environ;
669                 char      **p;
670
671                 ereport(DEBUG3,
672                                 (errmsg_internal("%s: PostmasterMain: initial environ dump:",
673                                                                  progname)));
674                 ereport(DEBUG3,
675                          (errmsg_internal("-----------------------------------------")));
676                 for (p = environ; *p; ++p)
677                         ereport(DEBUG3,
678                                         (errmsg_internal("\t%s", *p)));
679                 ereport(DEBUG3,
680                          (errmsg_internal("-----------------------------------------")));
681         }
682
683         /*
684          * Fork away from controlling terminal, if -S specified.
685          *
686          * Must do this before we grab any interlock files, else the interlocks
687          * will show the wrong PID.
688          */
689         if (SilentMode)
690                 pmdaemonize();
691
692         /*
693          * Create lockfile for data directory.
694          *
695          * We want to do this before we try to grab the input sockets, because the
696          * data directory interlock is more reliable than the socket-file
697          * interlock (thanks to whoever decided to put socket files in /tmp :-().
698          * For the same reason, it's best to grab the TCP socket(s) before the
699          * Unix socket.
700          */
701         CreateDataDirLockFile(true);
702
703         /*
704          * If timezone is not set, determine what the OS uses.  (In theory this
705          * should be done during GUC initialization, but because it can take as
706          * much as several seconds, we delay it until after we've created the
707          * postmaster.pid file.  This prevents problems with boot scripts that
708          * expect the pidfile to appear quickly.  Also, we avoid problems with
709          * trying to locate the timezone files too early in initialization.)
710          */
711         pg_timezone_initialize();
712
713         /*
714          * Likewise, init timezone_abbreviations if not already set.
715          */
716         pg_timezone_abbrev_initialize();
717
718         /*
719          * Initialize SSL library, if specified.
720          */
721 #ifdef USE_SSL
722         if (EnableSSL)
723                 secure_initialize();
724 #endif
725
726         /*
727          * process any libraries that should be preloaded at postmaster start
728          */
729         process_shared_preload_libraries();
730
731         /*
732          * Remove old temporary files.  At this point there can be no other
733          * Postgres processes running in this directory, so this should be safe.
734          */
735         RemovePgTempFiles();
736
737         /*
738          * Establish input sockets.
739          */
740         for (i = 0; i < MAXLISTEN; i++)
741                 ListenSocket[i] = -1;
742
743         if (ListenAddresses)
744         {
745                 char       *rawstring;
746                 List       *elemlist;
747                 ListCell   *l;
748                 int                     success = 0;
749
750                 /* Need a modifiable copy of ListenAddresses */
751                 rawstring = pstrdup(ListenAddresses);
752
753                 /* Parse string into list of identifiers */
754                 if (!SplitIdentifierString(rawstring, ',', &elemlist))
755                 {
756                         /* syntax error in list */
757                         ereport(FATAL,
758                                         (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
759                                          errmsg("invalid list syntax for \"listen_addresses\"")));
760                 }
761
762                 foreach(l, elemlist)
763                 {
764                         char       *curhost = (char *) lfirst(l);
765
766                         if (strcmp(curhost, "*") == 0)
767                                 status = StreamServerPort(AF_UNSPEC, NULL,
768                                                                                   (unsigned short) PostPortNumber,
769                                                                                   UnixSocketDir,
770                                                                                   ListenSocket, MAXLISTEN);
771                         else
772                                 status = StreamServerPort(AF_UNSPEC, curhost,
773                                                                                   (unsigned short) PostPortNumber,
774                                                                                   UnixSocketDir,
775                                                                                   ListenSocket, MAXLISTEN);
776                         if (status == STATUS_OK)
777                                 success++;
778                         else
779                                 ereport(WARNING,
780                                                 (errmsg("could not create listen socket for \"%s\"",
781                                                                 curhost)));
782                 }
783
784                 if (!success && list_length(elemlist))
785                         ereport(FATAL,
786                                         (errmsg("could not create any TCP/IP sockets")));
787
788                 list_free(elemlist);
789                 pfree(rawstring);
790         }
791
792 #ifdef USE_BONJOUR
793         /* Register for Bonjour only if we opened TCP socket(s) */
794         if (ListenSocket[0] != -1 && bonjour_name != NULL)
795         {
796                 DNSServiceRegistrationCreate(bonjour_name,
797                                                                          "_postgresql._tcp.",
798                                                                          "",
799                                                                          htons(PostPortNumber),
800                                                                          "",
801                                                                          (DNSServiceRegistrationReply) reg_reply,
802                                                                          NULL);
803         }
804 #endif
805
806 #ifdef HAVE_UNIX_SOCKETS
807         status = StreamServerPort(AF_UNIX, NULL,
808                                                           (unsigned short) PostPortNumber,
809                                                           UnixSocketDir,
810                                                           ListenSocket, MAXLISTEN);
811         if (status != STATUS_OK)
812                 ereport(WARNING,
813                                 (errmsg("could not create Unix-domain socket")));
814 #endif
815
816         /*
817          * check that we have some socket to listen on
818          */
819         if (ListenSocket[0] == -1)
820                 ereport(FATAL,
821                                 (errmsg("no socket created for listening")));
822
823         /*
824          * Set up shared memory and semaphores.
825          */
826         reset_shared(PostPortNumber);
827
828         /*
829          * Estimate number of openable files.  This must happen after setting up
830          * semaphores, because on some platforms semaphores count as open files.
831          */
832         set_max_safe_fds();
833
834         /*
835          * Load configuration files for client authentication.
836          */
837         load_hba();
838         load_ident();
839
840         /*
841          * Initialize the list of active backends.
842          */
843         BackendList = DLNewList();
844
845 #ifdef WIN32
846
847         /*
848          * Initialize the child pid/HANDLE arrays for signal handling.
849          */
850         win32_childPIDArray = (pid_t *)
851                 malloc(mul_size(NUM_BACKENDARRAY_ELEMS, sizeof(pid_t)));
852         win32_childHNDArray = (HANDLE *)
853                 malloc(mul_size(NUM_BACKENDARRAY_ELEMS, sizeof(HANDLE)));
854         if (!win32_childPIDArray || !win32_childHNDArray)
855                 ereport(FATAL,
856                                 (errcode(ERRCODE_OUT_OF_MEMORY),
857                                  errmsg("out of memory")));
858
859         /*
860          * Set up a handle that child processes can use to check whether the
861          * postmaster is still running.
862          */
863         if (DuplicateHandle(GetCurrentProcess(),
864                                                 GetCurrentProcess(),
865                                                 GetCurrentProcess(),
866                                                 &PostmasterHandle,
867                                                 0,
868                                                 TRUE,
869                                                 DUPLICATE_SAME_ACCESS) == 0)
870                 ereport(FATAL,
871                                 (errmsg_internal("could not duplicate postmaster handle: error code %d",
872                                                                  (int) GetLastError())));
873 #endif
874
875         /*
876          * Record postmaster options.  We delay this till now to avoid recording
877          * bogus options (eg, NBuffers too high for available memory).
878          */
879         if (!CreateOptsFile(argc, argv, my_exec_path))
880                 ExitPostmaster(1);
881
882 #ifdef EXEC_BACKEND
883         write_nondefault_variables(PGC_POSTMASTER);
884 #endif
885
886         /*
887          * Write the external PID file if requested
888          */
889         if (external_pid_file)
890         {
891                 FILE       *fpidfile = fopen(external_pid_file, "w");
892
893                 if (fpidfile)
894                 {
895                         fprintf(fpidfile, "%d\n", MyProcPid);
896                         fclose(fpidfile);
897                         /* Should we remove the pid file on postmaster exit? */
898                 }
899                 else
900                         write_stderr("%s: could not write external PID file \"%s\": %s\n",
901                                                  progname, external_pid_file, strerror(errno));
902         }
903
904         /*
905          * Set up signal handlers for the postmaster process.
906          *
907          * CAUTION: when changing this list, check for side-effects on the signal
908          * handling setup of child processes.  See tcop/postgres.c,
909          * bootstrap/bootstrap.c, postmaster/bgwriter.c, postmaster/autovacuum.c,
910          * postmaster/pgarch.c, postmaster/pgstat.c, and postmaster/syslogger.c.
911          */
912         pqinitmask();
913         PG_SETMASK(&BlockSig);
914
915         pqsignal(SIGHUP, SIGHUP_handler);       /* reread config file and have
916                                                                                  * children do same */
917         pqsignal(SIGINT, pmdie);        /* send SIGTERM and shut down */
918         pqsignal(SIGQUIT, pmdie);       /* send SIGQUIT and die */
919         pqsignal(SIGTERM, pmdie);       /* wait for children and shut down */
920         pqsignal(SIGALRM, SIG_IGN); /* ignored */
921         pqsignal(SIGPIPE, SIG_IGN); /* ignored */
922         pqsignal(SIGUSR1, sigusr1_handler); /* message from child process */
923         pqsignal(SIGUSR2, dummy_handler);       /* unused, reserve for children */
924         pqsignal(SIGCHLD, reaper);      /* handle child termination */
925         pqsignal(SIGTTIN, SIG_IGN); /* ignored */
926         pqsignal(SIGTTOU, SIG_IGN); /* ignored */
927         /* ignore SIGXFSZ, so that ulimit violations work like disk full */
928 #ifdef SIGXFSZ
929         pqsignal(SIGXFSZ, SIG_IGN); /* ignored */
930 #endif
931
932         /*
933          * If enabled, start up syslogger collection subprocess
934          */
935         SysLoggerPID = SysLogger_Start();
936
937         /*
938          * Reset whereToSendOutput from DestDebug (its starting state) to
939          * DestNone. This stops ereport from sending log messages to stderr unless
940          * Log_destination permits.  We don't do this until the postmaster is
941          * fully launched, since startup failures may as well be reported to
942          * stderr.
943          */
944         whereToSendOutput = DestNone;
945
946         /*
947          * Initialize stats collection subsystem (this does NOT start the
948          * collector process!)
949          */
950         pgstat_init();
951
952         /*
953          * Initialize the autovacuum subsystem (again, no process start yet)
954          */
955         autovac_init();
956
957         /*
958          * Remember postmaster startup time
959          */
960         PgStartTime = GetCurrentTimestamp();
961
962         /*
963          * We're ready to rock and roll...
964          */
965         StartupPID = StartupDataBase();
966
967         status = ServerLoop();
968
969         /*
970          * ServerLoop probably shouldn't ever return, but if it does, close down.
971          */
972         ExitPostmaster(status != STATUS_OK);
973
974         return 0;                                       /* not reached */
975 }
976
977
978 /*
979  * Validate the proposed data directory
980  */
981 static void
982 checkDataDir(void)
983 {
984         char            path[MAXPGPATH];
985         FILE       *fp;
986         struct stat stat_buf;
987
988         Assert(DataDir);
989
990         if (stat(DataDir, &stat_buf) != 0)
991         {
992                 if (errno == ENOENT)
993                         ereport(FATAL,
994                                         (errcode_for_file_access(),
995                                          errmsg("data directory \"%s\" does not exist",
996                                                         DataDir)));
997                 else
998                         ereport(FATAL,
999                                         (errcode_for_file_access(),
1000                                  errmsg("could not read permissions of directory \"%s\": %m",
1001                                                 DataDir)));
1002         }
1003
1004         /*
1005          * Check that the directory belongs to my userid; if not, reject.
1006          *
1007          * This check is an essential part of the interlock that prevents two
1008          * postmasters from starting in the same directory (see CreateLockFile()).
1009          * Do not remove or weaken it.
1010          *
1011          * XXX can we safely enable this check on Windows?
1012          */
1013 #if !defined(WIN32) && !defined(__CYGWIN__)
1014         if (stat_buf.st_uid != geteuid())
1015                 ereport(FATAL,
1016                                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1017                                  errmsg("data directory \"%s\" has wrong ownership",
1018                                                 DataDir),
1019                                  errhint("The server must be started by the user that owns the data directory.")));
1020 #endif
1021
1022         /*
1023          * Check if the directory has group or world access.  If so, reject.
1024          *
1025          * It would be possible to allow weaker constraints (for example, allow
1026          * group access) but we cannot make a general assumption that that is
1027          * okay; for example there are platforms where nearly all users
1028          * customarily belong to the same group.  Perhaps this test should be
1029          * configurable.
1030          *
1031          * XXX temporarily suppress check when on Windows, because there may not
1032          * be proper support for Unix-y file permissions.  Need to think of a
1033          * reasonable check to apply on Windows.
1034          */
1035 #if !defined(WIN32) && !defined(__CYGWIN__)
1036         if (stat_buf.st_mode & (S_IRWXG | S_IRWXO))
1037                 ereport(FATAL,
1038                                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1039                                  errmsg("data directory \"%s\" has group or world access",
1040                                                 DataDir),
1041                                  errdetail("Permissions should be u=rwx (0700).")));
1042 #endif
1043
1044         /* Look for PG_VERSION before looking for pg_control */
1045         ValidatePgVersion(DataDir);
1046
1047         snprintf(path, sizeof(path), "%s/global/pg_control", DataDir);
1048
1049         fp = AllocateFile(path, PG_BINARY_R);
1050         if (fp == NULL)
1051         {
1052                 write_stderr("%s: could not find the database system\n"
1053                                          "Expected to find it in the directory \"%s\",\n"
1054                                          "but could not open file \"%s\": %s\n",
1055                                          progname, DataDir, path, strerror(errno));
1056                 ExitPostmaster(2);
1057         }
1058         FreeFile(fp);
1059 }
1060
1061
1062 #ifdef USE_BONJOUR
1063
1064 /*
1065  * empty callback function for DNSServiceRegistrationCreate()
1066  */
1067 static void
1068 reg_reply(DNSServiceRegistrationReplyErrorType errorCode, void *context)
1069 {
1070
1071 }
1072 #endif   /* USE_BONJOUR */
1073
1074
1075 /*
1076  * Fork away from the controlling terminal (-S option)
1077  */
1078 static void
1079 pmdaemonize(void)
1080 {
1081 #ifndef WIN32
1082         int                     i;
1083         pid_t           pid;
1084
1085         pid = fork_process();
1086         if (pid == (pid_t) -1)
1087         {
1088                 write_stderr("%s: could not fork background process: %s\n",
1089                                          progname, strerror(errno));
1090                 ExitPostmaster(1);
1091         }
1092         else if (pid)
1093         {                                                       /* parent */
1094                 /* Parent should just exit, without doing any atexit cleanup */
1095                 _exit(0);
1096         }
1097
1098         MyProcPid = PostmasterPid = getpid();           /* reset PID vars to child */
1099
1100 /* GH: If there's no setsid(), we hopefully don't need silent mode.
1101  * Until there's a better solution.
1102  */
1103 #ifdef HAVE_SETSID
1104         if (setsid() < 0)
1105         {
1106                 write_stderr("%s: could not dissociate from controlling TTY: %s\n",
1107                                          progname, strerror(errno));
1108                 ExitPostmaster(1);
1109         }
1110 #endif
1111         i = open(NULL_DEV, O_RDWR, 0);
1112         dup2(i, 0);
1113         dup2(i, 1);
1114         dup2(i, 2);
1115         close(i);
1116 #else                                                   /* WIN32 */
1117         /* not supported */
1118         elog(FATAL, "SilentMode not supported under WIN32");
1119 #endif   /* WIN32 */
1120 }
1121
1122
1123 /*
1124  * Main idle loop of postmaster
1125  */
1126 static int
1127 ServerLoop(void)
1128 {
1129         fd_set          readmask;
1130         int                     nSockets;
1131         time_t          now,
1132                                 last_touch_time;
1133         struct timeval earlier,
1134                                 later;
1135
1136         gettimeofday(&earlier, NULL);
1137         last_touch_time = time(NULL);
1138
1139         nSockets = initMasks(&readmask);
1140
1141         for (;;)
1142         {
1143                 Port       *port;
1144                 fd_set          rmask;
1145                 struct timeval timeout;
1146                 int                     selres;
1147                 int                     i;
1148
1149                 /*
1150                  * Wait for something to happen.
1151                  *
1152                  * We wait at most one minute, to ensure that the other background
1153                  * tasks handled below get done even when no requests are arriving.
1154                  */
1155                 memcpy((char *) &rmask, (char *) &readmask, sizeof(fd_set));
1156
1157                 timeout.tv_sec = 60;
1158                 timeout.tv_usec = 0;
1159
1160                 PG_SETMASK(&UnBlockSig);
1161
1162                 selres = select(nSockets, &rmask, NULL, NULL, &timeout);
1163
1164                 /*
1165                  * Block all signals until we wait again.  (This makes it safe for our
1166                  * signal handlers to do nontrivial work.)
1167                  */
1168                 PG_SETMASK(&BlockSig);
1169
1170                 if (selres < 0)
1171                 {
1172                         if (errno != EINTR && errno != EWOULDBLOCK)
1173                         {
1174                                 ereport(LOG,
1175                                                 (errcode_for_socket_access(),
1176                                                  errmsg("select() failed in postmaster: %m")));
1177                                 return STATUS_ERROR;
1178                         }
1179                 }
1180
1181                 /*
1182                  * New connection pending on any of our sockets? If so, fork a child
1183                  * process to deal with it.
1184                  */
1185                 if (selres > 0)
1186                 {
1187                         /*
1188                          * Select a random seed at the time of first receiving a request.
1189                          */
1190                         while (random_seed == 0)
1191                         {
1192                                 gettimeofday(&later, NULL);
1193
1194                                 /*
1195                                  * We are not sure how much precision is in tv_usec, so we
1196                                  * swap the high and low 16 bits of 'later' and XOR them with
1197                                  * 'earlier'. On the off chance that the result is 0, we loop
1198                                  * until it isn't.
1199                                  */
1200                                 random_seed = earlier.tv_usec ^
1201                                         ((later.tv_usec << 16) |
1202                                          ((later.tv_usec >> 16) & 0xffff));
1203                         }
1204
1205                         for (i = 0; i < MAXLISTEN; i++)
1206                         {
1207                                 if (ListenSocket[i] == -1)
1208                                         break;
1209                                 if (FD_ISSET(ListenSocket[i], &rmask))
1210                                 {
1211                                         port = ConnCreate(ListenSocket[i]);
1212                                         if (port)
1213                                         {
1214                                                 BackendStartup(port);
1215
1216                                                 /*
1217                                                  * We no longer need the open socket or port structure
1218                                                  * in this process
1219                                                  */
1220                                                 StreamClose(port->sock);
1221                                                 ConnFree(port);
1222                                         }
1223                                 }
1224                         }
1225                 }
1226
1227                 /* If we have lost the system logger, try to start a new one */
1228                 if (SysLoggerPID == 0 && Redirect_stderr)
1229                         SysLoggerPID = SysLogger_Start();
1230
1231                 /*
1232                  * If no background writer process is running, and we are not in a
1233                  * state that prevents it, start one.  It doesn't matter if this
1234                  * fails, we'll just try again later.
1235                  */
1236                 if (BgWriterPID == 0 && StartupPID == 0 && !FatalError)
1237                 {
1238                         BgWriterPID = StartBackgroundWriter();
1239                         /* If shutdown is pending, set it going */
1240                         if (Shutdown > NoShutdown && BgWriterPID != 0)
1241                                 signal_child(BgWriterPID, SIGUSR2);
1242                 }
1243
1244                 /* If we have lost the autovacuum launcher, try to start a new one */
1245                 if ((AutoVacuumingActive() || start_autovac_launcher) && AutoVacPID == 0 &&
1246                         StartupPID == 0 && !FatalError && Shutdown == NoShutdown)
1247                 {
1248                         AutoVacPID = StartAutoVacLauncher();
1249                         if (AutoVacPID != 0)
1250                                 start_autovac_launcher = false; /* signal successfully processed */
1251                 }
1252
1253                 /* If we have lost the archiver, try to start a new one */
1254                 if (XLogArchivingActive() && PgArchPID == 0 &&
1255                         StartupPID == 0 && !FatalError && Shutdown == NoShutdown)
1256                         PgArchPID = pgarch_start();
1257
1258                 /* If we have lost the stats collector, try to start a new one */
1259                 if (PgStatPID == 0 &&
1260                         StartupPID == 0 && !FatalError && Shutdown == NoShutdown)
1261                         PgStatPID = pgstat_start();
1262
1263                 /*
1264                  * Touch the socket and lock file every 58 minutes, to ensure that
1265                  * they are not removed by overzealous /tmp-cleaning tasks.  We assume
1266                  * no one runs cleaners with cutoff times of less than an hour ...
1267                  */
1268                 now = time(NULL);
1269                 if (now - last_touch_time >= 58 * SECS_PER_MINUTE)
1270                 {
1271                         TouchSocketFile();
1272                         TouchSocketLockFile();
1273                         last_touch_time = now;
1274                 }
1275         }
1276 }
1277
1278
1279 /*
1280  * Initialise the masks for select() for the ports we are listening on.
1281  * Return the number of sockets to listen on.
1282  */
1283 static int
1284 initMasks(fd_set *rmask)
1285 {
1286         int                     nsocks = -1;
1287         int                     i;
1288
1289         FD_ZERO(rmask);
1290
1291         for (i = 0; i < MAXLISTEN; i++)
1292         {
1293                 int                     fd = ListenSocket[i];
1294
1295                 if (fd == -1)
1296                         break;
1297                 FD_SET(fd, rmask);
1298                 if (fd > nsocks)
1299                         nsocks = fd;
1300         }
1301
1302         return nsocks + 1;
1303 }
1304
1305
1306 /*
1307  * Read the startup packet and do something according to it.
1308  *
1309  * Returns STATUS_OK or STATUS_ERROR, or might call ereport(FATAL) and
1310  * not return at all.
1311  *
1312  * (Note that ereport(FATAL) stuff is sent to the client, so only use it
1313  * if that's what you want.  Return STATUS_ERROR if you don't want to
1314  * send anything to the client, which would typically be appropriate
1315  * if we detect a communications failure.)
1316  */
1317 static int
1318 ProcessStartupPacket(Port *port, bool SSLdone)
1319 {
1320         int32           len;
1321         void       *buf;
1322         ProtocolVersion proto;
1323         MemoryContext oldcontext;
1324
1325         if (pq_getbytes((char *) &len, 4) == EOF)
1326         {
1327                 /*
1328                  * EOF after SSLdone probably means the client didn't like our
1329                  * response to NEGOTIATE_SSL_CODE.      That's not an error condition, so
1330                  * don't clutter the log with a complaint.
1331                  */
1332                 if (!SSLdone)
1333                         ereport(COMMERROR,
1334                                         (errcode(ERRCODE_PROTOCOL_VIOLATION),
1335                                          errmsg("incomplete startup packet")));
1336                 return STATUS_ERROR;
1337         }
1338
1339         len = ntohl(len);
1340         len -= 4;
1341
1342         if (len < (int32) sizeof(ProtocolVersion) ||
1343                 len > MAX_STARTUP_PACKET_LENGTH)
1344         {
1345                 ereport(COMMERROR,
1346                                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1347                                  errmsg("invalid length of startup packet")));
1348                 return STATUS_ERROR;
1349         }
1350
1351         /*
1352          * Allocate at least the size of an old-style startup packet, plus one
1353          * extra byte, and make sure all are zeroes.  This ensures we will have
1354          * null termination of all strings, in both fixed- and variable-length
1355          * packet layouts.
1356          */
1357         if (len <= (int32) sizeof(StartupPacket))
1358                 buf = palloc0(sizeof(StartupPacket) + 1);
1359         else
1360                 buf = palloc0(len + 1);
1361
1362         if (pq_getbytes(buf, len) == EOF)
1363         {
1364                 ereport(COMMERROR,
1365                                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1366                                  errmsg("incomplete startup packet")));
1367                 return STATUS_ERROR;
1368         }
1369
1370         /*
1371          * The first field is either a protocol version number or a special
1372          * request code.
1373          */
1374         port->proto = proto = ntohl(*((ProtocolVersion *) buf));
1375
1376         if (proto == CANCEL_REQUEST_CODE)
1377         {
1378                 processCancelRequest(port, buf);
1379                 return 127;                             /* XXX */
1380         }
1381
1382         if (proto == NEGOTIATE_SSL_CODE && !SSLdone)
1383         {
1384                 char            SSLok;
1385
1386 #ifdef USE_SSL
1387                 /* No SSL when disabled or on Unix sockets */
1388                 if (!EnableSSL || IS_AF_UNIX(port->laddr.addr.ss_family))
1389                         SSLok = 'N';
1390                 else
1391                         SSLok = 'S';            /* Support for SSL */
1392 #else
1393                 SSLok = 'N';                    /* No support for SSL */
1394 #endif
1395
1396 retry1:
1397                 if (send(port->sock, &SSLok, 1, 0) != 1)
1398                 {
1399                         if (errno == EINTR)
1400                                 goto retry1;    /* if interrupted, just retry */
1401                         ereport(COMMERROR,
1402                                         (errcode_for_socket_access(),
1403                                          errmsg("failed to send SSL negotiation response: %m")));
1404                         return STATUS_ERROR;    /* close the connection */
1405                 }
1406
1407 #ifdef USE_SSL
1408                 if (SSLok == 'S' && secure_open_server(port) == -1)
1409                         return STATUS_ERROR;
1410 #endif
1411                 /* regular startup packet, cancel, etc packet should follow... */
1412                 /* but not another SSL negotiation request */
1413                 return ProcessStartupPacket(port, true);
1414         }
1415
1416         /* Could add additional special packet types here */
1417
1418         /*
1419          * Set FrontendProtocol now so that ereport() knows what format to send if
1420          * we fail during startup.
1421          */
1422         FrontendProtocol = proto;
1423
1424         /* Check we can handle the protocol the frontend is using. */
1425
1426         if (PG_PROTOCOL_MAJOR(proto) < PG_PROTOCOL_MAJOR(PG_PROTOCOL_EARLIEST) ||
1427                 PG_PROTOCOL_MAJOR(proto) > PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST) ||
1428                 (PG_PROTOCOL_MAJOR(proto) == PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST) &&
1429                  PG_PROTOCOL_MINOR(proto) > PG_PROTOCOL_MINOR(PG_PROTOCOL_LATEST)))
1430                 ereport(FATAL,
1431                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1432                                  errmsg("unsupported frontend protocol %u.%u: server supports %u.0 to %u.%u",
1433                                                 PG_PROTOCOL_MAJOR(proto), PG_PROTOCOL_MINOR(proto),
1434                                                 PG_PROTOCOL_MAJOR(PG_PROTOCOL_EARLIEST),
1435                                                 PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST),
1436                                                 PG_PROTOCOL_MINOR(PG_PROTOCOL_LATEST))));
1437
1438         /*
1439          * Now fetch parameters out of startup packet and save them into the Port
1440          * structure.  All data structures attached to the Port struct must be
1441          * allocated in TopMemoryContext so that they won't disappear when we pass
1442          * them to PostgresMain (see BackendRun).  We need not worry about leaking
1443          * this storage on failure, since we aren't in the postmaster process
1444          * anymore.
1445          */
1446         oldcontext = MemoryContextSwitchTo(TopMemoryContext);
1447
1448         if (PG_PROTOCOL_MAJOR(proto) >= 3)
1449         {
1450                 int32           offset = sizeof(ProtocolVersion);
1451
1452                 /*
1453                  * Scan packet body for name/option pairs.      We can assume any string
1454                  * beginning within the packet body is null-terminated, thanks to
1455                  * zeroing extra byte above.
1456                  */
1457                 port->guc_options = NIL;
1458
1459                 while (offset < len)
1460                 {
1461                         char       *nameptr = ((char *) buf) + offset;
1462                         int32           valoffset;
1463                         char       *valptr;
1464
1465                         if (*nameptr == '\0')
1466                                 break;                  /* found packet terminator */
1467                         valoffset = offset + strlen(nameptr) + 1;
1468                         if (valoffset >= len)
1469                                 break;                  /* missing value, will complain below */
1470                         valptr = ((char *) buf) + valoffset;
1471
1472                         if (strcmp(nameptr, "database") == 0)
1473                                 port->database_name = pstrdup(valptr);
1474                         else if (strcmp(nameptr, "user") == 0)
1475                                 port->user_name = pstrdup(valptr);
1476                         else if (strcmp(nameptr, "options") == 0)
1477                                 port->cmdline_options = pstrdup(valptr);
1478                         else
1479                         {
1480                                 /* Assume it's a generic GUC option */
1481                                 port->guc_options = lappend(port->guc_options,
1482                                                                                         pstrdup(nameptr));
1483                                 port->guc_options = lappend(port->guc_options,
1484                                                                                         pstrdup(valptr));
1485                         }
1486                         offset = valoffset + strlen(valptr) + 1;
1487                 }
1488
1489                 /*
1490                  * If we didn't find a packet terminator exactly at the end of the
1491                  * given packet length, complain.
1492                  */
1493                 if (offset != len - 1)
1494                         ereport(FATAL,
1495                                         (errcode(ERRCODE_PROTOCOL_VIOLATION),
1496                                          errmsg("invalid startup packet layout: expected terminator as last byte")));
1497         }
1498         else
1499         {
1500                 /*
1501                  * Get the parameters from the old-style, fixed-width-fields startup
1502                  * packet as C strings.  The packet destination was cleared first so a
1503                  * short packet has zeros silently added.  We have to be prepared to
1504                  * truncate the pstrdup result for oversize fields, though.
1505                  */
1506                 StartupPacket *packet = (StartupPacket *) buf;
1507
1508                 port->database_name = pstrdup(packet->database);
1509                 if (strlen(port->database_name) > sizeof(packet->database))
1510                         port->database_name[sizeof(packet->database)] = '\0';
1511                 port->user_name = pstrdup(packet->user);
1512                 if (strlen(port->user_name) > sizeof(packet->user))
1513                         port->user_name[sizeof(packet->user)] = '\0';
1514                 port->cmdline_options = pstrdup(packet->options);
1515                 if (strlen(port->cmdline_options) > sizeof(packet->options))
1516                         port->cmdline_options[sizeof(packet->options)] = '\0';
1517                 port->guc_options = NIL;
1518         }
1519
1520         /* Check a user name was given. */
1521         if (port->user_name == NULL || port->user_name[0] == '\0')
1522                 ereport(FATAL,
1523                                 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
1524                          errmsg("no PostgreSQL user name specified in startup packet")));
1525
1526         /* The database defaults to the user name. */
1527         if (port->database_name == NULL || port->database_name[0] == '\0')
1528                 port->database_name = pstrdup(port->user_name);
1529
1530         if (Db_user_namespace)
1531         {
1532                 /*
1533                  * If user@, it is a global user, remove '@'. We only want to do this
1534                  * if there is an '@' at the end and no earlier in the user string or
1535                  * they may fake as a local user of another database attaching to this
1536                  * database.
1537                  */
1538                 if (strchr(port->user_name, '@') ==
1539                         port->user_name + strlen(port->user_name) - 1)
1540                         *strchr(port->user_name, '@') = '\0';
1541                 else
1542                 {
1543                         /* Append '@' and dbname */
1544                         char       *db_user;
1545
1546                         db_user = palloc(strlen(port->user_name) +
1547                                                          strlen(port->database_name) + 2);
1548                         sprintf(db_user, "%s@%s", port->user_name, port->database_name);
1549                         port->user_name = db_user;
1550                 }
1551         }
1552
1553         /*
1554          * Truncate given database and user names to length of a Postgres name.
1555          * This avoids lookup failures when overlength names are given.
1556          */
1557         if (strlen(port->database_name) >= NAMEDATALEN)
1558                 port->database_name[NAMEDATALEN - 1] = '\0';
1559         if (strlen(port->user_name) >= NAMEDATALEN)
1560                 port->user_name[NAMEDATALEN - 1] = '\0';
1561
1562         /*
1563          * Done putting stuff in TopMemoryContext.
1564          */
1565         MemoryContextSwitchTo(oldcontext);
1566
1567         /*
1568          * If we're going to reject the connection due to database state, say so
1569          * now instead of wasting cycles on an authentication exchange. (This also
1570          * allows a pg_ping utility to be written.)
1571          */
1572         switch (port->canAcceptConnections)
1573         {
1574                 case CAC_STARTUP:
1575                         ereport(FATAL,
1576                                         (errcode(ERRCODE_CANNOT_CONNECT_NOW),
1577                                          errmsg("the database system is starting up")));
1578                         break;
1579                 case CAC_SHUTDOWN:
1580                         ereport(FATAL,
1581                                         (errcode(ERRCODE_CANNOT_CONNECT_NOW),
1582                                          errmsg("the database system is shutting down")));
1583                         break;
1584                 case CAC_RECOVERY:
1585                         ereport(FATAL,
1586                                         (errcode(ERRCODE_CANNOT_CONNECT_NOW),
1587                                          errmsg("the database system is in recovery mode")));
1588                         break;
1589                 case CAC_TOOMANY:
1590                         ereport(FATAL,
1591                                         (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
1592                                          errmsg("sorry, too many clients already")));
1593                         break;
1594                 case CAC_OK:
1595                 default:
1596                         break;
1597         }
1598
1599         return STATUS_OK;
1600 }
1601
1602
1603 /*
1604  * The client has sent a cancel request packet, not a normal
1605  * start-a-new-connection packet.  Perform the necessary processing.
1606  * Nothing is sent back to the client.
1607  */
1608 static void
1609 processCancelRequest(Port *port, void *pkt)
1610 {
1611         CancelRequestPacket *canc = (CancelRequestPacket *) pkt;
1612         int                     backendPID;
1613         long            cancelAuthCode;
1614         Backend    *bp;
1615
1616 #ifndef EXEC_BACKEND
1617         Dlelem     *curr;
1618 #else
1619         int                     i;
1620 #endif
1621
1622         backendPID = (int) ntohl(canc->backendPID);
1623         cancelAuthCode = (long) ntohl(canc->cancelAuthCode);
1624
1625         /*
1626          * See if we have a matching backend.  In the EXEC_BACKEND case, we can no
1627          * longer access the postmaster's own backend list, and must rely on the
1628          * duplicate array in shared memory.
1629          */
1630 #ifndef EXEC_BACKEND
1631         for (curr = DLGetHead(BackendList); curr; curr = DLGetSucc(curr))
1632         {
1633                 bp = (Backend *) DLE_VAL(curr);
1634 #else
1635         for (i = 0; i < NUM_BACKENDARRAY_ELEMS; i++)
1636         {
1637                 bp = (Backend *) &ShmemBackendArray[i];
1638 #endif
1639                 if (bp->pid == backendPID)
1640                 {
1641                         if (bp->cancel_key == cancelAuthCode)
1642                         {
1643                                 /* Found a match; signal that backend to cancel current op */
1644                                 ereport(DEBUG2,
1645                                                 (errmsg_internal("processing cancel request: sending SIGINT to process %d",
1646                                                                                  backendPID)));
1647                                 signal_child(bp->pid, SIGINT);
1648                         }
1649                         else
1650                                 /* Right PID, wrong key: no way, Jose */
1651                                 ereport(DEBUG2,
1652                                  (errmsg_internal("bad key in cancel request for process %d",
1653                                                                   backendPID)));
1654                         return;
1655                 }
1656         }
1657
1658         /* No matching backend */
1659         ereport(DEBUG2,
1660                         (errmsg_internal("bad pid in cancel request for process %d",
1661                                                          backendPID)));
1662 }
1663
1664 /*
1665  * canAcceptConnections --- check to see if database state allows connections.
1666  */
1667 static enum CAC_state
1668 canAcceptConnections(void)
1669 {
1670         /* Can't start backends when in startup/shutdown/recovery state. */
1671         if (Shutdown > NoShutdown)
1672                 return CAC_SHUTDOWN;
1673         if (StartupPID)
1674                 return CAC_STARTUP;
1675         if (FatalError)
1676                 return CAC_RECOVERY;
1677
1678         /*
1679          * Don't start too many children.
1680          *
1681          * We allow more connections than we can have backends here because some
1682          * might still be authenticating; they might fail auth, or some existing
1683          * backend might exit before the auth cycle is completed. The exact
1684          * MaxBackends limit is enforced when a new backend tries to join the
1685          * shared-inval backend array.
1686          */
1687         if (CountChildren() >= 2 * MaxBackends)
1688                 return CAC_TOOMANY;
1689
1690         return CAC_OK;
1691 }
1692
1693
1694 /*
1695  * ConnCreate -- create a local connection data structure
1696  */
1697 static Port *
1698 ConnCreate(int serverFd)
1699 {
1700         Port       *port;
1701
1702         if (!(port = (Port *) calloc(1, sizeof(Port))))
1703         {
1704                 ereport(LOG,
1705                                 (errcode(ERRCODE_OUT_OF_MEMORY),
1706                                  errmsg("out of memory")));
1707                 ExitPostmaster(1);
1708         }
1709
1710         if (StreamConnection(serverFd, port) != STATUS_OK)
1711         {
1712                 if (port->sock >= 0)
1713                         StreamClose(port->sock);
1714                 ConnFree(port);
1715                 port = NULL;
1716         }
1717         else
1718         {
1719                 /*
1720                  * Precompute password salt values to use for this connection. It's
1721                  * slightly annoying to do this long in advance of knowing whether
1722                  * we'll need 'em or not, but we must do the random() calls before we
1723                  * fork, not after.  Else the postmaster's random sequence won't get
1724                  * advanced, and all backends would end up using the same salt...
1725                  */
1726                 RandomSalt(port->cryptSalt, port->md5Salt);
1727         }
1728
1729         return port;
1730 }
1731
1732
1733 /*
1734  * ConnFree -- free a local connection data structure
1735  */
1736 static void
1737 ConnFree(Port *conn)
1738 {
1739 #ifdef USE_SSL
1740         secure_close(conn);
1741 #endif
1742         free(conn);
1743 }
1744
1745
1746 /*
1747  * ClosePostmasterPorts -- close all the postmaster's open sockets
1748  *
1749  * This is called during child process startup to release file descriptors
1750  * that are not needed by that child process.  The postmaster still has
1751  * them open, of course.
1752  *
1753  * Note: we pass am_syslogger as a boolean because we don't want to set
1754  * the global variable yet when this is called.
1755  */
1756 void
1757 ClosePostmasterPorts(bool am_syslogger)
1758 {
1759         int                     i;
1760
1761         /* Close the listen sockets */
1762         for (i = 0; i < MAXLISTEN; i++)
1763         {
1764                 if (ListenSocket[i] != -1)
1765                 {
1766                         StreamClose(ListenSocket[i]);
1767                         ListenSocket[i] = -1;
1768                 }
1769         }
1770
1771         /* If using syslogger, close the read side of the pipe */
1772         if (!am_syslogger)
1773         {
1774 #ifndef WIN32
1775                 if (syslogPipe[0] >= 0)
1776                         close(syslogPipe[0]);
1777                 syslogPipe[0] = -1;
1778 #else
1779                 if (syslogPipe[0])
1780                         CloseHandle(syslogPipe[0]);
1781                 syslogPipe[0] = 0;
1782 #endif
1783         }
1784 }
1785
1786
1787 /*
1788  * reset_shared -- reset shared memory and semaphores
1789  */
1790 static void
1791 reset_shared(int port)
1792 {
1793         /*
1794          * Create or re-create shared memory and semaphores.
1795          *
1796          * Note: in each "cycle of life" we will normally assign the same IPC keys
1797          * (if using SysV shmem and/or semas), since the port number is used to
1798          * determine IPC keys.  This helps ensure that we will clean up dead IPC
1799          * objects if the postmaster crashes and is restarted.
1800          */
1801         CreateSharedMemoryAndSemaphores(false, port);
1802 }
1803
1804
1805 /*
1806  * SIGHUP -- reread config files, and tell children to do same
1807  */
1808 static void
1809 SIGHUP_handler(SIGNAL_ARGS)
1810 {
1811         int                     save_errno = errno;
1812
1813         PG_SETMASK(&BlockSig);
1814
1815         if (Shutdown <= SmartShutdown)
1816         {
1817                 ereport(LOG,
1818                                 (errmsg("received SIGHUP, reloading configuration files")));
1819                 ProcessConfigFile(PGC_SIGHUP);
1820                 SignalChildren(SIGHUP);
1821                 if (BgWriterPID != 0)
1822                         signal_child(BgWriterPID, SIGHUP);
1823                 if (AutoVacPID != 0)
1824                         signal_child(AutoVacPID, SIGHUP);
1825                 if (PgArchPID != 0)
1826                         signal_child(PgArchPID, SIGHUP);
1827                 if (SysLoggerPID != 0)
1828                         signal_child(SysLoggerPID, SIGHUP);
1829                 /* PgStatPID does not currently need SIGHUP */
1830
1831                 /* Reload authentication config files too */
1832                 load_hba();
1833                 load_ident();
1834
1835 #ifdef EXEC_BACKEND
1836                 /* Update the starting-point file for future children */
1837                 write_nondefault_variables(PGC_SIGHUP);
1838 #endif
1839         }
1840
1841         PG_SETMASK(&UnBlockSig);
1842
1843         errno = save_errno;
1844 }
1845
1846
1847 /*
1848  * pmdie -- signal handler for processing various postmaster signals.
1849  */
1850 static void
1851 pmdie(SIGNAL_ARGS)
1852 {
1853         int                     save_errno = errno;
1854
1855         PG_SETMASK(&BlockSig);
1856
1857         ereport(DEBUG2,
1858                         (errmsg_internal("postmaster received signal %d",
1859                                                          postgres_signal_arg)));
1860
1861         switch (postgres_signal_arg)
1862         {
1863                 case SIGTERM:
1864
1865                         /*
1866                          * Smart Shutdown:
1867                          *
1868                          * Wait for children to end their work, then shut down.
1869                          */
1870                         if (Shutdown >= SmartShutdown)
1871                                 break;
1872                         Shutdown = SmartShutdown;
1873                         ereport(LOG,
1874                                         (errmsg("received smart shutdown request")));
1875
1876                         /* autovacuum workers are shut down immediately */
1877                         if (DLGetHead(BackendList))
1878                                 SignalSomeChildren(SIGINT, true);
1879
1880                         if (DLGetHead(BackendList))
1881                                 break;                  /* let reaper() handle this */
1882
1883                         /*
1884                          * No children left. Begin shutdown of data base system.
1885                          */
1886                         if (StartupPID != 0 || FatalError)
1887                                 break;                  /* let reaper() handle this */
1888                         /* Start the bgwriter if not running */
1889                         if (BgWriterPID == 0)
1890                                 BgWriterPID = StartBackgroundWriter();
1891                         /* And tell it to shut down */
1892                         if (BgWriterPID != 0)
1893                                 signal_child(BgWriterPID, SIGUSR2);
1894                         /* Tell pgarch to shut down too; nothing left for it to do */
1895                         if (PgArchPID != 0)
1896                                 signal_child(PgArchPID, SIGQUIT);
1897                         /* Tell pgstat to shut down too; nothing left for it to do */
1898                         if (PgStatPID != 0)
1899                                 signal_child(PgStatPID, SIGQUIT);
1900                         /* Tell autovac launcher to shut down too */
1901                         if (AutoVacPID != 0)
1902                                 signal_child(AutoVacPID, SIGTERM);
1903                         break;
1904
1905                 case SIGINT:
1906
1907                         /*
1908                          * Fast Shutdown:
1909                          *
1910                          * Abort all children with SIGTERM (rollback active transactions
1911                          * and exit) and shut down when they are gone.
1912                          */
1913                         if (Shutdown >= FastShutdown)
1914                                 break;
1915                         Shutdown = FastShutdown;
1916                         ereport(LOG,
1917                                         (errmsg("received fast shutdown request")));
1918
1919                         if (DLGetHead(BackendList))
1920                         {
1921                                 if (!FatalError)
1922                                 {
1923                                         ereport(LOG,
1924                                                         (errmsg("aborting any active transactions")));
1925                                         SignalChildren(SIGTERM);
1926                                         /* reaper() does the rest */
1927                                 }
1928                                 break;
1929                         }
1930
1931                         /*
1932                          * No children left. Begin shutdown of data base system.
1933                          *
1934                          * Note: if we previously got SIGTERM then we may send SIGUSR2 to
1935                          * the bgwriter a second time here.  This should be harmless.
1936                          */
1937                         if (StartupPID != 0)
1938                         {
1939                                 signal_child(StartupPID, SIGTERM);
1940                                 break;                  /* let reaper() do the rest */
1941                         }
1942                         if (FatalError)
1943                                 break;                  /* let reaper() handle this case */
1944                         /* Start the bgwriter if not running */
1945                         if (BgWriterPID == 0)
1946                                 BgWriterPID = StartBackgroundWriter();
1947                         /* And tell it to shut down */
1948                         if (BgWriterPID != 0)
1949                                 signal_child(BgWriterPID, SIGUSR2);
1950                         /* Tell pgarch to shut down too; nothing left for it to do */
1951                         if (PgArchPID != 0)
1952                                 signal_child(PgArchPID, SIGQUIT);
1953                         /* Tell pgstat to shut down too; nothing left for it to do */
1954                         if (PgStatPID != 0)
1955                                 signal_child(PgStatPID, SIGQUIT);
1956                         /* Tell autovac launcher to shut down too */
1957                         if (AutoVacPID != 0)
1958                                 signal_child(AutoVacPID, SIGTERM);
1959                         break;
1960
1961                 case SIGQUIT:
1962
1963                         /*
1964                          * Immediate Shutdown:
1965                          *
1966                          * abort all children with SIGQUIT and exit without attempt to
1967                          * properly shut down data base system.
1968                          */
1969                         ereport(LOG,
1970                                         (errmsg("received immediate shutdown request")));
1971                         if (StartupPID != 0)
1972                                 signal_child(StartupPID, SIGQUIT);
1973                         if (BgWriterPID != 0)
1974                                 signal_child(BgWriterPID, SIGQUIT);
1975                         if (AutoVacPID != 0)
1976                                 signal_child(AutoVacPID, SIGQUIT);
1977                         if (PgArchPID != 0)
1978                                 signal_child(PgArchPID, SIGQUIT);
1979                         if (PgStatPID != 0)
1980                                 signal_child(PgStatPID, SIGQUIT);
1981                         if (DLGetHead(BackendList))
1982                                 SignalChildren(SIGQUIT);
1983                         ExitPostmaster(0);
1984                         break;
1985         }
1986
1987         PG_SETMASK(&UnBlockSig);
1988
1989         errno = save_errno;
1990 }
1991
1992 /*
1993  * Reaper -- signal handler to cleanup after a backend (child) dies.
1994  */
1995 static void
1996 reaper(SIGNAL_ARGS)
1997 {
1998         int                     save_errno = errno;
1999
2000 #ifdef HAVE_WAITPID
2001         int                     status;                 /* backend exit status */
2002 #else
2003 #ifndef WIN32
2004         union wait      status;                 /* backend exit status */
2005 #endif
2006 #endif
2007         int                     exitstatus;
2008         int                     pid;                    /* process id of dead backend */
2009
2010         PG_SETMASK(&BlockSig);
2011
2012         ereport(DEBUG4,
2013                         (errmsg_internal("reaping dead processes")));
2014 #ifdef HAVE_WAITPID
2015         while ((pid = waitpid(-1, &status, WNOHANG)) > 0)
2016         {
2017                 exitstatus = status;
2018 #else
2019 #ifndef WIN32
2020         while ((pid = wait3(&status, WNOHANG, NULL)) > 0)
2021         {
2022                 exitstatus = status.w_status;
2023 #else
2024         while ((pid = win32_waitpid(&exitstatus)) > 0)
2025         {
2026                 /*
2027                  * We need to do this here, and not in CleanupBackend, since this is
2028                  * to be called on all children when we are done with them. Could move
2029                  * to LogChildExit, but that seems like asking for future trouble...
2030                  */
2031                 win32_RemoveChild(pid);
2032 #endif   /* WIN32 */
2033 #endif   /* HAVE_WAITPID */
2034
2035                 /*
2036                  * Check if this child was a startup process.
2037                  */
2038                 if (StartupPID != 0 && pid == StartupPID)
2039                 {
2040                         StartupPID = 0;
2041                         /* Note: FATAL exit of startup is treated as catastrophic */
2042                         if (!EXIT_STATUS_0(exitstatus))
2043                         {
2044                                 LogChildExit(LOG, _("startup process"),
2045                                                          pid, exitstatus);
2046                                 ereport(LOG,
2047                                 (errmsg("aborting startup due to startup process failure")));
2048                                 ExitPostmaster(1);
2049                         }
2050
2051                         /*
2052                          * Startup succeeded - we are done with system startup or
2053                          * recovery.
2054                          */
2055                         FatalError = false;
2056
2057                         /*
2058                          * Load the flat authorization file into postmaster's cache. The
2059                          * startup process has recomputed this from the database contents,
2060                          * so we wait till it finishes before loading it.
2061                          */
2062                         load_role();
2063
2064                         /*
2065                          * Crank up the background writer.      It doesn't matter if this
2066                          * fails, we'll just try again later.
2067                          */
2068                         Assert(BgWriterPID == 0);
2069                         BgWriterPID = StartBackgroundWriter();
2070
2071                         /*
2072                          * Go to shutdown mode if a shutdown request was pending.
2073                          * Otherwise, try to start the archiver, stats collector and
2074                          * autovacuum launcher.
2075                          */
2076                         if (Shutdown > NoShutdown && BgWriterPID != 0)
2077                                 signal_child(BgWriterPID, SIGUSR2);
2078                         else if (Shutdown == NoShutdown)
2079                         {
2080                                 if (XLogArchivingActive() && PgArchPID == 0)
2081                                         PgArchPID = pgarch_start();
2082                                 if (PgStatPID == 0)
2083                                         PgStatPID = pgstat_start();
2084                                 if (AutoVacuumingActive() && AutoVacPID == 0)
2085                                         AutoVacPID = StartAutoVacLauncher();
2086
2087                                 /* at this point we are really open for business */
2088                                 ereport(LOG,
2089                                                 (errmsg("database system is ready to accept connections")));
2090                         }
2091
2092                         continue;
2093                 }
2094
2095                 /*
2096                  * Was it the bgwriter?
2097                  */
2098                 if (BgWriterPID != 0 && pid == BgWriterPID)
2099                 {
2100                         BgWriterPID = 0;
2101                         if (EXIT_STATUS_0(exitstatus) &&
2102                                 Shutdown > NoShutdown && !FatalError &&
2103                                 !DLGetHead(BackendList) && AutoVacPID == 0)
2104                         {
2105                                 /*
2106                                  * Normal postmaster exit is here: we've seen normal exit of
2107                                  * the bgwriter after it's been told to shut down. We expect
2108                                  * that it wrote a shutdown checkpoint.  (If for some reason
2109                                  * it didn't, recovery will occur on next postmaster start.)
2110                                  *
2111                                  * Note: we do not wait around for exit of the archiver or
2112                                  * stats processes.  They've been sent SIGQUIT by this point,
2113                                  * and in any case contain logic to commit hara-kiri if they
2114                                  * notice the postmaster is gone.
2115                                  */
2116                                 ExitPostmaster(0);
2117                         }
2118
2119                         /*
2120                          * Any unexpected exit of the bgwriter (including FATAL exit)
2121                          * is treated as a crash.
2122                          */
2123                         HandleChildCrash(pid, exitstatus,
2124                                                          _("background writer process"));
2125
2126                         /*
2127                          * If the bgwriter crashed while trying to write the shutdown
2128                          * checkpoint, we may as well just stop here; any recovery
2129                          * required will happen on next postmaster start.
2130                          */
2131                         if (Shutdown > NoShutdown &&
2132                                 !DLGetHead(BackendList) && AutoVacPID == 0)
2133                         {
2134                                 ereport(LOG,
2135                                                 (errmsg("abnormal database system shutdown")));
2136                                 ExitPostmaster(1);
2137                         }
2138
2139                         /* Else, proceed as in normal crash recovery */
2140                         continue;
2141                 }
2142
2143                 /*
2144                  * Was it the autovacuum launcher?  Normal exit can be ignored; we'll
2145                  * start a new one at the next iteration of the postmaster's main loop,
2146                  * if necessary.  Any other exit condition is treated as a crash.
2147                  */
2148                 if (AutoVacPID != 0 && pid == AutoVacPID)
2149                 {
2150                         AutoVacPID = 0;
2151                         if (!EXIT_STATUS_0(exitstatus))
2152                                 HandleChildCrash(pid, exitstatus,
2153                                                                  _("autovacuum launcher process"));
2154                         continue;
2155                 }
2156
2157                 /*
2158                  * Was it the archiver?  If so, just try to start a new one; no need
2159                  * to force reset of the rest of the system.  (If fail, we'll try
2160                  * again in future cycles of the main loop.)
2161                  */
2162                 if (PgArchPID != 0 && pid == PgArchPID)
2163                 {
2164                         PgArchPID = 0;
2165                         if (!EXIT_STATUS_0(exitstatus))
2166                                 LogChildExit(LOG, _("archiver process"),
2167                                                          pid, exitstatus);
2168                         if (XLogArchivingActive() &&
2169                                 StartupPID == 0 && !FatalError && Shutdown == NoShutdown)
2170                                 PgArchPID = pgarch_start();
2171                         continue;
2172                 }
2173
2174                 /*
2175                  * Was it the statistics collector?  If so, just try to start a new
2176                  * one; no need to force reset of the rest of the system.  (If fail,
2177                  * we'll try again in future cycles of the main loop.)
2178                  */
2179                 if (PgStatPID != 0 && pid == PgStatPID)
2180                 {
2181                         PgStatPID = 0;
2182                         if (!EXIT_STATUS_0(exitstatus))
2183                                 LogChildExit(LOG, _("statistics collector process"),
2184                                                          pid, exitstatus);
2185                         if (StartupPID == 0 && !FatalError && Shutdown == NoShutdown)
2186                                 PgStatPID = pgstat_start();
2187                         continue;
2188                 }
2189
2190                 /* Was it the system logger? try to start a new one */
2191                 if (SysLoggerPID != 0 && pid == SysLoggerPID)
2192                 {
2193                         SysLoggerPID = 0;
2194                         /* for safety's sake, launch new logger *first* */
2195                         SysLoggerPID = SysLogger_Start();
2196                         if (!EXIT_STATUS_0(exitstatus))
2197                                 LogChildExit(LOG, _("system logger process"),
2198                                                          pid, exitstatus);
2199                         continue;
2200                 }
2201
2202                 /*
2203                  * Else do standard backend child cleanup.
2204                  */
2205                 CleanupBackend(pid, exitstatus);
2206         }                                                       /* loop over pending child-death reports */
2207
2208         if (FatalError)
2209         {
2210                 /*
2211                  * Wait for all important children to exit, then reset shmem and
2212                  * StartupDataBase.  (We can ignore the archiver and stats processes
2213                  * here since they are not connected to shmem.)
2214                  */
2215                 if (DLGetHead(BackendList) || StartupPID != 0 || BgWriterPID != 0 ||
2216                         AutoVacPID != 0)
2217                         goto reaper_done;
2218                 ereport(LOG,
2219                                 (errmsg("all server processes terminated; reinitializing")));
2220
2221                 shmem_exit(0);
2222                 reset_shared(PostPortNumber);
2223
2224                 StartupPID = StartupDataBase();
2225
2226                 goto reaper_done;
2227         }
2228
2229         if (Shutdown > NoShutdown)
2230         {
2231                 if (DLGetHead(BackendList) || StartupPID != 0)
2232                         goto reaper_done;
2233                 /* Start the bgwriter if not running */
2234                 if (BgWriterPID == 0)
2235                         BgWriterPID = StartBackgroundWriter();
2236                 /* And tell it to shut down */
2237                 if (BgWriterPID != 0)
2238                         signal_child(BgWriterPID, SIGUSR2);
2239                 /* Tell pgarch to shut down too; nothing left for it to do */
2240                 if (PgArchPID != 0)
2241                         signal_child(PgArchPID, SIGQUIT);
2242                 /* Tell pgstat to shut down too; nothing left for it to do */
2243                 if (PgStatPID != 0)
2244                         signal_child(PgStatPID, SIGQUIT);
2245                 /* Tell autovac launcher to shut down too */
2246                 if (AutoVacPID != 0)
2247                         signal_child(AutoVacPID, SIGTERM);
2248         }
2249
2250 reaper_done:
2251         PG_SETMASK(&UnBlockSig);
2252
2253         errno = save_errno;
2254 }
2255
2256
2257 /*
2258  * CleanupBackend -- cleanup after terminated backend.
2259  *
2260  * Remove all local state associated with backend.
2261  */
2262 static void
2263 CleanupBackend(int pid,
2264                            int exitstatus)      /* child's exit status. */
2265 {
2266         Dlelem     *curr;
2267
2268         LogChildExit(DEBUG2, _("server process"), pid, exitstatus);
2269
2270         /*
2271          * If a backend dies in an ugly way then we must signal all other backends
2272          * to quickdie.  If exit status is zero (normal) or one (FATAL exit), we
2273          * assume everything is all right and simply remove the backend from the
2274          * active backend list.
2275          */
2276         if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
2277         {
2278                 HandleChildCrash(pid, exitstatus, _("server process"));
2279                 return;
2280         }
2281
2282         for (curr = DLGetHead(BackendList); curr; curr = DLGetSucc(curr))
2283         {
2284                 Backend    *bp = (Backend *) DLE_VAL(curr);
2285
2286                 if (bp->pid == pid)
2287                 {
2288                         DLRemove(curr);
2289                         free(bp);
2290                         DLFreeElem(curr);
2291 #ifdef EXEC_BACKEND
2292                         ShmemBackendArrayRemove(pid);
2293 #endif
2294                         break;
2295                 }
2296         }
2297 }
2298
2299 /*
2300  * HandleChildCrash -- cleanup after failed backend, bgwriter, or autovacuum.
2301  *
2302  * The objectives here are to clean up our local state about the child
2303  * process, and to signal all other remaining children to quickdie.
2304  */
2305 static void
2306 HandleChildCrash(int pid, int exitstatus, const char *procname)
2307 {
2308         Dlelem     *curr,
2309                            *next;
2310         Backend    *bp;
2311
2312         /*
2313          * Make log entry unless there was a previous crash (if so, nonzero exit
2314          * status is to be expected in SIGQUIT response; don't clutter log)
2315          */
2316         if (!FatalError)
2317         {
2318                 LogChildExit(LOG, procname, pid, exitstatus);
2319                 ereport(LOG,
2320                                 (errmsg("terminating any other active server processes")));
2321         }
2322
2323         /* Process regular backends */
2324         for (curr = DLGetHead(BackendList); curr; curr = next)
2325         {
2326                 next = DLGetSucc(curr);
2327                 bp = (Backend *) DLE_VAL(curr);
2328                 if (bp->pid == pid)
2329                 {
2330                         /*
2331                          * Found entry for freshly-dead backend, so remove it.
2332                          */
2333                         DLRemove(curr);
2334                         free(bp);
2335                         DLFreeElem(curr);
2336 #ifdef EXEC_BACKEND
2337                         ShmemBackendArrayRemove(pid);
2338 #endif
2339                         /* Keep looping so we can signal remaining backends */
2340                 }
2341                 else
2342                 {
2343                         /*
2344                          * This backend is still alive.  Unless we did so already, tell it
2345                          * to commit hara-kiri.
2346                          *
2347                          * SIGQUIT is the special signal that says exit without proc_exit
2348                          * and let the user know what's going on. But if SendStop is set
2349                          * (-s on command line), then we send SIGSTOP instead, so that we
2350                          * can get core dumps from all backends by hand.
2351                          */
2352                         if (!FatalError)
2353                         {
2354                                 ereport(DEBUG2,
2355                                                 (errmsg_internal("sending %s to process %d",
2356                                                                                  (SendStop ? "SIGSTOP" : "SIGQUIT"),
2357                                                                                  (int) bp->pid)));
2358                                 signal_child(bp->pid, (SendStop ? SIGSTOP : SIGQUIT));
2359                         }
2360                 }
2361         }
2362
2363         /* Take care of the bgwriter too */
2364         if (pid == BgWriterPID)
2365                 BgWriterPID = 0;
2366         else if (BgWriterPID != 0 && !FatalError)
2367         {
2368                 ereport(DEBUG2,
2369                                 (errmsg_internal("sending %s to process %d",
2370                                                                  (SendStop ? "SIGSTOP" : "SIGQUIT"),
2371                                                                  (int) BgWriterPID)));
2372                 signal_child(BgWriterPID, (SendStop ? SIGSTOP : SIGQUIT));
2373         }
2374
2375         /* Take care of the autovacuum launcher too */
2376         if (pid == AutoVacPID)
2377                 AutoVacPID = 0;
2378         else if (AutoVacPID != 0 && !FatalError)
2379         {
2380                 ereport(DEBUG2,
2381                                 (errmsg_internal("sending %s to process %d",
2382                                                                  (SendStop ? "SIGSTOP" : "SIGQUIT"),
2383                                                                  (int) AutoVacPID)));
2384                 signal_child(AutoVacPID, (SendStop ? SIGSTOP : SIGQUIT));
2385         }
2386
2387         /* Force a power-cycle of the pgarch process too */
2388         /* (Shouldn't be necessary, but just for luck) */
2389         if (PgArchPID != 0 && !FatalError)
2390         {
2391                 ereport(DEBUG2,
2392                                 (errmsg_internal("sending %s to process %d",
2393                                                                  "SIGQUIT",
2394                                                                  (int) PgArchPID)));
2395                 signal_child(PgArchPID, SIGQUIT);
2396         }
2397
2398         /* Force a power-cycle of the pgstat process too */
2399         /* (Shouldn't be necessary, but just for luck) */
2400         if (PgStatPID != 0 && !FatalError)
2401         {
2402                 ereport(DEBUG2,
2403                                 (errmsg_internal("sending %s to process %d",
2404                                                                  "SIGQUIT",
2405                                                                  (int) PgStatPID)));
2406                 signal_child(PgStatPID, SIGQUIT);
2407         }
2408
2409         /* We do NOT restart the syslogger */
2410
2411         FatalError = true;
2412 }
2413
2414 /*
2415  * Log the death of a child process.
2416  */
2417 static void
2418 LogChildExit(int lev, const char *procname, int pid, int exitstatus)
2419 {
2420         if (WIFEXITED(exitstatus))
2421                 ereport(lev,
2422
2423                 /*------
2424                   translator: %s is a noun phrase describing a child process, such as
2425                   "server process" */
2426                                 (errmsg("%s (PID %d) exited with exit code %d",
2427                                                 procname, pid, WEXITSTATUS(exitstatus))));
2428         else if (WIFSIGNALED(exitstatus))
2429 #if defined(WIN32)
2430                 ereport(lev,
2431
2432                 /*------
2433                   translator: %s is a noun phrase describing a child process, such as
2434                   "server process" */
2435                                 (errmsg("%s (PID %d) was terminated by exception 0x%X",
2436                                                 procname, pid, WTERMSIG(exitstatus)),
2437                                  errhint("See C include file \"ntstatus.h\" for a description of the hex value.")));
2438 #elif defined(HAVE_DECL_SYS_SIGLIST) && HAVE_DECL_SYS_SIGLIST
2439                 ereport(lev,
2440
2441                 /*------
2442                   translator: %s is a noun phrase describing a child process, such as
2443                   "server process" */
2444                                 (errmsg("%s (PID %d) was terminated by signal %d: %s",
2445                                                 procname, pid, WTERMSIG(exitstatus),
2446                                                 WTERMSIG(exitstatus) < NSIG ?
2447                                                 sys_siglist[WTERMSIG(exitstatus)] : "(unknown)")));
2448 #else
2449                 ereport(lev,
2450
2451                 /*------
2452                   translator: %s is a noun phrase describing a child process, such as
2453                   "server process" */
2454                                 (errmsg("%s (PID %d) was terminated by signal %d",
2455                                                 procname, pid, WTERMSIG(exitstatus))));
2456 #endif
2457         else
2458                 ereport(lev,
2459
2460                 /*------
2461                   translator: %s is a noun phrase describing a child process, such as
2462                   "server process" */
2463                                 (errmsg("%s (PID %d) exited with unrecognized status %d",
2464                                                 procname, pid, exitstatus)));
2465 }
2466
2467 /*
2468  * Send a signal to a postmaster child process
2469  *
2470  * On systems that have setsid(), each child process sets itself up as a
2471  * process group leader.  For signals that are generally interpreted in the
2472  * appropriate fashion, we signal the entire process group not just the
2473  * direct child process.  This allows us to, for example, SIGQUIT a blocked
2474  * archive_recovery script, or SIGINT a script being run by a backend via
2475  * system().
2476  *
2477  * There is a race condition for recently-forked children: they might not
2478  * have executed setsid() yet.  So we signal the child directly as well as
2479  * the group.  We assume such a child will handle the signal before trying
2480  * to spawn any grandchild processes.  We also assume that signaling the
2481  * child twice will not cause any problems.
2482  */
2483 static void
2484 signal_child(pid_t pid, int signal)
2485 {
2486         if (kill(pid, signal) < 0)
2487                 elog(DEBUG3, "kill(%ld,%d) failed: %m", (long) pid, signal);
2488 #ifdef HAVE_SETSID
2489         switch (signal)
2490         {
2491                 case SIGINT:
2492                 case SIGTERM:
2493                 case SIGQUIT:
2494                 case SIGSTOP:
2495                         if (kill(-pid, signal) < 0)
2496                                 elog(DEBUG3, "kill(%ld,%d) failed: %m", (long) (-pid), signal);
2497                         break;
2498                 default:
2499                         break;
2500         }
2501 #endif
2502 }
2503
2504 /*
2505  * Send a signal to all backend children, including autovacuum workers (but NOT
2506  * special children).
2507  */
2508 static void
2509 SignalChildren(int signal)
2510 {
2511         SignalSomeChildren(signal, false);
2512 }
2513
2514 /*
2515  * Send a signal to all backend children, including autovacuum workers (but NOT
2516  * special children).  If only_autovac is TRUE, only the autovacuum worker
2517  * processes are signalled.
2518  */
2519 static void
2520 SignalSomeChildren(int signal, bool only_autovac)
2521 {
2522         Dlelem     *curr;
2523
2524         for (curr = DLGetHead(BackendList); curr; curr = DLGetSucc(curr))
2525         {
2526                 Backend    *bp = (Backend *) DLE_VAL(curr);
2527
2528                 if (only_autovac && !bp->is_autovacuum)
2529                         continue;
2530
2531                 ereport(DEBUG4,
2532                                 (errmsg_internal("sending signal %d to process %d",
2533                                                                  signal, (int) bp->pid)));
2534                 signal_child(bp->pid, signal);
2535         }
2536 }
2537
2538 /*
2539  * BackendStartup -- start backend process
2540  *
2541  * returns: STATUS_ERROR if the fork failed, STATUS_OK otherwise.
2542  *
2543  * Note: if you change this code, also consider StartAutovacuumWorker.
2544  */
2545 static int
2546 BackendStartup(Port *port)
2547 {
2548         Backend    *bn;                         /* for backend cleanup */
2549         pid_t           pid;
2550
2551         /*
2552          * Compute the cancel key that will be assigned to this backend. The
2553          * backend will have its own copy in the forked-off process' value of
2554          * MyCancelKey, so that it can transmit the key to the frontend.
2555          */
2556         MyCancelKey = PostmasterRandom();
2557
2558         /*
2559          * Make room for backend data structure.  Better before the fork() so we
2560          * can handle failure cleanly.
2561          */
2562         bn = (Backend *) malloc(sizeof(Backend));
2563         if (!bn)
2564         {
2565                 ereport(LOG,
2566                                 (errcode(ERRCODE_OUT_OF_MEMORY),
2567                                  errmsg("out of memory")));
2568                 return STATUS_ERROR;
2569         }
2570
2571         /* Pass down canAcceptConnections state (kluge for EXEC_BACKEND case) */
2572         port->canAcceptConnections = canAcceptConnections();
2573
2574 #ifdef EXEC_BACKEND
2575         pid = backend_forkexec(port);
2576 #else                                                   /* !EXEC_BACKEND */
2577         pid = fork_process();
2578         if (pid == 0)                           /* child */
2579         {
2580                 free(bn);
2581
2582                 /*
2583                  * Let's clean up ourselves as the postmaster child, and close the
2584                  * postmaster's listen sockets.  (In EXEC_BACKEND case this is all
2585                  * done in SubPostmasterMain.)
2586                  */
2587                 IsUnderPostmaster = true;               /* we are a postmaster subprocess now */
2588
2589                 MyProcPid = getpid();   /* reset MyProcPid */
2590
2591                 /* We don't want the postmaster's proc_exit() handlers */
2592                 on_exit_reset();
2593
2594                 /* Close the postmaster's sockets */
2595                 ClosePostmasterPorts(false);
2596
2597                 /* Perform additional initialization and client authentication */
2598                 BackendInitialize(port);
2599
2600                 /* And run the backend */
2601                 proc_exit(BackendRun(port));
2602         }
2603 #endif   /* EXEC_BACKEND */
2604
2605         if (pid < 0)
2606         {
2607                 /* in parent, fork failed */
2608                 int                     save_errno = errno;
2609
2610                 free(bn);
2611                 errno = save_errno;
2612                 ereport(LOG,
2613                                 (errmsg("could not fork new process for connection: %m")));
2614                 report_fork_failure_to_client(port, save_errno);
2615                 return STATUS_ERROR;
2616         }
2617
2618         /* in parent, successful fork */
2619         ereport(DEBUG2,
2620                         (errmsg_internal("forked new backend, pid=%d socket=%d",
2621                                                          (int) pid, port->sock)));
2622
2623         /*
2624          * Everything's been successful, it's safe to add this backend to our list
2625          * of backends.
2626          */
2627         bn->pid = pid;
2628         bn->cancel_key = MyCancelKey;
2629         DLAddHead(BackendList, DLNewElem(bn));
2630 #ifdef EXEC_BACKEND
2631         ShmemBackendArrayAdd(bn);
2632 #endif
2633
2634         return STATUS_OK;
2635 }
2636
2637 /*
2638  * Try to report backend fork() failure to client before we close the
2639  * connection.  Since we do not care to risk blocking the postmaster on
2640  * this connection, we set the connection to non-blocking and try only once.
2641  *
2642  * This is grungy special-purpose code; we cannot use backend libpq since
2643  * it's not up and running.
2644  */
2645 static void
2646 report_fork_failure_to_client(Port *port, int errnum)
2647 {
2648         char            buffer[1000];
2649         int                     rc;
2650
2651         /* Format the error message packet (always V2 protocol) */
2652         snprintf(buffer, sizeof(buffer), "E%s%s\n",
2653                          _("could not fork new process for connection: "),
2654                          strerror(errnum));
2655
2656         /* Set port to non-blocking.  Don't do send() if this fails */
2657         if (!pg_set_noblock(port->sock))
2658                 return;
2659
2660         /* We'll retry after EINTR, but ignore all other failures */
2661         do
2662         {
2663                 rc = send(port->sock, buffer, strlen(buffer) + 1, 0);
2664         } while (rc < 0 && errno == EINTR);
2665 }
2666
2667
2668 /*
2669  * split_opts -- split a string of options and append it to an argv array
2670  *
2671  * NB: the string is destructively modified!
2672  *
2673  * Since no current POSTGRES arguments require any quoting characters,
2674  * we can use the simple-minded tactic of assuming each set of space-
2675  * delimited characters is a separate argv element.
2676  *
2677  * If you don't like that, well, we *used* to pass the whole option string
2678  * as ONE argument to execl(), which was even less intelligent...
2679  */
2680 static void
2681 split_opts(char **argv, int *argcp, char *s)
2682 {
2683         while (s && *s)
2684         {
2685                 while (isspace((unsigned char) *s))
2686                         ++s;
2687                 if (*s == '\0')
2688                         break;
2689                 argv[(*argcp)++] = s;
2690                 while (*s && !isspace((unsigned char) *s))
2691                         ++s;
2692                 if (*s)
2693                         *s++ = '\0';
2694         }
2695 }
2696
2697
2698 /*
2699  * BackendInitialize -- initialize an interactive (postmaster-child)
2700  *                              backend process, and perform client authentication.
2701  *
2702  * returns: nothing.  Will not return at all if there's any failure.
2703  *
2704  * Note: this code does not depend on having any access to shared memory.
2705  * In the EXEC_BACKEND case, we are physically attached to shared memory
2706  * but have not yet set up most of our local pointers to shmem structures.
2707  */
2708 static void
2709 BackendInitialize(Port *port)
2710 {
2711         int                     status;
2712         char            remote_host[NI_MAXHOST];
2713         char            remote_port[NI_MAXSERV];
2714         char            remote_ps_data[NI_MAXHOST];
2715
2716         /* Save port etc. for ps status */
2717         MyProcPort = port;
2718
2719         /*
2720          * PreAuthDelay is a debugging aid for investigating problems in the
2721          * authentication cycle: it can be set in postgresql.conf to allow time to
2722          * attach to the newly-forked backend with a debugger. (See also the -W
2723          * backend switch, which we allow clients to pass through PGOPTIONS, but
2724          * it is not honored until after authentication.)
2725          */
2726         if (PreAuthDelay > 0)
2727                 pg_usleep(PreAuthDelay * 1000000L);
2728
2729         ClientAuthInProgress = true;    /* limit visibility of log messages */
2730
2731         /* save process start time */
2732         port->SessionStartTime = GetCurrentTimestamp();
2733         port->session_start = timestamptz_to_time_t(port->SessionStartTime);
2734
2735         /* set these to empty in case they are needed before we set them up */
2736         port->remote_host = "";
2737         port->remote_port = "";
2738
2739         /*
2740          * Initialize libpq and enable reporting of ereport errors to the client.
2741          * Must do this now because authentication uses libpq to send messages.
2742          */
2743         pq_init();                                      /* initialize libpq to talk to client */
2744         whereToSendOutput = DestRemote;         /* now safe to ereport to client */
2745
2746         /*
2747          * If possible, make this process a group leader, so that the postmaster
2748          * can signal any child processes too.  (We do this now on the off chance
2749          * that something might spawn a child process during authentication.)
2750          */
2751 #ifdef HAVE_SETSID
2752         if (setsid() < 0)
2753                 elog(FATAL, "setsid() failed: %m");
2754 #endif
2755
2756         /*
2757          * We arrange for a simple exit(1) if we receive SIGTERM or SIGQUIT during
2758          * any client authentication related communication. Otherwise the
2759          * postmaster cannot shutdown the database FAST or IMMED cleanly if a
2760          * buggy client blocks a backend during authentication.
2761          */
2762         pqsignal(SIGTERM, authdie);
2763         pqsignal(SIGQUIT, authdie);
2764         pqsignal(SIGALRM, authdie);
2765         PG_SETMASK(&AuthBlockSig);
2766
2767         /*
2768          * Get the remote host name and port for logging and status display.
2769          */
2770         remote_host[0] = '\0';
2771         remote_port[0] = '\0';
2772         if (pg_getnameinfo_all(&port->raddr.addr, port->raddr.salen,
2773                                                    remote_host, sizeof(remote_host),
2774                                                    remote_port, sizeof(remote_port),
2775                                            (log_hostname ? 0 : NI_NUMERICHOST) | NI_NUMERICSERV))
2776         {
2777                 int                     ret = pg_getnameinfo_all(&port->raddr.addr, port->raddr.salen,
2778                                                                                          remote_host, sizeof(remote_host),
2779                                                                                          remote_port, sizeof(remote_port),
2780                                                                                          NI_NUMERICHOST | NI_NUMERICSERV);
2781
2782                 if (ret)
2783                         ereport(WARNING,
2784                                         (errmsg_internal("pg_getnameinfo_all() failed: %s",
2785                                                                          gai_strerror(ret))));
2786         }
2787         snprintf(remote_ps_data, sizeof(remote_ps_data),
2788                          remote_port[0] == '\0' ? "%s" : "%s(%s)",
2789                          remote_host, remote_port);
2790
2791         if (Log_connections)
2792                 ereport(LOG,
2793                                 (errmsg("connection received: host=%s%s%s",
2794                                                 remote_host, remote_port[0] ? " port=" : "",
2795                                                 remote_port)));
2796
2797         /*
2798          * save remote_host and remote_port in port structure
2799          */
2800         port->remote_host = strdup(remote_host);
2801         port->remote_port = strdup(remote_port);
2802
2803         /*
2804          * In EXEC_BACKEND case, we didn't inherit the contents of pg_hba.conf
2805          * etcetera from the postmaster, and have to load them ourselves. Build
2806          * the PostmasterContext (which didn't exist before, in this process) to
2807          * contain the data.
2808          *
2809          * FIXME: [fork/exec] Ugh.      Is there a way around this overhead?
2810          */
2811 #ifdef EXEC_BACKEND
2812         Assert(PostmasterContext == NULL);
2813         PostmasterContext = AllocSetContextCreate(TopMemoryContext,
2814                                                                                           "Postmaster",
2815                                                                                           ALLOCSET_DEFAULT_MINSIZE,
2816                                                                                           ALLOCSET_DEFAULT_INITSIZE,
2817                                                                                           ALLOCSET_DEFAULT_MAXSIZE);
2818         MemoryContextSwitchTo(PostmasterContext);
2819
2820         load_hba();
2821         load_ident();
2822         load_role();
2823 #endif
2824
2825         /*
2826          * Ready to begin client interaction.  We will give up and exit(0) after a
2827          * time delay, so that a broken client can't hog a connection
2828          * indefinitely.  PreAuthDelay doesn't count against the time limit.
2829          */
2830         if (!enable_sig_alarm(AuthenticationTimeout * 1000, false))
2831                 elog(FATAL, "could not set timer for authorization timeout");
2832
2833         /*
2834          * Receive the startup packet (which might turn out to be a cancel request
2835          * packet).
2836          */
2837         status = ProcessStartupPacket(port, false);
2838
2839         if (status != STATUS_OK)
2840                 proc_exit(0);
2841
2842         /*
2843          * Now that we have the user and database name, we can set the process
2844          * title for ps.  It's good to do this as early as possible in startup.
2845          */
2846         init_ps_display(port->user_name, port->database_name, remote_ps_data,
2847                                         update_process_title ? "authentication" : "");
2848
2849         /*
2850          * Now perform authentication exchange.
2851          */
2852         ClientAuthentication(port); /* might not return, if failure */
2853
2854         /*
2855          * Done with authentication.  Disable timeout, and prevent SIGTERM/SIGQUIT
2856          * again until backend startup is complete.
2857          */
2858         if (!disable_sig_alarm(false))
2859                 elog(FATAL, "could not disable timer for authorization timeout");
2860         PG_SETMASK(&BlockSig);
2861
2862         if (Log_connections)
2863                 ereport(LOG,
2864                                 (errmsg("connection authorized: user=%s database=%s",
2865                                                 port->user_name, port->database_name)));
2866 }
2867
2868
2869 /*
2870  * BackendRun -- set up the backend's argument list and invoke PostgresMain()
2871  *
2872  * returns:
2873  *              Shouldn't return at all.
2874  *              If PostgresMain() fails, return status.
2875  */
2876 static int
2877 BackendRun(Port *port)
2878 {
2879         char      **av;
2880         int                     maxac;
2881         int                     ac;
2882         long            secs;
2883         int                     usecs;
2884         char            protobuf[32];
2885         int                     i;
2886
2887         /*
2888          * Don't want backend to be able to see the postmaster random number
2889          * generator state.  We have to clobber the static random_seed *and* start
2890          * a new random sequence in the random() library function.
2891          */
2892         random_seed = 0;
2893         /* slightly hacky way to get integer microseconds part of timestamptz */
2894         TimestampDifference(0, port->SessionStartTime, &secs, &usecs);
2895         srandom((unsigned int) (MyProcPid ^ usecs));
2896
2897         /* ----------------
2898          * Now, build the argv vector that will be given to PostgresMain.
2899          *
2900          * The layout of the command line is
2901          *              postgres [secure switches] -y databasename [insecure switches]
2902          * where the switches after -y come from the client request.
2903          *
2904          * The maximum possible number of commandline arguments that could come
2905          * from ExtraOptions or port->cmdline_options is (strlen + 1) / 2; see
2906          * split_opts().
2907          * ----------------
2908          */
2909         maxac = 10;                                     /* for fixed args supplied below */
2910         maxac += (strlen(ExtraOptions) + 1) / 2;
2911         if (port->cmdline_options)
2912                 maxac += (strlen(port->cmdline_options) + 1) / 2;
2913
2914         av = (char **) MemoryContextAlloc(TopMemoryContext,
2915                                                                           maxac * sizeof(char *));
2916         ac = 0;
2917
2918         av[ac++] = "postgres";
2919
2920         /*
2921          * Pass any backend switches specified with -o in the postmaster's own
2922          * command line.  We assume these are secure.  (It's OK to mangle
2923          * ExtraOptions now, since we're safely inside a subprocess.)
2924          */
2925         split_opts(av, &ac, ExtraOptions);
2926
2927         /* Tell the backend what protocol the frontend is using. */
2928         snprintf(protobuf, sizeof(protobuf), "-v%u", port->proto);
2929         av[ac++] = protobuf;
2930
2931         /*
2932          * Tell the backend it is being called from the postmaster, and which
2933          * database to use.  -y marks the end of secure switches.
2934          */
2935         av[ac++] = "-y";
2936         av[ac++] = port->database_name;
2937
2938         /*
2939          * Pass the (insecure) option switches from the connection request. (It's
2940          * OK to mangle port->cmdline_options now.)
2941          */
2942         if (port->cmdline_options)
2943                 split_opts(av, &ac, port->cmdline_options);
2944
2945         av[ac] = NULL;
2946
2947         Assert(ac < maxac);
2948
2949         /*
2950          * Release postmaster's working memory context so that backend can recycle
2951          * the space.  Note this does not trash *MyProcPort, because ConnCreate()
2952          * allocated that space with malloc() ... else we'd need to copy the Port
2953          * data here.  Also, subsidiary data such as the username isn't lost
2954          * either; see ProcessStartupPacket().
2955          */
2956         MemoryContextSwitchTo(TopMemoryContext);
2957         MemoryContextDelete(PostmasterContext);
2958         PostmasterContext = NULL;
2959
2960         /*
2961          * Debug: print arguments being passed to backend
2962          */
2963         ereport(DEBUG3,
2964                         (errmsg_internal("%s child[%d]: starting with (",
2965                                                          progname, (int) getpid())));
2966         for (i = 0; i < ac; ++i)
2967                 ereport(DEBUG3,
2968                                 (errmsg_internal("\t%s", av[i])));
2969         ereport(DEBUG3,
2970                         (errmsg_internal(")")));
2971
2972         ClientAuthInProgress = false;           /* client_min_messages is active now */
2973
2974         return (PostgresMain(ac, av, port->user_name));
2975 }
2976
2977
2978 #ifdef EXEC_BACKEND
2979
2980 /*
2981  * postmaster_forkexec -- fork and exec a postmaster subprocess
2982  *
2983  * The caller must have set up the argv array already, except for argv[2]
2984  * which will be filled with the name of the temp variable file.
2985  *
2986  * Returns the child process PID, or -1 on fork failure (a suitable error
2987  * message has been logged on failure).
2988  *
2989  * All uses of this routine will dispatch to SubPostmasterMain in the
2990  * child process.
2991  */
2992 pid_t
2993 postmaster_forkexec(int argc, char *argv[])
2994 {
2995         Port            port;
2996
2997         /* This entry point passes dummy values for the Port variables */
2998         memset(&port, 0, sizeof(port));
2999         return internal_forkexec(argc, argv, &port);
3000 }
3001
3002 /*
3003  * backend_forkexec -- fork/exec off a backend process
3004  *
3005  * returns the pid of the fork/exec'd process, or -1 on failure
3006  */
3007 static pid_t
3008 backend_forkexec(Port *port)
3009 {
3010         char       *av[4];
3011         int                     ac = 0;
3012
3013         av[ac++] = "postgres";
3014         av[ac++] = "--forkbackend";
3015         av[ac++] = NULL;                        /* filled in by internal_forkexec */
3016
3017         av[ac] = NULL;
3018         Assert(ac < lengthof(av));
3019
3020         return internal_forkexec(ac, av, port);
3021 }
3022
3023 #ifndef WIN32
3024
3025 /*
3026  * internal_forkexec non-win32 implementation
3027  *
3028  * - writes out backend variables to the parameter file
3029  * - fork():s, and then exec():s the child process
3030  */
3031 static pid_t
3032 internal_forkexec(int argc, char *argv[], Port *port)
3033 {
3034         static unsigned long tmpBackendFileNum = 0;
3035         pid_t           pid;
3036         char            tmpfilename[MAXPGPATH];
3037         BackendParameters param;
3038         FILE       *fp;
3039
3040         if (!save_backend_variables(&param, port))
3041                 return -1;                              /* log made by save_backend_variables */
3042
3043         /* Calculate name for temp file */
3044         snprintf(tmpfilename, MAXPGPATH, "%s/%s.backend_var.%d.%lu",
3045                          PG_TEMP_FILES_DIR, PG_TEMP_FILE_PREFIX,
3046                          MyProcPid, ++tmpBackendFileNum);
3047
3048         /* Open file */
3049         fp = AllocateFile(tmpfilename, PG_BINARY_W);
3050         if (!fp)
3051         {
3052                 /* As in OpenTemporaryFile, try to make the temp-file directory */
3053                 mkdir(PG_TEMP_FILES_DIR, S_IRWXU);
3054
3055                 fp = AllocateFile(tmpfilename, PG_BINARY_W);
3056                 if (!fp)
3057                 {
3058                         ereport(LOG,
3059                                         (errcode_for_file_access(),
3060                                          errmsg("could not create file \"%s\": %m",
3061                                                         tmpfilename)));
3062                         return -1;
3063                 }
3064         }
3065
3066         if (fwrite(&param, sizeof(param), 1, fp) != 1)
3067         {
3068                 ereport(LOG,
3069                                 (errcode_for_file_access(),
3070                                  errmsg("could not write to file \"%s\": %m", tmpfilename)));
3071                 FreeFile(fp);
3072                 return -1;
3073         }
3074
3075         /* Release file */
3076         if (FreeFile(fp))
3077         {
3078                 ereport(LOG,
3079                                 (errcode_for_file_access(),
3080                                  errmsg("could not write to file \"%s\": %m", tmpfilename)));
3081                 return -1;
3082         }
3083
3084         /* Make sure caller set up argv properly */
3085         Assert(argc >= 3);
3086         Assert(argv[argc] == NULL);
3087         Assert(strncmp(argv[1], "--fork", 6) == 0);
3088         Assert(argv[2] == NULL);
3089
3090         /* Insert temp file name after --fork argument */
3091         argv[2] = tmpfilename;
3092
3093         /* Fire off execv in child */
3094         if ((pid = fork_process()) == 0)
3095         {
3096                 if (execv(postgres_exec_path, argv) < 0)
3097                 {
3098                         ereport(LOG,
3099                                         (errmsg("could not execute server process \"%s\": %m",
3100                                                         postgres_exec_path)));
3101                         /* We're already in the child process here, can't return */
3102                         exit(1);
3103                 }
3104         }
3105
3106         return pid;                                     /* Parent returns pid, or -1 on fork failure */
3107 }
3108 #else                                                   /* WIN32 */
3109
3110 /*
3111  * internal_forkexec win32 implementation
3112  *
3113  * - starts backend using CreateProcess(), in suspended state
3114  * - writes out backend variables to the parameter file
3115  *      - during this, duplicates handles and sockets required for
3116  *        inheritance into the new process
3117  * - resumes execution of the new process once the backend parameter
3118  *       file is complete.
3119  */
3120 static pid_t
3121 internal_forkexec(int argc, char *argv[], Port *port)
3122 {
3123         STARTUPINFO si;
3124         PROCESS_INFORMATION pi;
3125         int                     i;
3126         int                     j;
3127         char            cmdLine[MAXPGPATH * 2];
3128         HANDLE          childHandleCopy;
3129         HANDLE          waiterThread;
3130         HANDLE          paramHandle;
3131         BackendParameters *param;
3132         SECURITY_ATTRIBUTES sa;
3133         char            paramHandleStr[32];
3134
3135         /* Make sure caller set up argv properly */
3136         Assert(argc >= 3);
3137         Assert(argv[argc] == NULL);
3138         Assert(strncmp(argv[1], "--fork", 6) == 0);
3139         Assert(argv[2] == NULL);
3140
3141         /* Verify that there is room in the child list */
3142         if (win32_numChildren >= NUM_BACKENDARRAY_ELEMS)
3143         {
3144                 elog(LOG, "no room for child entry in backend list");
3145                 /* Report same error as for a fork failure on Unix */
3146                 errno = EAGAIN;
3147                 return -1;
3148         }
3149
3150         /* Set up shared memory for parameter passing */
3151         ZeroMemory(&sa, sizeof(sa));
3152         sa.nLength = sizeof(sa);
3153         sa.bInheritHandle = TRUE;
3154         paramHandle = CreateFileMapping(INVALID_HANDLE_VALUE,
3155                                                                         &sa,
3156                                                                         PAGE_READWRITE,
3157                                                                         0,
3158                                                                         sizeof(BackendParameters),
3159                                                                         NULL);
3160         if (paramHandle == INVALID_HANDLE_VALUE)
3161         {
3162                 elog(LOG, "could not create backend parameter file mapping: error code %d",
3163                          (int) GetLastError());
3164                 return -1;
3165         }
3166
3167         param = MapViewOfFile(paramHandle, FILE_MAP_WRITE, 0, 0, sizeof(BackendParameters));
3168         if (!param)
3169         {
3170                 elog(LOG, "could not map backend parameter memory: error code %d",
3171                          (int) GetLastError());
3172                 CloseHandle(paramHandle);
3173                 return -1;
3174         }
3175
3176         /* Insert temp file name after --fork argument */
3177         sprintf(paramHandleStr, "%lu", (DWORD) paramHandle);
3178         argv[2] = paramHandleStr;
3179
3180         /* Format the cmd line */
3181         cmdLine[sizeof(cmdLine) - 1] = '\0';
3182         cmdLine[sizeof(cmdLine) - 2] = '\0';
3183         snprintf(cmdLine, sizeof(cmdLine) - 1, "\"%s\"", postgres_exec_path);
3184         i = 0;
3185         while (argv[++i] != NULL)
3186         {
3187                 j = strlen(cmdLine);
3188                 snprintf(cmdLine + j, sizeof(cmdLine) - 1 - j, " \"%s\"", argv[i]);
3189         }
3190         if (cmdLine[sizeof(cmdLine) - 2] != '\0')
3191         {
3192                 elog(LOG, "subprocess command line too long");
3193                 return -1;
3194         }
3195
3196         memset(&pi, 0, sizeof(pi));
3197         memset(&si, 0, sizeof(si));
3198         si.cb = sizeof(si);
3199
3200         /*
3201          * Create the subprocess in a suspended state. This will be resumed later,
3202          * once we have written out the parameter file.
3203          */
3204         if (!CreateProcess(NULL, cmdLine, NULL, NULL, TRUE, CREATE_SUSPENDED,
3205                                            NULL, NULL, &si, &pi))
3206         {
3207                 elog(LOG, "CreateProcess call failed: %m (error code %d)",
3208                          (int) GetLastError());
3209                 return -1;
3210         }
3211
3212         if (!save_backend_variables(param, port, pi.hProcess, pi.dwProcessId))
3213         {
3214                 /*
3215                  * log made by save_backend_variables, but we have to clean up the
3216                  * mess with the half-started process
3217                  */
3218                 if (!TerminateProcess(pi.hProcess, 255))
3219                         ereport(ERROR,
3220                                         (errmsg_internal("could not terminate unstarted process: error code %d",
3221                                                                          (int) GetLastError())));
3222                 CloseHandle(pi.hProcess);
3223                 CloseHandle(pi.hThread);
3224                 return -1;                              /* log made by save_backend_variables */
3225         }
3226
3227         /* Drop the shared memory that is now inherited to the backend */
3228         if (!UnmapViewOfFile(param))
3229                 elog(LOG, "could not unmap view of backend parameter file: error code %d",
3230                          (int) GetLastError());
3231         if (!CloseHandle(paramHandle))
3232                 elog(LOG, "could not close handle to backend parameter file: error code %d",
3233                          (int) GetLastError());
3234
3235         /*
3236          * Now that the backend variables are written out, we start the child
3237          * thread so it can start initializing while we set up the rest of the
3238          * parent state.
3239          */
3240         if (ResumeThread(pi.hThread) == -1)
3241         {
3242                 if (!TerminateProcess(pi.hProcess, 255))
3243                 {
3244                         ereport(ERROR,
3245                                         (errmsg_internal("could not terminate unstartable process: error code %d",
3246                                                                          (int) GetLastError())));
3247                         CloseHandle(pi.hProcess);
3248                         CloseHandle(pi.hThread);
3249                         return -1;
3250                 }
3251                 CloseHandle(pi.hProcess);
3252                 CloseHandle(pi.hThread);
3253                 ereport(ERROR,
3254                                 (errmsg_internal("could not resume thread of unstarted process: error code %d",
3255                                                                  (int) GetLastError())));
3256                 return -1;
3257         }
3258
3259         if (!IsUnderPostmaster)
3260         {
3261                 /* We are the Postmaster creating a child... */
3262                 win32_AddChild(pi.dwProcessId, pi.hProcess);
3263         }
3264
3265         /* Set up the thread to handle the SIGCHLD for this process */
3266         if (DuplicateHandle(GetCurrentProcess(),
3267                                                 pi.hProcess,
3268                                                 GetCurrentProcess(),
3269                                                 &childHandleCopy,
3270                                                 0,
3271                                                 FALSE,
3272                                                 DUPLICATE_SAME_ACCESS) == 0)
3273                 ereport(FATAL,
3274                   (errmsg_internal("could not duplicate child handle: error code %d",
3275                                                    (int) GetLastError())));
3276
3277         waiterThread = CreateThread(NULL, 64 * 1024, win32_sigchld_waiter,
3278                                                                 (LPVOID) childHandleCopy, 0, NULL);
3279         if (!waiterThread)
3280                 ereport(FATAL,
3281                                 (errmsg_internal("could not create sigchld waiter thread: error code %d",
3282                                                                  (int) GetLastError())));
3283         CloseHandle(waiterThread);
3284
3285         if (IsUnderPostmaster)
3286                 CloseHandle(pi.hProcess);
3287         CloseHandle(pi.hThread);
3288
3289         return pi.dwProcessId;
3290 }
3291 #endif   /* WIN32 */
3292
3293
3294 /*
3295  * SubPostmasterMain -- Get the fork/exec'd process into a state equivalent
3296  *                      to what it would be if we'd simply forked on Unix, and then
3297  *                      dispatch to the appropriate place.
3298  *
3299  * The first two command line arguments are expected to be "--forkFOO"
3300  * (where FOO indicates which postmaster child we are to become), and
3301  * the name of a variables file that we can read to load data that would
3302  * have been inherited by fork() on Unix.  Remaining arguments go to the
3303  * subprocess FooMain() routine.
3304  */
3305 int
3306 SubPostmasterMain(int argc, char *argv[])
3307 {
3308         Port            port;
3309
3310         /* Do this sooner rather than later... */
3311         IsUnderPostmaster = true;       /* we are a postmaster subprocess now */
3312
3313         MyProcPid = getpid();           /* reset MyProcPid */
3314
3315         /* Lose the postmaster's on-exit routines (really a no-op) */
3316         on_exit_reset();
3317
3318         /* In EXEC_BACKEND case we will not have inherited these settings */
3319         IsPostmasterEnvironment = true;
3320         whereToSendOutput = DestNone;
3321
3322         /* Setup essential subsystems (to ensure elog() behaves sanely) */
3323         MemoryContextInit();
3324         InitializeGUCOptions();
3325
3326         /* Read in the variables file */
3327         memset(&port, 0, sizeof(Port));
3328         read_backend_variables(argv[2], &port);
3329
3330         /* Check we got appropriate args */
3331         if (argc < 3)
3332                 elog(FATAL, "invalid subpostmaster invocation");
3333
3334         /*
3335          * If appropriate, physically re-attach to shared memory segment. We want
3336          * to do this before going any further to ensure that we can attach at the
3337          * same address the postmaster used.
3338          */
3339         if (strcmp(argv[1], "--forkbackend") == 0 ||
3340                 strcmp(argv[1], "--forkavlauncher") == 0 ||
3341                 strcmp(argv[1], "--forkavworker") == 0 ||
3342                 strcmp(argv[1], "--forkboot") == 0)
3343                 PGSharedMemoryReAttach();
3344
3345         /* autovacuum needs this set before calling InitProcess */
3346         if (strcmp(argv[1], "--forkavlauncher") == 0)
3347                 AutovacuumLauncherIAm();
3348         if (strcmp(argv[1], "--forkavworker") == 0)
3349                 AutovacuumWorkerIAm();
3350
3351         /*
3352          * Start our win32 signal implementation. This has to be done after we
3353          * read the backend variables, because we need to pick up the signal pipe
3354          * from the parent process.
3355          */
3356 #ifdef WIN32
3357         pgwin32_signal_initialize();
3358 #endif
3359
3360         /* In EXEC_BACKEND case we will not have inherited these settings */
3361         pqinitmask();
3362         PG_SETMASK(&BlockSig);
3363
3364         /* Read in remaining GUC variables */
3365         read_nondefault_variables();
3366
3367         /* Run backend or appropriate child */
3368         if (strcmp(argv[1], "--forkbackend") == 0)
3369         {
3370                 Assert(argc == 3);              /* shouldn't be any more args */
3371
3372                 /* Close the postmaster's sockets */
3373                 ClosePostmasterPorts(false);
3374
3375                 /*
3376                  * Need to reinitialize the SSL library in the backend, since the
3377                  * context structures contain function pointers and cannot be passed
3378                  * through the parameter file.
3379                  */
3380 #ifdef USE_SSL
3381                 if (EnableSSL)
3382                         secure_initialize();
3383 #endif
3384
3385                 /*
3386                  * process any libraries that should be preloaded at postmaster start
3387                  *
3388                  * NOTE: we have to re-load the shared_preload_libraries here because
3389                  *               this backend is not fork()ed so we can't inherit any shared
3390                  *               libraries / DLL's from our parent (the postmaster).
3391                  */
3392                 process_shared_preload_libraries();
3393
3394                 /*
3395                  * Perform additional initialization and client authentication.
3396                  *
3397                  * We want to do this before InitProcess() for a couple of reasons: 1.
3398                  * so that we aren't eating up a PGPROC slot while waiting on the
3399                  * client. 2. so that if InitProcess() fails due to being out of
3400                  * PGPROC slots, we have already initialized libpq and are able to
3401                  * report the error to the client.
3402                  */
3403                 BackendInitialize(&port);
3404
3405                 /* Restore basic shared memory pointers */
3406                 InitShmemAccess(UsedShmemSegAddr);
3407
3408                 /* Need a PGPROC to run CreateSharedMemoryAndSemaphores */
3409                 InitProcess();
3410
3411                 /*
3412                  * Attach process to shared data structures.  If testing EXEC_BACKEND
3413                  * on Linux, you must run this as root before starting the postmaster:
3414                  *
3415                  * echo 0 >/proc/sys/kernel/randomize_va_space
3416                  *
3417                  * This prevents a randomized stack base address that causes child
3418                  * shared memory to be at a different address than the parent, making
3419                  * it impossible to attached to shared memory.  Return the value to
3420                  * '1' when finished.
3421                  */
3422                 CreateSharedMemoryAndSemaphores(false, 0);
3423
3424                 /* And run the backend */
3425                 proc_exit(BackendRun(&port));
3426         }
3427         if (strcmp(argv[1], "--forkboot") == 0)
3428         {
3429                 /* Close the postmaster's sockets */
3430                 ClosePostmasterPorts(false);
3431
3432                 /* Restore basic shared memory pointers */
3433                 InitShmemAccess(UsedShmemSegAddr);
3434
3435                 /* Need a PGPROC to run CreateSharedMemoryAndSemaphores */
3436                 InitDummyProcess();
3437
3438                 /* Attach process to shared data structures */
3439                 CreateSharedMemoryAndSemaphores(false, 0);
3440
3441                 BootstrapMain(argc - 2, argv + 2);
3442                 proc_exit(0);
3443         }
3444         if (strcmp(argv[1], "--forkavlauncher") == 0)
3445         {
3446                 /* Close the postmaster's sockets */
3447                 ClosePostmasterPorts(false);
3448
3449                 /* Restore basic shared memory pointers */
3450                 InitShmemAccess(UsedShmemSegAddr);
3451
3452                 /* Need a PGPROC to run CreateSharedMemoryAndSemaphores */
3453                 InitDummyProcess();
3454
3455                 /* Attach process to shared data structures */
3456                 CreateSharedMemoryAndSemaphores(false, 0);
3457
3458                 AutoVacLauncherMain(argc - 2, argv + 2);
3459                 proc_exit(0);
3460         }
3461         if (strcmp(argv[1], "--forkavworker") == 0)
3462         {
3463                 /* Close the postmaster's sockets */
3464                 ClosePostmasterPorts(false);
3465
3466                 /* Restore basic shared memory pointers */
3467                 InitShmemAccess(UsedShmemSegAddr);
3468
3469                 /* Need a PGPROC to run CreateSharedMemoryAndSemaphores */
3470                 InitProcess();
3471
3472                 /* Attach process to shared data structures */
3473                 CreateSharedMemoryAndSemaphores(false, 0);
3474
3475                 AutoVacWorkerMain(argc - 2, argv + 2);
3476                 proc_exit(0);
3477         }
3478         if (strcmp(argv[1], "--forkarch") == 0)
3479         {
3480                 /* Close the postmaster's sockets */
3481                 ClosePostmasterPorts(false);
3482
3483                 /* Do not want to attach to shared memory */
3484
3485                 PgArchiverMain(argc, argv);
3486                 proc_exit(0);
3487         }
3488         if (strcmp(argv[1], "--forkcol") == 0)
3489         {
3490                 /* Close the postmaster's sockets */
3491                 ClosePostmasterPorts(false);
3492
3493                 /* Do not want to attach to shared memory */
3494
3495                 PgstatCollectorMain(argc, argv);
3496                 proc_exit(0);
3497         }
3498         if (strcmp(argv[1], "--forklog") == 0)
3499         {
3500                 /* Close the postmaster's sockets */
3501                 ClosePostmasterPorts(true);
3502
3503                 /* Do not want to attach to shared memory */
3504
3505                 SysLoggerMain(argc, argv);
3506                 proc_exit(0);
3507         }
3508
3509         return 1;                                       /* shouldn't get here */
3510 }
3511 #endif   /* EXEC_BACKEND */
3512
3513
3514 /*
3515  * ExitPostmaster -- cleanup
3516  *
3517  * Do NOT call exit() directly --- always go through here!
3518  */
3519 static void
3520 ExitPostmaster(int status)
3521 {
3522         /* should cleanup shared memory and kill all backends */
3523
3524         /*
3525          * Not sure of the semantics here.      When the Postmaster dies, should the
3526          * backends all be killed? probably not.
3527          *
3528          * MUST         -- vadim 05-10-1999
3529          */
3530
3531         proc_exit(status);
3532 }
3533
3534 /*
3535  * sigusr1_handler - handle signal conditions from child processes
3536  */
3537 static void
3538 sigusr1_handler(SIGNAL_ARGS)
3539 {
3540         int                     save_errno = errno;
3541
3542         PG_SETMASK(&BlockSig);
3543
3544         if (CheckPostmasterSignal(PMSIGNAL_PASSWORD_CHANGE))
3545         {
3546                 /*
3547                  * Authorization file has changed.
3548                  */
3549                 load_role();
3550         }
3551
3552         if (CheckPostmasterSignal(PMSIGNAL_WAKEN_CHILDREN))
3553         {
3554                 /*
3555                  * Send SIGUSR1 to all children (triggers CatchupInterruptHandler).
3556                  * See storage/ipc/sinval[adt].c for the use of this.
3557                  */
3558                 if (Shutdown <= SmartShutdown)
3559                         SignalChildren(SIGUSR1);
3560         }
3561
3562         if (CheckPostmasterSignal(PMSIGNAL_WAKEN_ARCHIVER) &&
3563                 PgArchPID != 0 && Shutdown == NoShutdown)
3564         {
3565                 /*
3566                  * Send SIGUSR1 to archiver process, to wake it up and begin archiving
3567                  * next transaction log file.
3568                  */
3569                 signal_child(PgArchPID, SIGUSR1);
3570         }
3571
3572         if (CheckPostmasterSignal(PMSIGNAL_ROTATE_LOGFILE) &&
3573                 SysLoggerPID != 0)
3574         {
3575                 /* Tell syslogger to rotate logfile */
3576                 signal_child(SysLoggerPID, SIGUSR1);
3577         }
3578
3579         if (CheckPostmasterSignal(PMSIGNAL_START_AUTOVAC_LAUNCHER))
3580         {
3581                 /*
3582                  * Start one iteration of the autovacuum daemon, even if autovacuuming
3583                  * is nominally not enabled.  This is so we can have an active defense
3584                  * against transaction ID wraparound.  We set a flag for the main loop
3585                  * to do it rather than trying to do it here --- this is because the
3586                  * autovac process itself may send the signal, and we want to handle
3587                  * that by launching another iteration as soon as the current one
3588                  * completes.
3589                  */
3590                 start_autovac_launcher = true;
3591         }
3592
3593         /* The autovacuum launcher wants us to start a worker process. */
3594         if (CheckPostmasterSignal(PMSIGNAL_START_AUTOVAC_WORKER))
3595                 StartAutovacuumWorker();
3596
3597         PG_SETMASK(&UnBlockSig);
3598
3599         errno = save_errno;
3600 }
3601
3602
3603 /*
3604  * Dummy signal handler
3605  *
3606  * We use this for signals that we don't actually use in the postmaster,
3607  * but we do use in backends.  If we were to SIG_IGN such signals in the
3608  * postmaster, then a newly started backend might drop a signal that arrives
3609  * before it's able to reconfigure its signal processing.  (See notes in
3610  * tcop/postgres.c.)
3611  */
3612 static void
3613 dummy_handler(SIGNAL_ARGS)
3614 {
3615 }
3616
3617
3618 /*
3619  * CharRemap: given an int in range 0..61, produce textual encoding of it
3620  * per crypt(3) conventions.
3621  */
3622 static char
3623 CharRemap(long ch)
3624 {
3625         if (ch < 0)
3626                 ch = -ch;
3627         ch = ch % 62;
3628
3629         if (ch < 26)
3630                 return 'A' + ch;
3631
3632         ch -= 26;
3633         if (ch < 26)
3634                 return 'a' + ch;
3635
3636         ch -= 26;
3637         return '0' + ch;
3638 }
3639
3640 /*
3641  * RandomSalt
3642  */
3643 static void
3644 RandomSalt(char *cryptSalt, char *md5Salt)
3645 {
3646         long            rand = PostmasterRandom();
3647
3648         cryptSalt[0] = CharRemap(rand % 62);
3649         cryptSalt[1] = CharRemap(rand / 62);
3650
3651         /*
3652          * It's okay to reuse the first random value for one of the MD5 salt
3653          * bytes, since only one of the two salts will be sent to the client.
3654          * After that we need to compute more random bits.
3655          *
3656          * We use % 255, sacrificing one possible byte value, so as to ensure that
3657          * all bits of the random() value participate in the result. While at it,
3658          * add one to avoid generating any null bytes.
3659          */
3660         md5Salt[0] = (rand % 255) + 1;
3661         rand = PostmasterRandom();
3662         md5Salt[1] = (rand % 255) + 1;
3663         rand = PostmasterRandom();
3664         md5Salt[2] = (rand % 255) + 1;
3665         rand = PostmasterRandom();
3666         md5Salt[3] = (rand % 255) + 1;
3667 }
3668
3669 /*
3670  * PostmasterRandom
3671  */
3672 static long
3673 PostmasterRandom(void)
3674 {
3675         static bool initialized = false;
3676
3677         if (!initialized)
3678         {
3679                 Assert(random_seed != 0);
3680                 srandom(random_seed);
3681                 initialized = true;
3682         }
3683
3684         return random();
3685 }
3686
3687 /*
3688  * Count up number of child processes (regular backends only)
3689  */
3690 static int
3691 CountChildren(void)
3692 {
3693         Dlelem     *curr;
3694         int                     cnt = 0;
3695
3696         for (curr = DLGetHead(BackendList); curr; curr = DLGetSucc(curr))
3697                 cnt++;
3698         return cnt;
3699 }
3700
3701
3702 /*
3703  * StartChildProcess -- start a non-backend child process for the postmaster
3704  *
3705  * xlop determines what kind of child will be started.  All child types
3706  * initially go to BootstrapMain, which will handle common setup.
3707  *
3708  * Return value of StartChildProcess is subprocess' PID, or 0 if failed
3709  * to start subprocess.
3710  */
3711 static pid_t
3712 StartChildProcess(int xlop)
3713 {
3714         pid_t           pid;
3715         char       *av[10];
3716         int                     ac = 0;
3717         char            xlbuf[32];
3718
3719         /*
3720          * Set up command-line arguments for subprocess
3721          */
3722         av[ac++] = "postgres";
3723
3724 #ifdef EXEC_BACKEND
3725         av[ac++] = "--forkboot";
3726         av[ac++] = NULL;                        /* filled in by postmaster_forkexec */
3727 #endif
3728
3729         snprintf(xlbuf, sizeof(xlbuf), "-x%d", xlop);
3730         av[ac++] = xlbuf;
3731
3732         av[ac] = NULL;
3733         Assert(ac < lengthof(av));
3734
3735 #ifdef EXEC_BACKEND
3736         pid = postmaster_forkexec(ac, av);
3737 #else                                                   /* !EXEC_BACKEND */
3738         pid = fork_process();
3739
3740         if (pid == 0)                           /* child */
3741         {
3742                 IsUnderPostmaster = true;               /* we are a postmaster subprocess now */
3743
3744                 /* Close the postmaster's sockets */
3745                 ClosePostmasterPorts(false);
3746
3747                 /* Lose the postmaster's on-exit routines and port connections */
3748                 on_exit_reset();
3749
3750                 /* Release postmaster's working memory context */
3751                 MemoryContextSwitchTo(TopMemoryContext);
3752                 MemoryContextDelete(PostmasterContext);
3753                 PostmasterContext = NULL;
3754
3755                 BootstrapMain(ac, av);
3756                 ExitPostmaster(0);
3757         }
3758 #endif   /* EXEC_BACKEND */
3759
3760         if (pid < 0)
3761         {
3762                 /* in parent, fork failed */
3763                 int                     save_errno = errno;
3764
3765                 errno = save_errno;
3766                 switch (xlop)
3767                 {
3768                         case BS_XLOG_STARTUP:
3769                                 ereport(LOG,
3770                                                 (errmsg("could not fork startup process: %m")));
3771                                 break;
3772                         case BS_XLOG_BGWRITER:
3773                                 ereport(LOG,
3774                                    (errmsg("could not fork background writer process: %m")));
3775                                 break;
3776                         default:
3777                                 ereport(LOG,
3778                                                 (errmsg("could not fork process: %m")));
3779                                 break;
3780                 }
3781
3782                 /*
3783                  * fork failure is fatal during startup, but there's no need to choke
3784                  * immediately if starting other child types fails.
3785                  */
3786                 if (xlop == BS_XLOG_STARTUP)
3787                         ExitPostmaster(1);
3788                 return 0;
3789         }
3790
3791         /*
3792          * in parent, successful fork
3793          */
3794         return pid;
3795 }
3796
3797 /*
3798  * StartAutovacuumWorker
3799  *              Start an autovac worker process.
3800  *
3801  * This function is here because it enters the resulting PID into the
3802  * postmaster's private backends list.
3803  *
3804  * NB -- this code very roughly matches BackendStartup.
3805  */
3806 static void
3807 StartAutovacuumWorker(void)
3808 {
3809         Backend    *bn;
3810
3811         /*
3812          * do nothing if not in condition to run a process.  This should not
3813          * actually happen, since the signal is only supposed to be sent by
3814          * autovacuum launcher when it's OK to do it, but test for it just in case.
3815          */
3816         if (StartupPID != 0 || FatalError || Shutdown != NoShutdown)
3817                 return;
3818
3819         bn = (Backend *) malloc(sizeof(Backend));
3820         if (!bn)
3821         {
3822                 ereport(LOG,
3823                                 (errcode(ERRCODE_OUT_OF_MEMORY),
3824                                  errmsg("out of memory")));
3825                 return;
3826         }
3827
3828         bn->pid = StartAutoVacWorker();
3829         bn->is_autovacuum = true;
3830         /* we don't need a cancel key */
3831
3832         if (bn->pid > 0)
3833         {
3834                 DLAddHead(BackendList, DLNewElem(bn));
3835 #ifdef EXEC_BACKEND
3836                 ShmemBackendArrayAdd(bn);
3837 #endif
3838         }
3839         else
3840         {
3841                 /* not much we can do */
3842                 ereport(LOG,
3843                                 (errmsg("could not fork new process for autovacuum: %m")));
3844                 free(bn);
3845         }
3846 }
3847
3848 /*
3849  * Create the opts file
3850  */
3851 static bool
3852 CreateOptsFile(int argc, char *argv[], char *fullprogname)
3853 {
3854         FILE       *fp;
3855         int                     i;
3856
3857 #define OPTS_FILE       "postmaster.opts"
3858
3859         if ((fp = fopen(OPTS_FILE, "w")) == NULL)
3860         {
3861                 elog(LOG, "could not create file \"%s\": %m", OPTS_FILE);
3862                 return false;
3863         }
3864
3865         fprintf(fp, "%s", fullprogname);
3866         for (i = 1; i < argc; i++)
3867                 fprintf(fp, " %s%s%s", SYSTEMQUOTE, argv[i], SYSTEMQUOTE);
3868         fputs("\n", fp);
3869
3870         if (fclose(fp))
3871         {
3872                 elog(LOG, "could not write file \"%s\": %m", OPTS_FILE);
3873                 return false;
3874         }
3875
3876         return true;
3877 }
3878
3879
3880 #ifdef EXEC_BACKEND
3881
3882 /*
3883  * The following need to be available to the save/restore_backend_variables
3884  * functions
3885  */
3886 extern slock_t *ShmemLock;
3887 extern LWLock *LWLockArray;
3888 extern slock_t *ProcStructLock;
3889 extern PROC_HDR *ProcGlobal;
3890 extern PGPROC *DummyProcs;
3891 extern int      pgStatSock;
3892
3893 #ifndef WIN32
3894 #define write_inheritable_socket(dest, src, childpid) (*(dest) = (src))
3895 #define read_inheritable_socket(dest, src) (*(dest) = *(src))
3896 #else
3897 static void write_duplicated_handle(HANDLE * dest, HANDLE src, HANDLE child);
3898 static void write_inheritable_socket(InheritableSocket * dest, SOCKET src,
3899                                                  pid_t childPid);
3900 static void read_inheritable_socket(SOCKET * dest, InheritableSocket * src);
3901 #endif
3902
3903
3904 /* Save critical backend variables into the BackendParameters struct */
3905 #ifndef WIN32
3906 static bool
3907 save_backend_variables(BackendParameters * param, Port *port)
3908 #else
3909 static bool
3910 save_backend_variables(BackendParameters * param, Port *port,
3911                                            HANDLE childProcess, pid_t childPid)
3912 #endif
3913 {
3914         memcpy(&param->port, port, sizeof(Port));
3915         write_inheritable_socket(&param->portsocket, port->sock, childPid);
3916
3917         strlcpy(param->DataDir, DataDir, MAXPGPATH);
3918
3919         memcpy(&param->ListenSocket, &ListenSocket, sizeof(ListenSocket));
3920
3921         param->MyCancelKey = MyCancelKey;
3922
3923         param->UsedShmemSegID = UsedShmemSegID;
3924         param->UsedShmemSegAddr = UsedShmemSegAddr;
3925
3926         param->ShmemLock = ShmemLock;
3927         param->ShmemVariableCache = ShmemVariableCache;
3928         param->ShmemBackendArray = ShmemBackendArray;
3929
3930         param->LWLockArray = LWLockArray;
3931         param->ProcStructLock = ProcStructLock;
3932         param->ProcGlobal = ProcGlobal;
3933         param->DummyProcs = DummyProcs;
3934         write_inheritable_socket(&param->pgStatSock, pgStatSock, childPid);
3935
3936         param->PostmasterPid = PostmasterPid;
3937         param->PgStartTime = PgStartTime;
3938
3939 #ifdef WIN32
3940         param->PostmasterHandle = PostmasterHandle;
3941         write_duplicated_handle(&param->initial_signal_pipe,
3942                                                         pgwin32_create_signal_listener(childPid),
3943                                                         childProcess);
3944 #endif
3945
3946         memcpy(&param->syslogPipe, &syslogPipe, sizeof(syslogPipe));
3947
3948         strlcpy(param->my_exec_path, my_exec_path, MAXPGPATH);
3949
3950         strlcpy(param->pkglib_path, pkglib_path, MAXPGPATH);
3951
3952         strlcpy(param->ExtraOptions, ExtraOptions, MAXPGPATH);
3953
3954         strlcpy(param->lc_collate, setlocale(LC_COLLATE, NULL), LOCALE_NAME_BUFLEN);
3955         strlcpy(param->lc_ctype, setlocale(LC_CTYPE, NULL), LOCALE_NAME_BUFLEN);
3956
3957         return true;
3958 }
3959
3960
3961 #ifdef WIN32
3962 /*
3963  * Duplicate a handle for usage in a child process, and write the child
3964  * process instance of the handle to the parameter file.
3965  */
3966 static void
3967 write_duplicated_handle(HANDLE * dest, HANDLE src, HANDLE childProcess)
3968 {
3969         HANDLE          hChild = INVALID_HANDLE_VALUE;
3970
3971         if (!DuplicateHandle(GetCurrentProcess(),
3972                                                  src,
3973                                                  childProcess,
3974                                                  &hChild,
3975                                                  0,
3976                                                  TRUE,
3977                                                  DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS))
3978                 ereport(ERROR,
3979                                 (errmsg_internal("could not duplicate handle to be written to backend parameter file: error code %d",
3980                                                                  (int) GetLastError())));
3981
3982         *dest = hChild;
3983 }
3984
3985 /*
3986  * Duplicate a socket for usage in a child process, and write the resulting
3987  * structure to the parameter file.
3988  * This is required because a number of LSPs (Layered Service Providers) very
3989  * common on Windows (antivirus, firewalls, download managers etc) break
3990  * straight socket inheritance.
3991  */
3992 static void
3993 write_inheritable_socket(InheritableSocket * dest, SOCKET src, pid_t childpid)
3994 {
3995         dest->origsocket = src;
3996         if (src != 0 && src != -1)
3997         {
3998                 /* Actual socket */
3999                 if (WSADuplicateSocket(src, childpid, &dest->wsainfo) != 0)
4000                         ereport(ERROR,
4001                                         (errmsg("could not duplicate socket %d for use in backend: error code %d",
4002                                                         src, WSAGetLastError())));
4003         }
4004 }
4005
4006 /*
4007  * Read a duplicate socket structure back, and get the socket descriptor.
4008  */
4009 static void
4010 read_inheritable_socket(SOCKET * dest, InheritableSocket * src)
4011 {
4012         SOCKET          s;
4013
4014         if (src->origsocket == -1 || src->origsocket == 0)
4015         {
4016                 /* Not a real socket! */
4017                 *dest = src->origsocket;
4018         }
4019         else
4020         {
4021                 /* Actual socket, so create from structure */
4022                 s = WSASocket(FROM_PROTOCOL_INFO,
4023                                           FROM_PROTOCOL_INFO,
4024                                           FROM_PROTOCOL_INFO,
4025                                           &src->wsainfo,
4026                                           0,
4027                                           0);
4028                 if (s == INVALID_SOCKET)
4029                 {
4030                         write_stderr("could not create inherited socket: error code %d\n",
4031                                                  WSAGetLastError());
4032                         exit(1);
4033                 }
4034                 *dest = s;
4035
4036                 /*
4037                  * To make sure we don't get two references to the same socket, close
4038                  * the original one. (This would happen when inheritance actually
4039                  * works..
4040                  */
4041                 closesocket(src->origsocket);
4042         }
4043 }
4044 #endif
4045
4046 static void
4047 read_backend_variables(char *id, Port *port)
4048 {
4049         BackendParameters param;
4050
4051 #ifndef WIN32
4052         /* Non-win32 implementation reads from file */
4053         FILE       *fp;
4054
4055         /* Open file */
4056         fp = AllocateFile(id, PG_BINARY_R);
4057         if (!fp)
4058         {
4059                 write_stderr("could not read from backend variables file \"%s\": %s\n",
4060                                          id, strerror(errno));
4061                 exit(1);
4062         }
4063
4064         if (fread(&param, sizeof(param), 1, fp) != 1)
4065         {
4066                 write_stderr("could not read from backend variables file \"%s\": %s\n",
4067                                          id, strerror(errno));
4068                 exit(1);
4069         }
4070
4071         /* Release file */
4072         FreeFile(fp);
4073         if (unlink(id) != 0)
4074         {
4075                 write_stderr("could not remove file \"%s\": %s\n",
4076                                          id, strerror(errno));
4077                 exit(1);
4078         }
4079 #else
4080         /* Win32 version uses mapped file */
4081         HANDLE          paramHandle;
4082         BackendParameters *paramp;
4083
4084         paramHandle = (HANDLE) atol(id);
4085         paramp = MapViewOfFile(paramHandle, FILE_MAP_READ, 0, 0, 0);
4086         if (!paramp)
4087         {
4088                 write_stderr("could not map view of backend variables: error code %d\n",
4089                                          (int) GetLastError());
4090                 exit(1);
4091         }
4092
4093         memcpy(&param, paramp, sizeof(BackendParameters));
4094
4095         if (!UnmapViewOfFile(paramp))
4096         {
4097                 write_stderr("could not unmap view of backend variables: error code %d\n",
4098                                          (int) GetLastError());
4099                 exit(1);
4100         }
4101
4102         if (!CloseHandle(paramHandle))
4103         {
4104                 write_stderr("could not close handle to backend parameter variables: error code %d\n",
4105                                          (int) GetLastError());
4106                 exit(1);
4107         }
4108 #endif
4109
4110         restore_backend_variables(&param, port);
4111 }
4112
4113 /* Restore critical backend variables from the BackendParameters struct */
4114 static void
4115 restore_backend_variables(BackendParameters * param, Port *port)
4116 {
4117         memcpy(port, &param->port, sizeof(Port));
4118         read_inheritable_socket(&port->sock, &param->portsocket);
4119
4120         SetDataDir(param->DataDir);
4121
4122         memcpy(&ListenSocket, &param->ListenSocket, sizeof(ListenSocket));
4123
4124         MyCancelKey = param->MyCancelKey;
4125
4126         UsedShmemSegID = param->UsedShmemSegID;
4127         UsedShmemSegAddr = param->UsedShmemSegAddr;
4128
4129         ShmemLock = param->ShmemLock;
4130         ShmemVariableCache = param->ShmemVariableCache;
4131         ShmemBackendArray = param->ShmemBackendArray;
4132
4133         LWLockArray = param->LWLockArray;
4134         ProcStructLock = param->ProcStructLock;
4135         ProcGlobal = param->ProcGlobal;
4136         DummyProcs = param->DummyProcs;
4137         read_inheritable_socket(&pgStatSock, &param->pgStatSock);
4138
4139         PostmasterPid = param->PostmasterPid;
4140         PgStartTime = param->PgStartTime;
4141
4142 #ifdef WIN32
4143         PostmasterHandle = param->PostmasterHandle;
4144         pgwin32_initial_signal_pipe = param->initial_signal_pipe;
4145 #endif
4146
4147         memcpy(&syslogPipe, &param->syslogPipe, sizeof(syslogPipe));
4148
4149         strlcpy(my_exec_path, param->my_exec_path, MAXPGPATH);
4150
4151         strlcpy(pkglib_path, param->pkglib_path, MAXPGPATH);
4152
4153         strlcpy(ExtraOptions, param->ExtraOptions, MAXPGPATH);
4154
4155         setlocale(LC_COLLATE, param->lc_collate);
4156         setlocale(LC_CTYPE, param->lc_ctype);
4157 }
4158
4159
4160 Size
4161 ShmemBackendArraySize(void)
4162 {
4163         return mul_size(NUM_BACKENDARRAY_ELEMS, sizeof(Backend));
4164 }
4165
4166 void
4167 ShmemBackendArrayAllocation(void)
4168 {
4169         Size            size = ShmemBackendArraySize();
4170
4171         ShmemBackendArray = (Backend *) ShmemAlloc(size);
4172         /* Mark all slots as empty */
4173         memset(ShmemBackendArray, 0, size);
4174 }
4175
4176 static void
4177 ShmemBackendArrayAdd(Backend *bn)
4178 {
4179         int                     i;
4180
4181         /* Find an empty slot */
4182         for (i = 0; i < NUM_BACKENDARRAY_ELEMS; i++)
4183         {
4184                 if (ShmemBackendArray[i].pid == 0)
4185                 {
4186                         ShmemBackendArray[i] = *bn;
4187                         return;
4188                 }
4189         }
4190
4191         ereport(FATAL,
4192                         (errmsg_internal("no free slots in shmem backend array")));
4193 }
4194
4195 static void
4196 ShmemBackendArrayRemove(pid_t pid)
4197 {
4198         int                     i;
4199
4200         for (i = 0; i < NUM_BACKENDARRAY_ELEMS; i++)
4201         {
4202                 if (ShmemBackendArray[i].pid == pid)
4203                 {
4204                         /* Mark the slot as empty */
4205                         ShmemBackendArray[i].pid = 0;
4206                         return;
4207                 }
4208         }
4209
4210         ereport(WARNING,
4211                         (errmsg_internal("could not find backend entry with pid %d",
4212                                                          (int) pid)));
4213 }
4214 #endif   /* EXEC_BACKEND */
4215
4216
4217 #ifdef WIN32
4218
4219 /*
4220  * Note: The following three functions must not be interrupted (eg. by
4221  * signals).  As the Postgres Win32 signalling architecture (currently)
4222  * requires polling, or APC checking functions which aren't used here, this
4223  * is not an issue.
4224  *
4225  * We keep two separate arrays, instead of a single array of pid/HANDLE
4226  * structs, to avoid having to re-create a handle array for
4227  * WaitForMultipleObjects on each call to win32_waitpid.
4228  */
4229
4230 static void
4231 win32_AddChild(pid_t pid, HANDLE handle)
4232 {
4233         Assert(win32_childPIDArray && win32_childHNDArray);
4234         if (win32_numChildren < NUM_BACKENDARRAY_ELEMS)
4235         {
4236                 win32_childPIDArray[win32_numChildren] = pid;
4237                 win32_childHNDArray[win32_numChildren] = handle;
4238                 ++win32_numChildren;
4239         }
4240         else
4241                 ereport(FATAL,
4242                                 (errmsg_internal("no room for child entry with pid %lu",
4243                                                                  (unsigned long) pid)));
4244 }
4245
4246 static void
4247 win32_RemoveChild(pid_t pid)
4248 {
4249         int                     i;
4250
4251         Assert(win32_childPIDArray && win32_childHNDArray);
4252
4253         for (i = 0; i < win32_numChildren; i++)
4254         {
4255                 if (win32_childPIDArray[i] == pid)
4256                 {
4257                         CloseHandle(win32_childHNDArray[i]);
4258
4259                         /* Swap last entry into the "removed" one */
4260                         --win32_numChildren;
4261                         win32_childPIDArray[i] = win32_childPIDArray[win32_numChildren];
4262                         win32_childHNDArray[i] = win32_childHNDArray[win32_numChildren];
4263                         return;
4264                 }
4265         }
4266
4267         ereport(WARNING,
4268                         (errmsg_internal("could not find child entry with pid %lu",
4269                                                          (unsigned long) pid)));
4270 }
4271
4272 static pid_t
4273 win32_waitpid(int *exitstatus)
4274 {
4275         /*
4276          * Note: Do NOT use WaitForMultipleObjectsEx, as we don't want to run
4277          * queued APCs here.
4278          */
4279         int                     index;
4280         DWORD           exitCode;
4281         DWORD           ret;
4282         unsigned long offset;
4283
4284         Assert(win32_childPIDArray && win32_childHNDArray);
4285         elog(DEBUG3, "waiting on %lu children", win32_numChildren);
4286
4287         for (offset = 0; offset < win32_numChildren; offset += MAXIMUM_WAIT_OBJECTS)
4288         {
4289                 unsigned long num = Min(MAXIMUM_WAIT_OBJECTS, win32_numChildren - offset);
4290
4291                 ret = WaitForMultipleObjects(num, &win32_childHNDArray[offset], FALSE, 0);
4292                 switch (ret)
4293                 {
4294                         case WAIT_FAILED:
4295                                 ereport(LOG,
4296                                                 (errmsg_internal("failed to wait on %lu of %lu children: error code %d",
4297                                                          num, win32_numChildren, (int) GetLastError())));
4298                                 return -1;
4299
4300                         case WAIT_TIMEOUT:
4301                                 /* No children (in this chunk) have finished */
4302                                 break;
4303
4304                         default:
4305
4306                                 /*
4307                                  * Get the exit code, and return the PID of, the respective
4308                                  * process
4309                                  */
4310                                 index = offset + ret - WAIT_OBJECT_0;
4311                                 Assert(index >= 0 && index < win32_numChildren);
4312                                 if (!GetExitCodeProcess(win32_childHNDArray[index], &exitCode))
4313                                 {
4314                                         /*
4315                                          * If we get this far, this should never happen, but, then
4316                                          * again... No choice other than to assume a catastrophic
4317                                          * failure.
4318                                          */
4319                                         ereport(FATAL,
4320                                         (errmsg_internal("failed to get exit code for child %lu",
4321                                                            (unsigned long) win32_childPIDArray[index])));
4322                                 }
4323                                 *exitstatus = (int) exitCode;
4324                                 return win32_childPIDArray[index];
4325                 }
4326         }
4327
4328         /* No children have finished */
4329         return -1;
4330 }
4331
4332 /*
4333  * Note! Code below executes on separate threads, one for
4334  * each child process created
4335  */
4336 static DWORD WINAPI
4337 win32_sigchld_waiter(LPVOID param)
4338 {
4339         HANDLE          procHandle = (HANDLE) param;
4340
4341         DWORD           r = WaitForSingleObject(procHandle, INFINITE);
4342
4343         if (r == WAIT_OBJECT_0)
4344                 pg_queue_signal(SIGCHLD);
4345         else
4346                 write_stderr("could not wait on child process handle: error code %d\n",
4347                                          (int) GetLastError());
4348         CloseHandle(procHandle);
4349         return 0;
4350 }
4351
4352 #endif   /* WIN32 */