OSDN Git Service

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