1 /*-------------------------------------------------------------------------
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.
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.
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 PROC 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.
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
35 * Portions Copyright (c) 1996-2001, PostgreSQL Global Development Group
36 * Portions Copyright (c) 1994, Regents of the University of California
40 * $Header: /cvsroot/pgsql/src/backend/postmaster/postmaster.c,v 1.253 2001/10/28 06:25:47 momjian Exp $
45 * The Postmaster sets up a few shared memory data structures
46 * for the backends. It should at the very least initialize the
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.
56 * The Postmaster cleans up after backends if they have an emergency
57 * exit and/or core dump.
59 *-------------------------------------------------------------------------
68 #include <sys/types.h>
71 #include <sys/socket.h>
75 #include <sys/param.h>
76 #include <netinet/in.h>
77 #include <arpa/inet.h>
81 #ifdef HAVE_SYS_SELECT_H
82 #include <sys/select.h>
89 #include "catalog/pg_database.h"
90 #include "commands/async.h"
91 #include "lib/dllist.h"
92 #include "libpq/auth.h"
93 #include "libpq/crypt.h"
94 #include "libpq/libpq.h"
95 #include "libpq/pqcomm.h"
96 #include "libpq/pqsignal.h"
97 #include "miscadmin.h"
98 #include "nodes/nodes.h"
99 #include "storage/fd.h"
100 #include "storage/ipc.h"
101 #include "storage/proc.h"
102 #include "access/xlog.h"
103 #include "tcop/tcopprot.h"
104 #include "utils/exc.h"
105 #include "utils/guc.h"
106 #include "utils/memutils.h"
107 #include "utils/ps_status.h"
108 #include "bootstrap/bootstrap.h"
112 #define INVALID_SOCK (-1)
115 #ifdef HAVE_SIGPROCMASK
127 * List of active backends (or child processes anyway; we don't actually
128 * know whether a given child has become a backend or is still in the
129 * authorization phase). This is used mainly to keep track of how many
130 * children we have and send them appropriate signals when necessary.
134 pid_t pid; /* process id of backend */
135 long cancel_key; /* cancel key for cancels for this backend */
138 static Dllist *BackendList;
140 /* The socket number we are listening for connections on */
146 * MaxBackends is the limit on the number of backends we can start.
147 * The default is established by configure, but it can be altered at
148 * postmaster start with the postmaster's -N switch. Note
149 * that a larger MaxBackends value will increase the size of the shared
150 * memory area as well as cause the postmaster to grab more kernel
151 * semaphores, even if you never actually use that many backends.
153 int MaxBackends = DEF_MAXBACKENDS;
156 static char *progname = (char *) NULL;
158 /* flag to indicate that SIGHUP arrived during server loop */
159 static volatile bool got_SIGHUP = false;
164 static int ServerSock_INET = INVALID_SOCK; /* stream socket server */
166 #ifdef HAVE_UNIX_SOCKETS
167 static int ServerSock_UNIX = INVALID_SOCK; /* stream socket server */
171 static SSL_CTX *SSL_context = NULL; /* Global SSL context */
175 * Set by the -o option
177 static char ExtraOptions[MAXPGPATH];
180 * These globals control the behavior of the postmaster in case some
181 * backend dumps core. Normally, it kills all peers of the dead backend
182 * and reinitializes shared memory. By specifying -s or -n, we can have
183 * the postmaster stop (rather than kill) peers and not reinitialize
184 * shared data structures.
186 static bool Reinit = true;
187 static int SendStop = false;
189 /* still more option variables */
190 bool NetServer = false; /* listen on TCP/IP */
191 bool EnableSSL = false;
192 bool SilentMode = false; /* silent mode (-S) */
194 int PreAuthDelay = 0;
195 int AuthenticationTimeout = 60;
196 int CheckPointTimeout = 300;
198 bool HostnameLookup; /* for ps display */
200 bool Log_connections = false;
202 /* Startup/shutdown state */
203 static pid_t StartupPID = 0,
206 static time_t checkpointed = 0;
209 #define SmartShutdown 1
210 #define FastShutdown 2
212 static int Shutdown = NoShutdown;
214 static bool FatalError = false; /* T if recovering from backend crash */
217 * State for assigning random salts and cancel keys.
218 * Also, the global MyCancelKey passes the cancel key assigned to a given
219 * backend from the postmaster to that backend (via fork).
222 static unsigned int random_seed = 0;
228 #ifdef HAVE_INT_OPTRESET
233 * postmaster.c - function prototypes
235 static void pmdaemonize(int argc, char *argv[]);
236 static Port *ConnCreate(int serverFd);
237 static void ConnFree(Port *port);
238 static void reset_shared(unsigned short port);
239 static void SIGHUP_handler(SIGNAL_ARGS);
240 static void pmdie(SIGNAL_ARGS);
241 static void reaper(SIGNAL_ARGS);
242 static void schedule_checkpoint(SIGNAL_ARGS);
243 static void CleanupProc(int pid, int exitstatus);
244 static int DoBackend(Port *port);
245 static void ExitPostmaster(int status);
246 static void usage(const char *);
247 static int ServerLoop(void);
248 static int BackendStartup(Port *port);
249 static int ProcessStartupPacket(Port *port, bool SSLdone);
250 static void processCancelRequest(Port *port, void *pkt);
251 static int initMasks(fd_set *rmask, fd_set *wmask);
254 CAC_OK, CAC_STARTUP, CAC_SHUTDOWN, CAC_RECOVERY, CAC_TOOMANY
256 static enum CAC_state canAcceptConnections(void);
257 static long PostmasterRandom(void);
258 static void RandomSalt(char *cryptSalt, char *md5Salt);
259 static void SignalChildren(int signal);
260 static int CountChildren(void);
261 static bool CreateOptsFile(int argc, char *argv[]);
262 static pid_t SSDataBase(int xlop);
264 postmaster_error(const char *fmt,...)
265 /* This lets gcc check the format string for consistency. */
266 __attribute__((format(printf, 1, 2)));
268 #define StartupDataBase() SSDataBase(BS_XLOG_STARTUP)
269 #define CheckPointDataBase() SSDataBase(BS_XLOG_CHECKPOINT)
270 #define ShutdownDataBase() SSDataBase(BS_XLOG_SHUTDOWN)
273 static void InitSSL(void);
278 checkDataDir(const char *checkdir)
280 char path[MAXPGPATH];
282 struct stat stat_buf;
284 if (checkdir == NULL)
286 fprintf(stderr, gettext(
287 "%s does not know where to find the database system data.\n"
288 "You must specify the directory that contains the database system\n"
289 "either by specifying the -D invocation option or by setting the\n"
290 "PGDATA environment variable.\n\n"),
296 * Check if the directory has group or world access. If so, reject.
298 if (stat(checkdir, &stat_buf) == -1)
301 elog(FATAL, "data directory %s was not found", checkdir);
303 elog(FATAL, "could not read permissions of directory %s: %m",
307 if (stat_buf.st_mode & (S_IRWXG | S_IRWXO))
308 elog(FATAL, "data directory %s has group or world access; permissions should be u=rwx (0700)",
311 /* Look for PG_VERSION before looking for pg_control */
312 ValidatePgVersion(checkdir);
314 snprintf(path, sizeof(path), "%s/global/pg_control", checkdir);
316 fp = AllocateFile(path, PG_BINARY_R);
319 fprintf(stderr, gettext(
320 "%s does not find the database system.\n"
321 "Expected to find it in the PGDATA directory \"%s\",\n"
322 "but unable to open file \"%s\": %s\n\n"),
323 progname, checkdir, path, strerror(errno));
331 PostmasterMain(int argc, char *argv[])
335 char original_extraoptions[MAXPGPATH];
336 char *potential_DataDir = NULL;
338 *original_extraoptions = '\0';
343 * Catch standard options before doing much else. This even works on
344 * systems without getopt_long.
348 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
353 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
355 puts("postmaster (PostgreSQL) " PG_VERSION);
361 * for security, no dir or file created can be group or other
364 umask((mode_t) 0077);
366 MyProcPid = getpid();
369 * Fire up essential subsystems: error and memory management
371 EnableExceptionHandling(true);
375 * By default, palloc() requests in the postmaster will be allocated
376 * in the PostmasterContext, which is space that can be recycled by
377 * backends. Allocated data that needs to be available to backends
378 * should be allocated in TopMemoryContext.
380 PostmasterContext = AllocSetContextCreate(TopMemoryContext,
382 ALLOCSET_DEFAULT_MINSIZE,
383 ALLOCSET_DEFAULT_INITSIZE,
384 ALLOCSET_DEFAULT_MAXSIZE);
385 MemoryContextSwitchTo(PostmasterContext);
390 ResetAllOptions(true);
392 /* PGPORT environment variable, if set, overrides GUC setting */
393 if (getenv("PGPORT"))
394 SetConfigOption("port", getenv("PGPORT"), PGC_POSTMASTER, true);
396 potential_DataDir = getenv("PGDATA"); /* default value */
399 * First we must scan for a -D argument to get the data dir. Then read
400 * the config file. Finally, scan all the other arguments. (Command
401 * line switches override config file.)
403 * Note: The two lists of options must be exactly the same, even though
404 * perhaps the first one would only have to be "D:" with opterr turned
405 * off. But some versions of getopt (notably GNU) are going to
406 * arbitrarily permute some "non-options" (according to the local
407 * world view) which will result in some switches being associated
408 * with the wrong argument. Death and destruction will occur.
411 while ((opt = getopt(argc, argv, "A:a:B:b:c:D:d:Fh:ik:lm:MN:no:p:Ss-:")) != EOF)
416 potential_DataDir = optarg;
420 fprintf(stderr, gettext("Try '%s --help' for more information.\n"), progname);
426 * Postmaster accepts no non-option switch arguments.
430 postmaster_error("invalid argument -- %s", argv[optind]);
431 fprintf(stderr, gettext("Try '%s --help' for more information.\n"),
436 checkDataDir(potential_DataDir); /* issues error messages */
437 SetDataDir(potential_DataDir);
439 ProcessConfigFile(PGC_POSTMASTER);
441 IgnoreSystemIndexes(false);
443 /* reset getopt(3) to rescan arguments */
445 #ifdef HAVE_INT_OPTRESET
446 optreset = 1; /* some systems need this too */
449 while ((opt = getopt(argc, argv, "A:a:B:b:c:D:d:Fh:ik:lm:MN:no:p:Ss-:")) != EOF)
454 #ifdef USE_ASSERT_CHECKING
455 SetConfigOption("debug_assertions", optarg, PGC_POSTMASTER, true);
457 postmaster_error("Assert checking is not compiled in.");
461 /* Can no longer set authentication method. */
464 SetConfigOption("shared_buffers", optarg, PGC_POSTMASTER, true);
467 /* Can no longer set the backend executable file to use. */
470 /* already done above */
475 * Turn on debugging for the postmaster and the backend
476 * servers descended from it.
478 SetConfigOption("debug_level", optarg, PGC_POSTMASTER, true);
481 SetConfigOption("fsync", "false", PGC_POSTMASTER, true);
484 SetConfigOption("virtual_host", optarg, PGC_POSTMASTER, true);
487 SetConfigOption("tcpip_socket", "true", PGC_POSTMASTER, true);
490 SetConfigOption("unix_socket_directory", optarg, PGC_POSTMASTER, true);
494 SetConfigOption("ssl", "true", PGC_POSTMASTER, true);
498 /* Multiplexed backends no longer supported. */
503 * ignore this flag. This may be passed in because the
504 * program was run as 'postgres -M' instead of
509 /* The max number of backends to start. */
510 SetConfigOption("max_connections", optarg, PGC_POSTMASTER, true);
513 /* Don't reinit shared mem after abnormal exit */
519 * Other options to pass to the backend on the command
520 * line -- useful only for debugging.
522 strcat(ExtraOptions, " ");
523 strcat(ExtraOptions, optarg);
524 strcpy(original_extraoptions, optarg);
527 SetConfigOption("port", optarg, PGC_POSTMASTER, true);
532 * Start in 'S'ilent mode (disassociate from controlling
533 * tty). You may also think of this as 'S'ysV mode since
534 * it's most badly needed on SysV-derived systems like
537 SetConfigOption("silent_mode", "true", PGC_POSTMASTER, true);
542 * In the event that some backend dumps core, send
543 * SIGSTOP, rather than SIGQUIT, to all its peers. This
544 * lets the wily post_hacker collect core dumps from
555 ParseLongOption(optarg, &name, &value);
559 elog(ERROR, "--%s requires argument", optarg);
561 elog(ERROR, "-c %s requires argument", optarg);
564 SetConfigOption(name, value, PGC_POSTMASTER, true);
572 /* shouldn't get here */
573 fprintf(stderr, gettext("Try '%s --help' for more information.\n"), progname);
579 * Check for invalid combinations of switches
581 if (NBuffers < 2 * MaxBackends || NBuffers < 16)
584 * Do not accept -B so small that backends are likely to starve
585 * for lack of buffers. The specific choices here are somewhat
588 postmaster_error("The number of buffers (-B) must be at least twice the number of allowed connections (-N) and at least 16.");
593 * Now that we are done processing the postmaster arguments, reset
594 * getopt(3) library so that it will work correctly in subprocesses.
597 #ifdef HAVE_INT_OPTRESET
598 optreset = 1; /* some systems need this too */
601 /* For debugging: display postmaster environment */
604 extern char **environ;
607 fprintf(stderr, "%s: PostmasterMain: initial environ dump:\n",
609 fprintf(stderr, "-----------------------------------------\n");
610 for (p = environ; *p; ++p)
611 fprintf(stderr, "\t%s\n", *p);
612 fprintf(stderr, "-----------------------------------------\n");
616 * On some systems our dynloader code needs the executable's pathname.
618 if (FindExec(pg_pathname, progname, "postgres") < 0)
619 elog(FATAL, "%s: could not locate executable, bailing out...",
623 * Initialize SSL library, if specified.
626 if (EnableSSL && !NetServer)
628 postmaster_error("For SSL, TCP/IP connections must be enabled.");
629 fprintf(stderr, gettext("Try '%s --help' for more information.\n"), progname);
637 * Fork away from controlling terminal, if -S specified.
639 * Must do this before we grab any interlock files, else the interlocks
640 * will show the wrong PID.
643 pmdaemonize(argc, argv);
646 * Create lockfile for data directory.
648 * We want to do this before we try to grab the input sockets, because
649 * the data directory interlock is more reliable than the socket-file
650 * interlock (thanks to whoever decided to put socket files in /tmp
651 * :-(). For the same reason, it's best to grab the TCP socket before
654 if (!CreateDataDirLockFile(DataDir, true))
658 * Remove old temporary files. At this point there can be no other
659 * Postgres processes running in this directory, so this should be
665 * Establish input sockets.
669 status = StreamServerPort(AF_INET, VirtualHost,
670 (unsigned short) PostPortNumber,
673 if (status != STATUS_OK)
675 postmaster_error("cannot create INET stream port");
680 #ifdef HAVE_UNIX_SOCKETS
681 status = StreamServerPort(AF_UNIX, VirtualHost,
682 (unsigned short) PostPortNumber,
685 if (status != STATUS_OK)
687 postmaster_error("cannot create UNIX stream port");
695 * Set up shared memory and semaphores.
697 reset_shared(PostPortNumber);
700 * Initialize the list of active backends.
702 BackendList = DLNewList();
705 * Record postmaster options. We delay this till now to avoid
706 * recording bogus options (eg, NBuffers too high for available
709 if (!CreateOptsFile(argc, argv))
713 * Set up signal handlers for the postmaster process.
716 PG_SETMASK(&BlockSig);
718 pqsignal(SIGHUP, SIGHUP_handler); /* reread config file and have
719 * children do same */
720 pqsignal(SIGINT, pmdie); /* send SIGTERM and ShutdownDataBase */
721 pqsignal(SIGQUIT, pmdie); /* send SIGQUIT and die */
722 pqsignal(SIGTERM, pmdie); /* wait for children and ShutdownDataBase */
723 pqsignal(SIGALRM, SIG_IGN); /* ignored */
724 pqsignal(SIGPIPE, SIG_IGN); /* ignored */
725 pqsignal(SIGUSR1, schedule_checkpoint); /* start a background
727 pqsignal(SIGUSR2, pmdie); /* send SIGUSR2, don't die */
728 pqsignal(SIGCHLD, reaper); /* handle child termination */
729 pqsignal(SIGTTIN, SIG_IGN); /* ignored */
730 pqsignal(SIGTTOU, SIG_IGN); /* ignored */
733 * Reset whereToSendOutput from Debug (its starting state) to None.
734 * This prevents elog from sending messages to stderr unless the
735 * syslog/stderr switch permits. We don't do this until the
736 * postmaster is fully launched, since startup failures may as well be
737 * reported to stderr.
739 whereToSendOutput = None;
742 * Initialize and startup the statistics collector process
744 if (pgstat_init() < 0)
746 if (pgstat_start() < 0)
750 * We're ready to rock and roll...
752 StartupPID = StartupDataBase();
754 status = ServerLoop();
757 * ServerLoop probably shouldn't ever return, but if it does, close
760 ExitPostmaster(status != STATUS_OK);
762 return 0; /* not reached */
766 pmdaemonize(int argc, char *argv[])
772 if (pid == (pid_t) -1)
774 postmaster_error("fork failed: %s", strerror(errno));
776 return; /* not reached */
780 /* Parent should just exit, without doing any atexit cleanup */
784 MyProcPid = getpid(); /* reset MyProcPid to child */
786 /* GH: If there's no setsid(), we hopefully don't need silent mode.
787 * Until there's a better solution.
792 postmaster_error("cannot disassociate from controlling TTY: %s",
797 i = open(NULL_DEV, O_RDWR | PG_BINARY);
807 * Print out help message
810 usage(const char *progname)
812 printf(gettext("%s is the PostgreSQL server.\n\n"), progname);
813 printf(gettext("Usage:\n %s [options...]\n\n"), progname);
814 printf(gettext("Options:\n"));
815 #ifdef USE_ASSERT_CHECKING
816 printf(gettext(" -A 1|0 enable/disable run-time assert checking\n"));
818 printf(gettext(" -B NBUFFERS number of shared buffers (default %d)\n"), DEF_NBUFFERS);
819 printf(gettext(" -c NAME=VALUE set run-time parameter\n"));
820 printf(gettext(" -d 1-5 debugging level\n"));
821 printf(gettext(" -D DATADIR database directory\n"));
822 printf(gettext(" -F turn fsync off\n"));
823 printf(gettext(" -h HOSTNAME host name or IP address to listen on\n"));
824 printf(gettext(" -i enable TCP/IP connections\n"));
825 printf(gettext(" -k DIRECTORY Unix-domain socket location\n"));
827 printf(gettext(" -l enable SSL connections\n"));
829 printf(gettext(" -N MAX-CONNECT maximum number of allowed connections (default %d)\n"),
831 printf(gettext(" -o OPTIONS pass 'OPTIONS' to each backend server\n"));
832 printf(gettext(" -p PORT port number to listen on (default %d)\n"), DEF_PGPORT);
833 printf(gettext(" -S silent mode (start in background without logging output)\n"));
835 printf(gettext("\nDeveloper options:\n"));
836 printf(gettext(" -n do not reinitialize shared memory after abnormal exit\n"));
837 printf(gettext(" -s send SIGSTOP to all backend servers if one dies\n"));
839 printf(gettext("\nPlease read the documentation for the complete list of run-time\n"
840 "configuration settings and how to set them on the command line or in\n"
841 "the configuration file.\n\n"
842 "Report bugs to <pgsql-bugs@postgresql.org>.\n"));
855 load_hba_and_ident();
857 gettimeofday(&now, &tz);
859 nSockets = initMasks(&readmask, &writemask);
866 struct timeval *timeout = NULL;
867 struct timeval timeout_tv;
869 if (CheckPointPID == 0 && checkpointed &&
870 Shutdown == NoShutdown && !FatalError && random_seed != 0)
872 time_t now = time(NULL);
874 if (CheckPointTimeout + checkpointed > now)
877 * Not time for checkpoint yet, so set a timeout for
880 timeout_tv.tv_sec = CheckPointTimeout + checkpointed - now;
881 timeout_tv.tv_usec = 0;
882 timeout = &timeout_tv;
886 /* Time to make the checkpoint... */
887 CheckPointPID = CheckPointDataBase();
890 * if fork failed, schedule another try at 0.1 normal
893 if (CheckPointPID == 0)
894 checkpointed = now - (9 * CheckPointTimeout) / 10;
899 * Wait for something to happen.
901 memcpy((char *) &rmask, (char *) &readmask, sizeof(fd_set));
902 memcpy((char *) &wmask, (char *) &writemask, sizeof(fd_set));
904 PG_SETMASK(&UnBlockSig);
906 if (select(nSockets, &rmask, &wmask, (fd_set *) NULL, timeout) < 0)
908 PG_SETMASK(&BlockSig);
909 if (errno == EINTR || errno == EWOULDBLOCK)
911 elog(DEBUG, "ServerLoop: select failed: %s", strerror(errno));
916 * Block all signals until we wait again
918 PG_SETMASK(&BlockSig);
921 * Respond to signals, if needed
926 ProcessConfigFile(PGC_SIGHUP);
927 load_hba_and_ident();
931 * Select a random seed at the time of first receiving a request.
933 while (random_seed == 0)
935 gettimeofday(&later, &tz);
938 * We are not sure how much precision is in tv_usec, so we
939 * swap the nibbles of 'later' and XOR them with 'now'. On the
940 * off chance that the result is 0, we loop until it isn't.
942 random_seed = now.tv_usec ^
943 ((later.tv_usec << 16) |
944 ((later.tv_usec >> 16) & 0xffff));
948 * New connection pending on our well-known port's socket? If so,
949 * fork a child process to deal with it.
952 #ifdef HAVE_UNIX_SOCKETS
953 if (ServerSock_UNIX != INVALID_SOCK
954 && FD_ISSET(ServerSock_UNIX, &rmask))
956 port = ConnCreate(ServerSock_UNIX);
959 BackendStartup(port);
962 * We no longer need the open socket or port structure in
965 StreamClose(port->sock);
971 if (ServerSock_INET != INVALID_SOCK
972 && FD_ISSET(ServerSock_INET, &rmask))
974 port = ConnCreate(ServerSock_INET);
977 BackendStartup(port);
980 * We no longer need the open socket or port structure in
983 StreamClose(port->sock);
992 * Initialise the read and write masks for select() for the well-known ports
993 * we are listening on. Return the number of sockets to listen on.
997 initMasks(fd_set *rmask, fd_set *wmask)
1004 #ifdef HAVE_UNIX_SOCKETS
1005 if (ServerSock_UNIX != INVALID_SOCK)
1007 FD_SET(ServerSock_UNIX, rmask);
1009 if (ServerSock_UNIX > nsocks)
1010 nsocks = ServerSock_UNIX;
1014 if (ServerSock_INET != INVALID_SOCK)
1016 FD_SET(ServerSock_INET, rmask);
1017 if (ServerSock_INET > nsocks)
1018 nsocks = ServerSock_INET;
1026 * Read the startup packet and do something according to it.
1028 * Returns STATUS_OK or STATUS_ERROR, or might call elog(FATAL) and
1029 * not return at all.
1031 * (Note that elog(FATAL) stuff is sent to the client, so only use it
1032 * if that's what you want. Return STATUS_ERROR if you don't want to
1033 * send anything to the client, which would typically be appropriate
1034 * if we detect a communications failure.)
1037 ProcessStartupPacket(Port *port, bool SSLdone)
1039 StartupPacket *packet;
1044 if (pq_getbytes((char *) &len, 4) == EOF)
1046 elog(DEBUG, "incomplete startup packet");
1047 return STATUS_ERROR;
1053 if (len < sizeof(len) || len > sizeof(len) + sizeof(StartupPacket))
1054 elog(FATAL, "invalid length of startup packet");
1058 if (pq_getbytes(buf, len) == EOF)
1060 elog(DEBUG, "incomplete startup packet");
1061 return STATUS_ERROR;
1067 * The first field is either a protocol version number or a special
1070 port->proto = ntohl(packet->protoVersion);
1072 if (port->proto == CANCEL_REQUEST_CODE)
1074 processCancelRequest(port, packet);
1075 return 127; /* XXX */
1078 if (port->proto == NEGOTIATE_SSL_CODE && !SSLdone)
1083 /* No SSL when disabled or on Unix sockets */
1084 if (!EnableSSL || port->laddr.sa.sa_family != AF_INET)
1087 SSLok = 'S'; /* Support for SSL */
1089 SSLok = 'N'; /* No support for SSL */
1091 if (send(port->sock, &SSLok, 1, 0) != 1)
1093 elog(DEBUG, "failed to send SSL negotiation response: %s",
1095 return STATUS_ERROR; /* close the connection */
1101 if (!(port->ssl = SSL_new(SSL_context)) ||
1102 !SSL_set_fd(port->ssl, port->sock) ||
1103 SSL_accept(port->ssl) <= 0)
1105 elog(DEBUG, "failed to initialize SSL connection: %s (%s)",
1106 ERR_reason_error_string(ERR_get_error()), strerror(errno));
1107 return STATUS_ERROR;
1111 /* regular startup packet, cancel, etc packet should follow... */
1112 /* but not another SSL negotiation request */
1113 return ProcessStartupPacket(port, true);
1116 /* Could add additional special packet types here */
1119 /* Check we can handle the protocol the frontend is using. */
1121 if (PG_PROTOCOL_MAJOR(port->proto) < PG_PROTOCOL_MAJOR(PG_PROTOCOL_EARLIEST) ||
1122 PG_PROTOCOL_MAJOR(port->proto) > PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST) ||
1123 (PG_PROTOCOL_MAJOR(port->proto) == PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST) &&
1124 PG_PROTOCOL_MINOR(port->proto) > PG_PROTOCOL_MINOR(PG_PROTOCOL_LATEST)))
1125 elog(FATAL, "unsupported frontend protocol");
1128 * Get the parameters from the startup packet as C strings. The
1129 * packet destination was cleared first so a short packet has zeros
1130 * silently added and a long packet is silently truncated.
1132 StrNCpy(port->database, packet->database, sizeof(port->database));
1133 StrNCpy(port->user, packet->user, sizeof(port->user));
1134 StrNCpy(port->options, packet->options, sizeof(port->options));
1135 StrNCpy(port->tty, packet->tty, sizeof(port->tty));
1137 /* The database defaults to the user name. */
1138 if (port->database[0] == '\0')
1139 StrNCpy(port->database, packet->user, sizeof(port->database));
1142 * Truncate given database and user names to length of a Postgres
1143 * name. This avoids lookup failures when overlength names are given.
1145 if ((int) sizeof(port->database) >= NAMEDATALEN)
1146 port->database[NAMEDATALEN - 1] = '\0';
1147 if ((int) sizeof(port->user) >= NAMEDATALEN)
1148 port->user[NAMEDATALEN - 1] = '\0';
1150 /* Check a user name was given. */
1151 if (port->user[0] == '\0')
1152 elog(FATAL, "no PostgreSQL user name specified in startup packet");
1155 * If we're going to reject the connection due to database state, say
1156 * so now instead of wasting cycles on an authentication exchange.
1157 * (This also allows a pg_ping utility to be written.)
1159 cac = canAcceptConnections();
1164 elog(FATAL, "The database system is starting up");
1167 elog(FATAL, "The database system is shutting down");
1170 elog(FATAL, "The database system is in recovery mode");
1173 elog(FATAL, "Sorry, too many clients already");
1185 * The client has sent a cancel request packet, not a normal
1186 * start-a-new-connection packet. Perform the necessary processing.
1187 * Nothing is sent back to the client.
1190 processCancelRequest(Port *port, void *pkt)
1192 CancelRequestPacket *canc = (CancelRequestPacket *) pkt;
1194 long cancelAuthCode;
1198 backendPID = (int) ntohl(canc->backendPID);
1199 cancelAuthCode = (long) ntohl(canc->cancelAuthCode);
1201 if (backendPID == CheckPointPID)
1204 elog(DEBUG, "processCancelRequest: CheckPointPID in cancel request for process %d", backendPID);
1208 /* See if we have a matching backend */
1210 for (curr = DLGetHead(BackendList); curr; curr = DLGetSucc(curr))
1212 bp = (Backend *) DLE_VAL(curr);
1213 if (bp->pid == backendPID)
1215 if (bp->cancel_key == cancelAuthCode)
1217 /* Found a match; signal that backend to cancel current op */
1219 elog(DEBUG, "processing cancel request: sending SIGINT to process %d",
1221 kill(bp->pid, SIGINT);
1225 /* Right PID, wrong key: no way, Jose */
1227 elog(DEBUG, "bad key in cancel request for process %d",
1234 /* No matching backend */
1236 elog(DEBUG, "bad pid in cancel request for process %d", backendPID);
1240 * canAcceptConnections --- check to see if database state allows connections.
1242 static enum CAC_state
1243 canAcceptConnections(void)
1245 /* Can't start backends when in startup/shutdown/recovery state. */
1246 if (Shutdown > NoShutdown)
1247 return CAC_SHUTDOWN;
1251 return CAC_RECOVERY;
1254 * Don't start too many children.
1256 * We allow more connections than we can have backends here because some
1257 * might still be authenticating; they might fail auth, or some
1258 * existing backend might exit before the auth cycle is completed. The
1259 * exact MaxBackends limit is enforced when a new backend tries to
1260 * join the shared-inval backend array.
1262 if (CountChildren() >= 2 * MaxBackends)
1270 * ConnCreate -- create a local connection data structure
1273 ConnCreate(int serverFd)
1277 if (!(port = (Port *) calloc(1, sizeof(Port))))
1279 elog(DEBUG, "ConnCreate: malloc failed");
1280 SignalChildren(SIGQUIT);
1284 if (StreamConnection(serverFd, port) != STATUS_OK)
1286 StreamClose(port->sock);
1293 * Precompute password salt values to use for this connection.
1294 * It's slightly annoying to do this long in advance of knowing
1295 * whether we'll need 'em or not, but we must do the random()
1296 * calls before we fork, not after. Else the postmaster's random
1297 * sequence won't get advanced, and all backends would end up
1298 * using the same salt...
1300 RandomSalt(port->cryptSalt, port->md5Salt);
1301 port->pktInfo.state = Idle;
1309 * ConnFree -- free a local connection data structure
1312 ConnFree(Port *conn)
1316 SSL_free(conn->ssl);
1323 * ClosePostmasterPorts -- close all the postmaster's open sockets
1325 * This is called during child process startup to release file descriptors
1326 * that are not needed by that child process. The postmaster still has
1327 * them open, of course.
1330 ClosePostmasterPorts(bool pgstat_too)
1332 /* Close the listen sockets */
1334 StreamClose(ServerSock_INET);
1335 ServerSock_INET = INVALID_SOCK;
1336 #ifdef HAVE_UNIX_SOCKETS
1337 StreamClose(ServerSock_UNIX);
1338 ServerSock_UNIX = INVALID_SOCK;
1340 /* Close pgstat control sockets, unless we're starting pgstat itself */
1342 pgstat_close_sockets();
1347 * reset_shared -- reset shared memory and semaphores
1350 reset_shared(unsigned short port)
1353 * Reset assignment of shared mem and semaphore IPC keys. Doing this
1354 * means that in normal cases we'll assign the same keys on each
1355 * "cycle of life", and thereby avoid leaving dead IPC objects
1356 * floating around if the postmaster crashes and is restarted.
1358 IpcInitKeyAssignment(port);
1361 * Create or re-create shared memory and semaphores.
1363 CreateSharedMemoryAndSemaphores(false, MaxBackends);
1368 * Set flag if SIGHUP was detected so config file can be reread in
1372 SIGHUP_handler(SIGNAL_ARGS)
1374 int save_errno = errno;
1376 PG_SETMASK(&BlockSig);
1378 if (Shutdown <= SmartShutdown)
1381 SignalChildren(SIGHUP);
1390 * pmdie -- signal handler for processing various postmaster signals.
1395 int save_errno = errno;
1397 PG_SETMASK(&BlockSig);
1400 elog(DEBUG, "pmdie %d", postgres_signal_arg);
1402 switch (postgres_signal_arg)
1407 * Send SIGUSR2 to all children (AsyncNotifyHandler)
1409 if (Shutdown > SmartShutdown)
1414 SignalChildren(SIGUSR2);
1423 * Wait for children to end their work and ShutdownDataBase.
1425 if (Shutdown >= SmartShutdown)
1430 Shutdown = SmartShutdown;
1431 elog(DEBUG, "smart shutdown request");
1432 if (DLGetHead(BackendList)) /* let reaper() handle this */
1439 * No children left. Shutdown data base system.
1441 if (StartupPID > 0 || FatalError) /* let reaper() handle
1447 if (ShutdownPID > 0)
1449 elog(REALLYFATAL, "shutdown process %d already running",
1454 ShutdownPID = ShutdownDataBase();
1463 * abort all children with SIGTERM (rollback active transactions
1464 * and exit) and ShutdownDataBase when they are gone.
1466 if (Shutdown >= FastShutdown)
1471 elog(DEBUG, "fast shutdown request");
1472 if (DLGetHead(BackendList)) /* let reaper() handle this */
1474 Shutdown = FastShutdown;
1477 elog(DEBUG, "aborting any active transactions");
1478 SignalChildren(SIGTERM);
1483 if (Shutdown > NoShutdown)
1485 Shutdown = FastShutdown;
1489 Shutdown = FastShutdown;
1492 * No children left. Shutdown data base system.
1494 if (StartupPID > 0 || FatalError) /* let reaper() handle
1500 if (ShutdownPID > 0)
1502 elog(REALLYFATAL, "shutdown process %d already running",
1507 ShutdownPID = ShutdownDataBase();
1514 * Immediate Shutdown:
1516 * abort all children with SIGQUIT and exit without attempt to
1517 * properly shutdown data base system.
1519 elog(DEBUG, "immediate shutdown request");
1520 if (ShutdownPID > 0)
1521 kill(ShutdownPID, SIGQUIT);
1523 kill(StartupPID, SIGQUIT);
1524 if (DLGetHead(BackendList))
1525 SignalChildren(SIGQUIT);
1529 /* exit postmaster */
1534 * Reaper -- signal handler to cleanup after a backend (child) dies.
1539 int save_errno = errno;
1542 int status; /* backend exit status */
1545 union wait status; /* backend exit status */
1548 int pid; /* process id of dead backend */
1550 PG_SETMASK(&BlockSig);
1551 /* It's not really necessary to reset the handler each time is it? */
1552 pqsignal(SIGCHLD, reaper);
1555 elog(DEBUG, "reaping dead processes");
1557 while ((pid = waitpid(-1, &status, WNOHANG)) > 0)
1559 exitstatus = status;
1561 while ((pid = wait3(&status, WNOHANG, NULL)) > 0)
1563 exitstatus = status.w_status;
1567 * Check if this child was the statistics collector. If so, start
1570 if (pgstat_ispgstat(pid))
1572 if (WIFEXITED(exitstatus))
1573 elog(DEBUG, "statistics collector exited with status %d",
1574 WEXITSTATUS(exitstatus));
1575 else if (WIFSIGNALED(exitstatus))
1576 elog(DEBUG, "statistics collector was terminated by signal %d",
1577 WTERMSIG(exitstatus));
1582 if (ShutdownPID > 0 && pid == ShutdownPID)
1584 if (WIFEXITED(exitstatus) && WEXITSTATUS(exitstatus) != 0)
1586 elog(DEBUG, "shutdown process %d exited with status %d",
1587 pid, WEXITSTATUS(exitstatus));
1590 if (WIFSIGNALED(exitstatus))
1592 elog(DEBUG, "shutdown process %d was terminated by signal %d",
1593 pid, WTERMSIG(exitstatus));
1599 if (StartupPID > 0 && pid == StartupPID)
1601 if (WIFEXITED(exitstatus) && WEXITSTATUS(exitstatus) != 0)
1603 elog(DEBUG, "startup process %d exited with status %d; aborting startup",
1604 pid, WEXITSTATUS(exitstatus));
1607 if (WIFSIGNALED(exitstatus))
1609 elog(DEBUG, "shutdown process %d was terminated by signal %d; aborting startup",
1610 pid, WTERMSIG(exitstatus));
1615 FatalError = false; /* done with recovery */
1616 if (Shutdown > NoShutdown)
1618 if (ShutdownPID > 0)
1620 elog(STOP, "startup process %d died while shutdown process %d already running",
1624 ShutdownPID = ShutdownDataBase();
1628 * Startup succeeded - remember its ID and RedoRecPtr
1633 * Arrange for first checkpoint to occur after standard delay.
1636 checkpointed = time(NULL);
1642 CleanupProc(pid, exitstatus);
1648 * Wait for all children exit, then reset shmem and
1651 if (DLGetHead(BackendList) || StartupPID > 0 || ShutdownPID > 0)
1656 elog(DEBUG, "all server processes terminated; reinitializing shared memory and semaphores");
1659 reset_shared(PostPortNumber);
1661 StartupPID = StartupDataBase();
1666 if (Shutdown > NoShutdown)
1668 if (DLGetHead(BackendList))
1673 if (StartupPID > 0 || ShutdownPID > 0)
1678 ShutdownPID = ShutdownDataBase();
1685 * CleanupProc -- cleanup after terminated backend.
1687 * Remove all local state associated with backend.
1689 * Dillon's note: should log child's exit status in the system log.
1692 CleanupProc(int pid,
1693 int exitstatus) /* child's exit status. */
1700 elog(DEBUG, "CleanupProc: pid %d exited with status %d",
1704 * If a backend dies in an ugly way (i.e. exit status not 0) then we
1705 * must signal all other backends to quickdie. If exit status is zero
1706 * we assume everything is hunky dory and simply remove the backend
1707 * from the active backend list.
1709 if (exitstatus == 0)
1711 curr = DLGetHead(BackendList);
1714 bp = (Backend *) DLE_VAL(curr);
1722 curr = DLGetSucc(curr);
1725 if (pid == CheckPointPID)
1730 checkpointed = time(NULL);
1731 /* Update RedoRecPtr for future child backends */
1741 /* below here we're dealing with a non-normal exit */
1743 /* Make log entry unless we did so already */
1746 if (WIFEXITED(exitstatus))
1747 elog(DEBUG, "server process (pid %d) exited with status %d",
1748 pid, WEXITSTATUS(exitstatus));
1749 else if (WIFSIGNALED(exitstatus))
1750 elog(DEBUG, "server process (pid %d) was terminated by signal %d",
1751 pid, WTERMSIG(exitstatus));
1752 elog(DEBUG, "terminating any other active server processes");
1755 curr = DLGetHead(BackendList);
1758 next = DLGetSucc(curr);
1759 bp = (Backend *) DLE_VAL(curr);
1763 * This backend is still alive. Unless we did so already,
1764 * tell it to commit hara-kiri.
1766 * SIGQUIT is the special signal that says exit without proc_exit
1767 * and let the user know what's going on. But if SendStop is
1768 * set (-s on command line), then we send SIGSTOP instead, so
1769 * that we can get core dumps from all backends by hand.
1774 elog(DEBUG, "CleanupProc: sending %s to process %d",
1775 (SendStop ? "SIGSTOP" : "SIGQUIT"),
1777 kill(bp->pid, (SendStop ? SIGSTOP : SIGQUIT));
1783 * Found entry for freshly-dead backend, so remove it.
1792 if (pid == CheckPointPID)
1800 * Tell the collector about backend termination
1809 * Send a signal to all backend children.
1812 SignalChildren(int signal)
1817 int mypid = getpid();
1819 curr = DLGetHead(BackendList);
1822 next = DLGetSucc(curr);
1823 bp = (Backend *) DLE_VAL(curr);
1825 if (bp->pid != mypid)
1828 elog(DEBUG, "SignalChildren: sending signal %d to process %d",
1831 kill(bp->pid, signal);
1839 * BackendStartup -- start backend process
1841 * returns: STATUS_ERROR if the fork/exec failed, STATUS_OK otherwise.
1844 BackendStartup(Port *port)
1846 Backend *bn; /* for backend cleanup */
1850 * Compute the cancel key that will be assigned to this backend. The
1851 * backend will have its own copy in the forked-off process' value of
1852 * MyCancelKey, so that it can transmit the key to the frontend.
1854 MyCancelKey = PostmasterRandom();
1857 * Make room for backend data structure. Better before the fork() so
1858 * we can handle failure cleanly.
1860 bn = (Backend *) malloc(sizeof(Backend));
1863 elog(DEBUG, "out of memory; connection startup aborted");
1864 return STATUS_ERROR;
1868 * Flush stdio channels just before fork, to avoid double-output
1869 * problems. Ideally we'd use fflush(NULL) here, but there are still a
1870 * few non-ANSI stdio libraries out there (like SunOS 4.1.x) that
1871 * coredump if we do. Presently stdout and stderr are the only stdio
1872 * output channels used by the postmaster, so fflush'ing them should
1879 /* Specific beos actions before backend startup */
1880 beos_before_backend_startup();
1885 if (pid == 0) /* child */
1891 /* Specific beos backend startup actions */
1892 beos_backend_startup();
1895 status = DoBackend(port);
1898 elog(DEBUG, "connection startup failed");
1905 /* in parent, error */
1910 /* Specific beos backend startup actions */
1911 beos_backend_startup_failed();
1913 elog(DEBUG, "connection startup failed (fork failure): %s",
1915 return STATUS_ERROR;
1918 /* in parent, normal */
1920 elog(DEBUG, "BackendStartup: forked pid=%d socket=%d",
1924 * Everything's been successful, it's safe to add this backend to our
1928 bn->cancel_key = MyCancelKey;
1929 DLAddHead(BackendList, DLNewElem(bn));
1936 * split_opts -- split a string of options and append it to an argv array
1938 * NB: the string is destructively modified!
1940 * Since no current POSTGRES arguments require any quoting characters,
1941 * we can use the simple-minded tactic of assuming each set of space-
1942 * delimited characters is a separate argv element.
1944 * If you don't like that, well, we *used* to pass the whole option string
1945 * as ONE argument to execl(), which was even less intelligent...
1948 split_opts(char **argv, int *argcp, char *s)
1952 while (isspace((unsigned char) *s))
1956 argv[(*argcp)++] = s;
1957 while (*s && !isspace((unsigned char) *s))
1965 * DoBackend -- perform authentication, and if successful, set up the
1966 * backend's argument list and invoke backend main().
1968 * This used to perform an execv() but we no longer exec the backend;
1969 * it's the same executable as the postmaster.
1972 * Shouldn't return at all.
1973 * If PostgresMain() fails, return status.
1976 DoBackend(Port *port)
1979 char *av[ARGV_SIZE * 2];
1981 char debugbuf[ARGV_SIZE];
1982 char protobuf[ARGV_SIZE];
1983 char dbbuf[ARGV_SIZE];
1984 char optbuf[ARGV_SIZE];
1985 char ttybuf[ARGV_SIZE];
1992 * Let's clean up ourselves as the postmaster child
1995 IsUnderPostmaster = true; /* we are a postmaster subprocess now */
1997 /* We don't want the postmaster's proc_exit() handlers */
2001 * Signal handlers setting is moved to tcop/postgres...
2004 /* Close the postmaster's other sockets */
2005 ClosePostmasterPorts(true);
2007 /* Save port etc. for ps status */
2010 /* Reset MyProcPid to new backend's pid */
2011 MyProcPid = getpid();
2014 * Initialize libpq and enable reporting of elog errors to the client.
2015 * Must do this now because authentication uses libpq to send
2018 pq_init(); /* initialize libpq to talk to client */
2019 whereToSendOutput = Remote; /* now safe to elog to client */
2022 * We arrange for a simple exit(0) if we receive SIGTERM or SIGQUIT
2023 * during any client authentication related communication. Otherwise
2024 * the postmaster cannot shutdown the database FAST or IMMED cleanly
2025 * if a buggy client blocks a backend during authentication. We also
2026 * will exit(0) after a time delay, so that a broken client can't hog
2027 * a connection indefinitely.
2029 * PreAuthDelay is a debugging aid for investigating problems in the
2030 * authentication cycle: it can be set in postgresql.conf to allow
2031 * time to attach to the newly-forked backend with a debugger. (See
2032 * also the -W backend switch, which we allow clients to pass through
2033 * PGOPTIONS, but it is not honored until after authentication.)
2035 pqsignal(SIGTERM, authdie);
2036 pqsignal(SIGQUIT, authdie);
2037 pqsignal(SIGALRM, authdie);
2038 PG_SETMASK(&AuthBlockSig);
2040 if (PreAuthDelay > 0)
2041 sleep(PreAuthDelay);
2043 if (!enable_sigalrm_interrupt(AuthenticationTimeout * 1000))
2044 elog(FATAL, "DoBackend: Unable to set timer for auth timeout");
2047 * Receive the startup packet (which might turn out to be a cancel
2050 status = ProcessStartupPacket(port, false);
2052 if (status != STATUS_OK)
2053 return 0; /* cancel request processed, or error */
2056 * Now that we have the user and database name, we can set the process
2057 * title for ps. It's good to do this as early as possible in
2060 * But first, we need the remote host name.
2062 if (port->raddr.sa.sa_family == AF_INET)
2064 unsigned short remote_port;
2067 remote_port = ntohs(port->raddr.in.sin_port);
2068 host_addr = inet_ntoa(port->raddr.in.sin_addr);
2074 struct hostent *host_ent;
2076 host_ent = gethostbyaddr((char *) &port->raddr.in.sin_addr,
2077 sizeof(port->raddr.in.sin_addr),
2082 remote_host = palloc(strlen(host_addr) + strlen(host_ent->h_name) + 3);
2083 sprintf(remote_host, "%s[%s]", host_ent->h_name, host_addr);
2087 if (remote_host == NULL)
2088 remote_host = pstrdup(host_addr);
2092 char *str = palloc(strlen(remote_host) + 7);
2094 sprintf(str, "%s:%hu", remote_host, remote_port);
2102 remote_host = "[local]";
2106 * Set process parameters for ps display.
2108 init_ps_display(port->user, port->database, remote_host);
2109 set_ps_display("authentication");
2112 * Now perform authentication exchange.
2114 ClientAuthentication(port); /* might not return, if failure */
2117 * Done with authentication. Disable timeout, and prevent
2118 * SIGTERM/SIGQUIT again until backend startup is complete.
2120 if (!disable_sigalrm_interrupt())
2121 elog(FATAL, "DoBackend: Unable to disable timer for auth timeout");
2122 PG_SETMASK(&BlockSig);
2124 if (Log_connections)
2125 elog(DEBUG, "connection: host=%s user=%s database=%s",
2126 remote_host, port->user, port->database);
2129 * Don't want backend to be able to see the postmaster random number
2130 * generator state. We have to clobber the static random_seed *and*
2131 * start a new random sequence in the random() library function.
2134 gettimeofday(&now, &tz);
2135 srandom((unsigned int) now.tv_usec);
2138 * Now, build the argv vector that will be given to PostgresMain.
2140 * The layout of the command line is
2141 * postgres [secure switches] -p databasename [insecure switches]
2142 * where the switches after -p come from the client request.
2146 av[ac++] = "postgres";
2149 * Pass the requested debugging level along to the backend. Level one
2150 * debugging in the postmaster traces postmaster connection activity,
2151 * and levels two and higher are passed along to the backend. This
2152 * allows us to watch only the postmaster or the postmaster and the
2157 sprintf(debugbuf, "-d%d", DebugLvl);
2158 av[ac++] = debugbuf;
2162 * Pass any backend switches specified with -o in the postmaster's own
2163 * command line. We assume these are secure. (It's OK to mangle
2164 * ExtraOptions since we are now in the child process; this won't
2165 * change the postmaster's copy.)
2167 split_opts(av, &ac, ExtraOptions);
2169 /* Tell the backend what protocol the frontend is using. */
2170 sprintf(protobuf, "-v%u", port->proto);
2171 av[ac++] = protobuf;
2174 * Tell the backend it is being called from the postmaster, and which
2175 * database to use. -p marks the end of secure switches.
2179 StrNCpy(dbbuf, port->database, ARGV_SIZE);
2183 * Pass the (insecure) option switches from the connection request.
2185 StrNCpy(optbuf, port->options, ARGV_SIZE);
2186 split_opts(av, &ac, optbuf);
2189 * Pass the (insecure) debug output file request.
2191 * NOTE: currently, this is useless code, since the backend will not
2192 * honor an insecure -o switch. I left it here since the backend
2193 * could be modified to allow insecure -o, given adequate checking
2194 * that the specified filename is something safe to write on.
2198 StrNCpy(ttybuf, port->tty, ARGV_SIZE);
2203 av[ac] = (char *) NULL;
2206 * Release postmaster's working memory context so that backend can
2207 * recycle the space. Note this does not trash *MyProcPort, because
2208 * ConnCreate() allocated that space with malloc() ... else we'd need
2209 * to copy the Port data here.
2211 MemoryContextSwitchTo(TopMemoryContext);
2212 MemoryContextDelete(PostmasterContext);
2213 PostmasterContext = NULL;
2216 * Debug: print arguments being passed to backend
2220 fprintf(stderr, "%s child[%d]: starting with (",
2221 progname, MyProcPid);
2222 for (i = 0; i < ac; ++i)
2223 fprintf(stderr, "%s ", av[i]);
2224 fprintf(stderr, ")\n");
2227 return (PostgresMain(ac, av, port->user));
2231 * ExitPostmaster -- cleanup
2233 * Do NOT call exit() directly --- always go through here!
2236 ExitPostmaster(int status)
2238 /* should cleanup shared memory and kill all backends */
2241 * Not sure of the semantics here. When the Postmaster dies, should
2242 * the backends all be killed? probably not.
2244 * MUST -- vadim 05-10-1999
2246 if (ServerSock_INET != INVALID_SOCK)
2247 StreamClose(ServerSock_INET);
2248 ServerSock_INET = INVALID_SOCK;
2249 #ifdef HAVE_UNIX_SOCKETS
2250 if (ServerSock_UNIX != INVALID_SOCK)
2251 StreamClose(ServerSock_UNIX);
2252 ServerSock_UNIX = INVALID_SOCK;
2258 /* Request to schedule a checkpoint (no-op if one is currently running) */
2260 schedule_checkpoint(SIGNAL_ARGS)
2262 int save_errno = errno;
2264 PG_SETMASK(&BlockSig);
2266 /* Ignore request if checkpointing is currently disabled */
2267 if (CheckPointPID == 0 && checkpointed &&
2268 Shutdown == NoShutdown && !FatalError && random_seed != 0)
2270 CheckPointPID = CheckPointDataBase();
2271 /* note: if fork fails, CheckPointPID stays 0; nothing happens */
2279 * CharRemap: given an int in range 0..61, produce textual encoding of it
2280 * per crypt(3) conventions.
2304 RandomSalt(char *cryptSalt, char *md5Salt)
2306 long rand = PostmasterRandom();
2308 cryptSalt[0] = CharRemap(rand % 62);
2309 cryptSalt[1] = CharRemap(rand / 62);
2312 * It's okay to reuse the first random value for one of the MD5 salt
2313 * bytes, since only one of the two salts will be sent to the client.
2314 * After that we need to compute more random bits.
2316 * We use % 255, sacrificing one possible byte value, so as to ensure
2317 * that all bits of the random() value participate in the result.
2318 * While at it, add one to avoid generating any null bytes.
2320 md5Salt[0] = (rand % 255) + 1;
2321 rand = PostmasterRandom();
2322 md5Salt[1] = (rand % 255) + 1;
2323 rand = PostmasterRandom();
2324 md5Salt[2] = (rand % 255) + 1;
2325 rand = PostmasterRandom();
2326 md5Salt[3] = (rand % 255) + 1;
2333 PostmasterRandom(void)
2335 static bool initialized = false;
2339 Assert(random_seed != 0);
2340 srandom(random_seed);
2348 * Count up number of child processes.
2355 int mypid = getpid();
2358 for (curr = DLGetHead(BackendList); curr; curr = DLGetSucc(curr))
2360 bp = (Backend *) DLE_VAL(curr);
2361 if (bp->pid != mypid)
2364 if (CheckPointPID != 0)
2371 * Initialize SSL library and structures
2378 SSL_load_error_strings();
2380 SSL_context = SSL_CTX_new(SSLv23_method());
2383 postmaster_error("failed to create SSL context: %s",
2384 ERR_reason_error_string(ERR_get_error()));
2387 snprintf(fnbuf, sizeof(fnbuf), "%s/server.crt", DataDir);
2388 if (!SSL_CTX_use_certificate_file(SSL_context, fnbuf, SSL_FILETYPE_PEM))
2390 postmaster_error("failed to load server certificate (%s): %s",
2391 fnbuf, ERR_reason_error_string(ERR_get_error()));
2394 snprintf(fnbuf, sizeof(fnbuf), "%s/server.key", DataDir);
2395 if (!SSL_CTX_use_PrivateKey_file(SSL_context, fnbuf, SSL_FILETYPE_PEM))
2397 postmaster_error("failed to load private key file (%s): %s",
2398 fnbuf, ERR_reason_error_string(ERR_get_error()));
2401 if (!SSL_CTX_check_private_key(SSL_context))
2403 postmaster_error("check of private key failed: %s",
2404 ERR_reason_error_string(ERR_get_error()));
2411 * Fire off a subprocess for startup/shutdown/checkpoint.
2413 * Return value is subprocess' PID, or 0 if failed to start subprocess
2414 * (0 is returned only for checkpoint case).
2417 SSDataBase(int xlop)
2426 /* Specific beos actions before backend startup */
2427 beos_before_backend_startup();
2430 if ((pid = fork()) == 0) /* child */
2432 const char *statmsg;
2433 char *av[ARGV_SIZE * 2];
2435 char nbbuf[ARGV_SIZE];
2436 char dbbuf[ARGV_SIZE];
2437 char xlbuf[ARGV_SIZE];
2440 /* Specific beos actions after backend startup */
2441 beos_backend_startup();
2444 IsUnderPostmaster = true; /* we are a postmaster subprocess
2447 /* Lose the postmaster's on-exit routines and port connections */
2450 /* Close the postmaster's sockets */
2451 ClosePostmasterPorts(true);
2454 * Identify myself via ps
2458 case BS_XLOG_STARTUP:
2459 statmsg = "startup subprocess";
2461 case BS_XLOG_CHECKPOINT:
2462 statmsg = "checkpoint subprocess";
2464 case BS_XLOG_SHUTDOWN:
2465 statmsg = "shutdown subprocess";
2468 statmsg = "??? subprocess";
2471 init_ps_display(statmsg, "", "");
2474 /* Set up command-line arguments for subprocess */
2475 av[ac++] = "postgres";
2479 sprintf(nbbuf, "-B%d", NBuffers);
2482 sprintf(xlbuf, "-x%d", xlop);
2487 StrNCpy(dbbuf, "template1", ARGV_SIZE);
2490 av[ac] = (char *) NULL;
2492 BootstrapMain(ac, av);
2500 /* Specific beos actions before backend startup */
2501 beos_backend_startup_failed();
2506 case BS_XLOG_STARTUP:
2507 elog(DEBUG, "could not launch startup process (fork failure): %s",
2510 case BS_XLOG_CHECKPOINT:
2511 elog(DEBUG, "could not launch checkpoint process (fork failure): %s",
2514 case BS_XLOG_SHUTDOWN:
2516 elog(DEBUG, "could not launch shutdown process (fork failure): %s",
2522 * fork failure is fatal during startup/shutdown, but there's no
2523 * need to choke if a routine checkpoint fails.
2525 if (xlop == BS_XLOG_CHECKPOINT)
2531 * The startup and shutdown processes are not considered normal
2532 * backends, but the checkpoint process is. Checkpoint must be added
2533 * to the list of backends.
2535 if (xlop == BS_XLOG_CHECKPOINT)
2537 if (!(bn = (Backend *) calloc(1, sizeof(Backend))))
2539 elog(DEBUG, "CheckPointDataBase: malloc failed");
2544 bn->cancel_key = PostmasterRandom();
2545 DLAddHead(BackendList, DLNewElem(bn));
2548 * Since this code is executed periodically, it's a fine place to
2549 * do other actions that should happen every now and then on no
2550 * particular schedule. Such as...
2552 TouchSocketLockFile();
2560 * Create the opts file
2563 CreateOptsFile(int argc, char *argv[])
2565 char fullprogname[MAXPGPATH];
2570 if (FindExec(fullprogname, argv[0], "postmaster") < 0)
2573 filename = palloc(strlen(DataDir) + 20);
2574 sprintf(filename, "%s/postmaster.opts", DataDir);
2576 fp = fopen(filename, "w");
2579 postmaster_error("cannot create file %s: %s",
2580 filename, strerror(errno));
2584 fprintf(fp, "%s", fullprogname);
2585 for (i = 1; i < argc; i++)
2586 fprintf(fp, " '%s'", argv[i]);
2591 postmaster_error("writing file %s failed", filename);
2602 postmaster_error(const char *fmt,...)
2606 fprintf(stderr, "%s: ", progname);
2608 vfprintf(stderr, gettext(fmt), ap);
2610 fprintf(stderr, "\n");