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