]> granicus.if.org Git - postgresql/blob - src/backend/utils/init/miscinit.c
Process options from the startup packed in walsender. Only few options
[postgresql] / src / backend / utils / init / miscinit.c
1 /*-------------------------------------------------------------------------
2  *
3  * miscinit.c
4  *        miscellaneous initialization support stuff
5  *
6  * Portions Copyright (c) 1996-2010, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *        $PostgreSQL: pgsql/src/backend/utils/init/miscinit.c,v 1.185 2010/08/16 17:32:46 tgl Exp $
12  *
13  *-------------------------------------------------------------------------
14  */
15 #include "postgres.h"
16
17 #include <sys/param.h>
18 #include <signal.h>
19 #include <sys/file.h>
20 #include <sys/stat.h>
21 #include <sys/time.h>
22 #include <fcntl.h>
23 #include <unistd.h>
24 #include <grp.h>
25 #include <pwd.h>
26 #include <netinet/in.h>
27 #include <arpa/inet.h>
28 #ifdef HAVE_UTIME_H
29 #include <utime.h>
30 #endif
31
32 #include "catalog/pg_authid.h"
33 #include "mb/pg_wchar.h"
34 #include "miscadmin.h"
35 #include "postmaster/autovacuum.h"
36 #include "storage/fd.h"
37 #include "storage/ipc.h"
38 #include "storage/pg_shmem.h"
39 #include "storage/proc.h"
40 #include "storage/procarray.h"
41 #include "utils/builtins.h"
42 #include "utils/guc.h"
43 #include "utils/memutils.h"
44 #include "utils/syscache.h"
45
46
47 #define DIRECTORY_LOCK_FILE             "postmaster.pid"
48
49 ProcessingMode Mode = InitProcessing;
50
51 /* Note: we rely on this to initialize as zeroes */
52 static char socketLockFile[MAXPGPATH];
53
54
55 /* ----------------------------------------------------------------
56  *              ignoring system indexes support stuff
57  *
58  * NOTE: "ignoring system indexes" means we do not use the system indexes
59  * for lookups (either in hardwired catalog accesses or in planner-generated
60  * plans).      We do, however, still update the indexes when a catalog
61  * modification is made.
62  * ----------------------------------------------------------------
63  */
64
65 bool            IgnoreSystemIndexes = false;
66
67
68 /* ----------------------------------------------------------------
69  *                              database path / name support stuff
70  * ----------------------------------------------------------------
71  */
72
73 void
74 SetDatabasePath(const char *path)
75 {
76         /* This should happen only once per process */
77         Assert(!DatabasePath);
78         DatabasePath = MemoryContextStrdup(TopMemoryContext, path);
79 }
80
81 /*
82  * Set data directory, but make sure it's an absolute path.  Use this,
83  * never set DataDir directly.
84  */
85 void
86 SetDataDir(const char *dir)
87 {
88         char       *new;
89
90         AssertArg(dir);
91
92         /* If presented path is relative, convert to absolute */
93         new = make_absolute_path(dir);
94
95         if (DataDir)
96                 free(DataDir);
97         DataDir = new;
98 }
99
100 /*
101  * Change working directory to DataDir.  Most of the postmaster and backend
102  * code assumes that we are in DataDir so it can use relative paths to access
103  * stuff in and under the data directory.  For convenience during path
104  * setup, however, we don't force the chdir to occur during SetDataDir.
105  */
106 void
107 ChangeToDataDir(void)
108 {
109         AssertState(DataDir);
110
111         if (chdir(DataDir) < 0)
112                 ereport(FATAL,
113                                 (errcode_for_file_access(),
114                                  errmsg("could not change directory to \"%s\": %m",
115                                                 DataDir)));
116 }
117
118 /*
119  * If the given pathname isn't already absolute, make it so, interpreting
120  * it relative to the current working directory.
121  *
122  * Also canonicalizes the path.  The result is always a malloc'd copy.
123  *
124  * Note: interpretation of relative-path arguments during postmaster startup
125  * should happen before doing ChangeToDataDir(), else the user will probably
126  * not like the results.
127  */
128 char *
129 make_absolute_path(const char *path)
130 {
131         char       *new;
132
133         /* Returning null for null input is convenient for some callers */
134         if (path == NULL)
135                 return NULL;
136
137         if (!is_absolute_path(path))
138         {
139                 char       *buf;
140                 size_t          buflen;
141
142                 buflen = MAXPGPATH;
143                 for (;;)
144                 {
145                         buf = malloc(buflen);
146                         if (!buf)
147                                 ereport(FATAL,
148                                                 (errcode(ERRCODE_OUT_OF_MEMORY),
149                                                  errmsg("out of memory")));
150
151                         if (getcwd(buf, buflen))
152                                 break;
153                         else if (errno == ERANGE)
154                         {
155                                 free(buf);
156                                 buflen *= 2;
157                                 continue;
158                         }
159                         else
160                         {
161                                 free(buf);
162                                 elog(FATAL, "could not get current working directory: %m");
163                         }
164                 }
165
166                 new = malloc(strlen(buf) + strlen(path) + 2);
167                 if (!new)
168                         ereport(FATAL,
169                                         (errcode(ERRCODE_OUT_OF_MEMORY),
170                                          errmsg("out of memory")));
171                 sprintf(new, "%s/%s", buf, path);
172                 free(buf);
173         }
174         else
175         {
176                 new = strdup(path);
177                 if (!new)
178                         ereport(FATAL,
179                                         (errcode(ERRCODE_OUT_OF_MEMORY),
180                                          errmsg("out of memory")));
181         }
182
183         /* Make sure punctuation is canonical, too */
184         canonicalize_path(new);
185
186         return new;
187 }
188
189
190 /* ----------------------------------------------------------------
191  *      User ID state
192  *
193  * We have to track several different values associated with the concept
194  * of "user ID".
195  *
196  * AuthenticatedUserId is determined at connection start and never changes.
197  *
198  * SessionUserId is initially the same as AuthenticatedUserId, but can be
199  * changed by SET SESSION AUTHORIZATION (if AuthenticatedUserIsSuperuser).
200  * This is the ID reported by the SESSION_USER SQL function.
201  *
202  * OuterUserId is the current user ID in effect at the "outer level" (outside
203  * any transaction or function).  This is initially the same as SessionUserId,
204  * but can be changed by SET ROLE to any role that SessionUserId is a
205  * member of.  (XXX rename to something like CurrentRoleId?)
206  *
207  * CurrentUserId is the current effective user ID; this is the one to use
208  * for all normal permissions-checking purposes.  At outer level this will
209  * be the same as OuterUserId, but it changes during calls to SECURITY
210  * DEFINER functions, as well as locally in some specialized commands.
211  *
212  * SecurityRestrictionContext holds flags indicating reason(s) for changing
213  * CurrentUserId.  In some cases we need to lock down operations that are
214  * not directly controlled by privilege settings, and this provides a
215  * convenient way to do it.
216  * ----------------------------------------------------------------
217  */
218 static Oid      AuthenticatedUserId = InvalidOid;
219 static Oid      SessionUserId = InvalidOid;
220 static Oid      OuterUserId = InvalidOid;
221 static Oid      CurrentUserId = InvalidOid;
222
223 /* We also have to remember the superuser state of some of these levels */
224 static bool AuthenticatedUserIsSuperuser = false;
225 static bool SessionUserIsSuperuser = false;
226
227 static int      SecurityRestrictionContext = 0;
228
229 /* We also remember if a SET ROLE is currently active */
230 static bool SetRoleIsActive = false;
231
232
233 /*
234  * GetUserId - get the current effective user ID.
235  *
236  * Note: there's no SetUserId() anymore; use SetUserIdAndSecContext().
237  */
238 Oid
239 GetUserId(void)
240 {
241         AssertState(OidIsValid(CurrentUserId));
242         return CurrentUserId;
243 }
244
245
246 /*
247  * GetOuterUserId/SetOuterUserId - get/set the outer-level user ID.
248  */
249 Oid
250 GetOuterUserId(void)
251 {
252         AssertState(OidIsValid(OuterUserId));
253         return OuterUserId;
254 }
255
256
257 static void
258 SetOuterUserId(Oid userid)
259 {
260         AssertState(SecurityRestrictionContext == 0);
261         AssertArg(OidIsValid(userid));
262         OuterUserId = userid;
263
264         /* We force the effective user ID to match, too */
265         CurrentUserId = userid;
266 }
267
268
269 /*
270  * GetSessionUserId/SetSessionUserId - get/set the session user ID.
271  */
272 Oid
273 GetSessionUserId(void)
274 {
275         AssertState(OidIsValid(SessionUserId));
276         return SessionUserId;
277 }
278
279
280 static void
281 SetSessionUserId(Oid userid, bool is_superuser)
282 {
283         AssertState(SecurityRestrictionContext == 0);
284         AssertArg(OidIsValid(userid));
285         SessionUserId = userid;
286         SessionUserIsSuperuser = is_superuser;
287         SetRoleIsActive = false;
288
289         /* We force the effective user IDs to match, too */
290         OuterUserId = userid;
291         CurrentUserId = userid;
292 }
293
294
295 /*
296  * GetUserIdAndSecContext/SetUserIdAndSecContext - get/set the current user ID
297  * and the SecurityRestrictionContext flags.
298  *
299  * Currently there are two valid bits in SecurityRestrictionContext:
300  *
301  * SECURITY_LOCAL_USERID_CHANGE indicates that we are inside an operation
302  * that is temporarily changing CurrentUserId via these functions.      This is
303  * needed to indicate that the actual value of CurrentUserId is not in sync
304  * with guc.c's internal state, so SET ROLE has to be disallowed.
305  *
306  * SECURITY_RESTRICTED_OPERATION indicates that we are inside an operation
307  * that does not wish to trust called user-defined functions at all.  This
308  * bit prevents not only SET ROLE, but various other changes of session state
309  * that normally is unprotected but might possibly be used to subvert the
310  * calling session later.  An example is replacing an existing prepared
311  * statement with new code, which will then be executed with the outer
312  * session's permissions when the prepared statement is next used.  Since
313  * these restrictions are fairly draconian, we apply them only in contexts
314  * where the called functions are really supposed to be side-effect-free
315  * anyway, such as VACUUM/ANALYZE/REINDEX.
316  *
317  * Unlike GetUserId, GetUserIdAndSecContext does *not* Assert that the current
318  * value of CurrentUserId is valid; nor does SetUserIdAndSecContext require
319  * the new value to be valid.  In fact, these routines had better not
320  * ever throw any kind of error.  This is because they are used by
321  * StartTransaction and AbortTransaction to save/restore the settings,
322  * and during the first transaction within a backend, the value to be saved
323  * and perhaps restored is indeed invalid.      We have to be able to get
324  * through AbortTransaction without asserting in case InitPostgres fails.
325  */
326 void
327 GetUserIdAndSecContext(Oid *userid, int *sec_context)
328 {
329         *userid = CurrentUserId;
330         *sec_context = SecurityRestrictionContext;
331 }
332
333 void
334 SetUserIdAndSecContext(Oid userid, int sec_context)
335 {
336         CurrentUserId = userid;
337         SecurityRestrictionContext = sec_context;
338 }
339
340
341 /*
342  * InLocalUserIdChange - are we inside a local change of CurrentUserId?
343  */
344 bool
345 InLocalUserIdChange(void)
346 {
347         return (SecurityRestrictionContext & SECURITY_LOCAL_USERID_CHANGE) != 0;
348 }
349
350 /*
351  * InSecurityRestrictedOperation - are we inside a security-restricted command?
352  */
353 bool
354 InSecurityRestrictedOperation(void)
355 {
356         return (SecurityRestrictionContext & SECURITY_RESTRICTED_OPERATION) != 0;
357 }
358
359
360 /*
361  * These are obsolete versions of Get/SetUserIdAndSecContext that are
362  * only provided for bug-compatibility with some rather dubious code in
363  * pljava.      We allow the userid to be set, but only when not inside a
364  * security restriction context.
365  */
366 void
367 GetUserIdAndContext(Oid *userid, bool *sec_def_context)
368 {
369         *userid = CurrentUserId;
370         *sec_def_context = InLocalUserIdChange();
371 }
372
373 void
374 SetUserIdAndContext(Oid userid, bool sec_def_context)
375 {
376         /* We throw the same error SET ROLE would. */
377         if (InSecurityRestrictedOperation())
378                 ereport(ERROR,
379                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
380                                  errmsg("cannot set parameter \"%s\" within security-restricted operation",
381                                                 "role")));
382         CurrentUserId = userid;
383         if (sec_def_context)
384                 SecurityRestrictionContext |= SECURITY_LOCAL_USERID_CHANGE;
385         else
386                 SecurityRestrictionContext &= ~SECURITY_LOCAL_USERID_CHANGE;
387 }
388
389
390 /*
391  * Initialize user identity during normal backend startup
392  */
393 void
394 InitializeSessionUserId(const char *rolename)
395 {
396         HeapTuple       roleTup;
397         Form_pg_authid rform;
398         Oid                     roleid;
399
400         /*
401          * Don't do scans if we're bootstrapping, none of the system catalogs
402          * exist yet, and they should be owned by postgres anyway.
403          */
404         AssertState(!IsBootstrapProcessingMode());
405
406         /* call only once */
407         AssertState(!OidIsValid(AuthenticatedUserId));
408
409         roleTup = SearchSysCache1(AUTHNAME, PointerGetDatum(rolename));
410         if (!HeapTupleIsValid(roleTup))
411                 ereport(FATAL,
412                                 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
413                                  errmsg("role \"%s\" does not exist", rolename)));
414
415         rform = (Form_pg_authid) GETSTRUCT(roleTup);
416         roleid = HeapTupleGetOid(roleTup);
417
418         AuthenticatedUserId = roleid;
419         AuthenticatedUserIsSuperuser = rform->rolsuper;
420
421         /* This sets OuterUserId/CurrentUserId too */
422         SetSessionUserId(roleid, AuthenticatedUserIsSuperuser);
423
424         /* Also mark our PGPROC entry with the authenticated user id */
425         /* (We assume this is an atomic store so no lock is needed) */
426         MyProc->roleId = roleid;
427
428         /*
429          * These next checks are not enforced when in standalone mode, so that
430          * there is a way to recover from sillinesses like "UPDATE pg_authid SET
431          * rolcanlogin = false;".
432          */
433         if (IsUnderPostmaster)
434         {
435                 /*
436                  * Is role allowed to login at all?
437                  */
438                 if (!rform->rolcanlogin)
439                         ereport(FATAL,
440                                         (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
441                                          errmsg("role \"%s\" is not permitted to log in",
442                                                         rolename)));
443
444                 /*
445                  * Check connection limit for this role.
446                  *
447                  * There is a race condition here --- we create our PGPROC before
448                  * checking for other PGPROCs.  If two backends did this at about the
449                  * same time, they might both think they were over the limit, while
450                  * ideally one should succeed and one fail.  Getting that to work
451                  * exactly seems more trouble than it is worth, however; instead we
452                  * just document that the connection limit is approximate.
453                  */
454                 if (rform->rolconnlimit >= 0 &&
455                         !AuthenticatedUserIsSuperuser &&
456                         CountUserBackends(roleid) > rform->rolconnlimit)
457                         ereport(FATAL,
458                                         (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
459                                          errmsg("too many connections for role \"%s\"",
460                                                         rolename)));
461         }
462
463         /* Record username and superuser status as GUC settings too */
464         SetConfigOption("session_authorization", rolename,
465                                         PGC_BACKEND, PGC_S_OVERRIDE);
466         SetConfigOption("is_superuser",
467                                         AuthenticatedUserIsSuperuser ? "on" : "off",
468                                         PGC_INTERNAL, PGC_S_OVERRIDE);
469
470         ReleaseSysCache(roleTup);
471 }
472
473
474 /*
475  * Initialize user identity during special backend startup
476  */
477 void
478 InitializeSessionUserIdStandalone(void)
479 {
480         /*
481          * This function should only be called in single-user mode and in
482          * autovacuum workers.
483          */
484         AssertState(!IsUnderPostmaster || IsAutoVacuumWorkerProcess());
485
486         /* call only once */
487         AssertState(!OidIsValid(AuthenticatedUserId));
488
489         AuthenticatedUserId = BOOTSTRAP_SUPERUSERID;
490         AuthenticatedUserIsSuperuser = true;
491
492         SetSessionUserId(BOOTSTRAP_SUPERUSERID, true);
493 }
494
495
496 /*
497  * Change session auth ID while running
498  *
499  * Only a superuser may set auth ID to something other than himself.  Note
500  * that in case of multiple SETs in a single session, the original userid's
501  * superuserness is what matters.  But we set the GUC variable is_superuser
502  * to indicate whether the *current* session userid is a superuser.
503  *
504  * Note: this is not an especially clean place to do the permission check.
505  * It's OK because the check does not require catalog access and can't
506  * fail during an end-of-transaction GUC reversion, but we may someday
507  * have to push it up into assign_session_authorization.
508  */
509 void
510 SetSessionAuthorization(Oid userid, bool is_superuser)
511 {
512         /* Must have authenticated already, else can't make permission check */
513         AssertState(OidIsValid(AuthenticatedUserId));
514
515         if (userid != AuthenticatedUserId &&
516                 !AuthenticatedUserIsSuperuser)
517                 ereport(ERROR,
518                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
519                                  errmsg("permission denied to set session authorization")));
520
521         SetSessionUserId(userid, is_superuser);
522
523         SetConfigOption("is_superuser",
524                                         is_superuser ? "on" : "off",
525                                         PGC_INTERNAL, PGC_S_OVERRIDE);
526 }
527
528 /*
529  * Report current role id
530  *              This follows the semantics of SET ROLE, ie return the outer-level ID
531  *              not the current effective ID, and return InvalidOid when the setting
532  *              is logically SET ROLE NONE.
533  */
534 Oid
535 GetCurrentRoleId(void)
536 {
537         if (SetRoleIsActive)
538                 return OuterUserId;
539         else
540                 return InvalidOid;
541 }
542
543 /*
544  * Change Role ID while running (SET ROLE)
545  *
546  * If roleid is InvalidOid, we are doing SET ROLE NONE: revert to the
547  * session user authorization.  In this case the is_superuser argument
548  * is ignored.
549  *
550  * When roleid is not InvalidOid, the caller must have checked whether
551  * the session user has permission to become that role.  (We cannot check
552  * here because this routine must be able to execute in a failed transaction
553  * to restore a prior value of the ROLE GUC variable.)
554  */
555 void
556 SetCurrentRoleId(Oid roleid, bool is_superuser)
557 {
558         /*
559          * Get correct info if it's SET ROLE NONE
560          *
561          * If SessionUserId hasn't been set yet, just do nothing --- the eventual
562          * SetSessionUserId call will fix everything.  This is needed since we
563          * will get called during GUC initialization.
564          */
565         if (!OidIsValid(roleid))
566         {
567                 if (!OidIsValid(SessionUserId))
568                         return;
569
570                 roleid = SessionUserId;
571                 is_superuser = SessionUserIsSuperuser;
572
573                 SetRoleIsActive = false;
574         }
575         else
576                 SetRoleIsActive = true;
577
578         SetOuterUserId(roleid);
579
580         SetConfigOption("is_superuser",
581                                         is_superuser ? "on" : "off",
582                                         PGC_INTERNAL, PGC_S_OVERRIDE);
583 }
584
585
586 /*
587  * Get user name from user oid
588  */
589 char *
590 GetUserNameFromId(Oid roleid)
591 {
592         HeapTuple       tuple;
593         char       *result;
594
595         tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
596         if (!HeapTupleIsValid(tuple))
597                 ereport(ERROR,
598                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
599                                  errmsg("invalid role OID: %u", roleid)));
600
601         result = pstrdup(NameStr(((Form_pg_authid) GETSTRUCT(tuple))->rolname));
602
603         ReleaseSysCache(tuple);
604         return result;
605 }
606
607
608 /*-------------------------------------------------------------------------
609  *                              Interlock-file support
610  *
611  * These routines are used to create both a data-directory lockfile
612  * ($DATADIR/postmaster.pid) and a Unix-socket-file lockfile ($SOCKFILE.lock).
613  * Both kinds of files contain the same info:
614  *
615  *              Owning process' PID
616  *              Data directory path
617  *
618  * By convention, the owning process' PID is negated if it is a standalone
619  * backend rather than a postmaster.  This is just for informational purposes.
620  * The path is also just for informational purposes (so that a socket lockfile
621  * can be more easily traced to the associated postmaster).
622  *
623  * A data-directory lockfile can optionally contain a third line, containing
624  * the key and ID for the shared memory block used by this postmaster.
625  *
626  * On successful lockfile creation, a proc_exit callback to remove the
627  * lockfile is automatically created.
628  *-------------------------------------------------------------------------
629  */
630
631 /*
632  * proc_exit callback to remove a lockfile.
633  */
634 static void
635 UnlinkLockFile(int status, Datum filename)
636 {
637         char       *fname = (char *) DatumGetPointer(filename);
638
639         if (fname != NULL)
640         {
641                 if (unlink(fname) != 0)
642                 {
643                         /* Should we complain if the unlink fails? */
644                 }
645                 free(fname);
646         }
647 }
648
649 /*
650  * Create a lockfile.
651  *
652  * filename is the name of the lockfile to create.
653  * amPostmaster is used to determine how to encode the output PID.
654  * isDDLock and refName are used to determine what error message to produce.
655  */
656 static void
657 CreateLockFile(const char *filename, bool amPostmaster,
658                            bool isDDLock, const char *refName)
659 {
660         int                     fd;
661         char            buffer[MAXPGPATH + 100];
662         int                     ntries;
663         int                     len;
664         int                     encoded_pid;
665         pid_t           other_pid;
666         pid_t           my_pid,
667                                 my_p_pid,
668                                 my_gp_pid;
669         const char *envvar;
670
671         /*
672          * If the PID in the lockfile is our own PID or our parent's or
673          * grandparent's PID, then the file must be stale (probably left over from
674          * a previous system boot cycle).  We need to check this because of the
675          * likelihood that a reboot will assign exactly the same PID as we had in
676          * the previous reboot, or one that's only one or two counts larger and
677          * hence the lockfile's PID now refers to an ancestor shell process.  We
678          * allow pg_ctl to pass down its parent shell PID (our grandparent PID)
679          * via the environment variable PG_GRANDPARENT_PID; this is so that
680          * launching the postmaster via pg_ctl can be just as reliable as
681          * launching it directly.  There is no provision for detecting
682          * further-removed ancestor processes, but if the init script is written
683          * carefully then all but the immediate parent shell will be root-owned
684          * processes and so the kill test will fail with EPERM.  Note that we
685          * cannot get a false negative this way, because an existing postmaster
686          * would surely never launch a competing postmaster or pg_ctl process
687          * directly.
688          */
689         my_pid = getpid();
690
691 #ifndef WIN32
692         my_p_pid = getppid();
693 #else
694
695         /*
696          * Windows hasn't got getppid(), but doesn't need it since it's not using
697          * real kill() either...
698          */
699         my_p_pid = 0;
700 #endif
701
702         envvar = getenv("PG_GRANDPARENT_PID");
703         if (envvar)
704                 my_gp_pid = atoi(envvar);
705         else
706                 my_gp_pid = 0;
707
708         /*
709          * We need a loop here because of race conditions.      But don't loop forever
710          * (for example, a non-writable $PGDATA directory might cause a failure
711          * that won't go away).  100 tries seems like plenty.
712          */
713         for (ntries = 0;; ntries++)
714         {
715                 /*
716                  * Try to create the lock file --- O_EXCL makes this atomic.
717                  *
718                  * Think not to make the file protection weaker than 0600.      See
719                  * comments below.
720                  */
721                 fd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
722                 if (fd >= 0)
723                         break;                          /* Success; exit the retry loop */
724
725                 /*
726                  * Couldn't create the pid file. Probably it already exists.
727                  */
728                 if ((errno != EEXIST && errno != EACCES) || ntries > 100)
729                         ereport(FATAL,
730                                         (errcode_for_file_access(),
731                                          errmsg("could not create lock file \"%s\": %m",
732                                                         filename)));
733
734                 /*
735                  * Read the file to get the old owner's PID.  Note race condition
736                  * here: file might have been deleted since we tried to create it.
737                  */
738                 fd = open(filename, O_RDONLY, 0600);
739                 if (fd < 0)
740                 {
741                         if (errno == ENOENT)
742                                 continue;               /* race condition; try again */
743                         ereport(FATAL,
744                                         (errcode_for_file_access(),
745                                          errmsg("could not open lock file \"%s\": %m",
746                                                         filename)));
747                 }
748                 if ((len = read(fd, buffer, sizeof(buffer) - 1)) < 0)
749                         ereport(FATAL,
750                                         (errcode_for_file_access(),
751                                          errmsg("could not read lock file \"%s\": %m",
752                                                         filename)));
753                 close(fd);
754
755                 buffer[len] = '\0';
756                 encoded_pid = atoi(buffer);
757
758                 /* if pid < 0, the pid is for postgres, not postmaster */
759                 other_pid = (pid_t) (encoded_pid < 0 ? -encoded_pid : encoded_pid);
760
761                 if (other_pid <= 0)
762                         elog(FATAL, "bogus data in lock file \"%s\": \"%s\"",
763                                  filename, buffer);
764
765                 /*
766                  * Check to see if the other process still exists
767                  *
768                  * Per discussion above, my_pid, my_p_pid, and my_gp_pid can be
769                  * ignored as false matches.
770                  *
771                  * Normally kill() will fail with ESRCH if the given PID doesn't
772                  * exist.
773                  *
774                  * We can treat the EPERM-error case as okay because that error
775                  * implies that the existing process has a different userid than we
776                  * do, which means it cannot be a competing postmaster.  A postmaster
777                  * cannot successfully attach to a data directory owned by a userid
778                  * other than its own.  (This is now checked directly in
779                  * checkDataDir(), but has been true for a long time because of the
780                  * restriction that the data directory isn't group- or
781                  * world-accessible.)  Also, since we create the lockfiles mode 600,
782                  * we'd have failed above if the lockfile belonged to another userid
783                  * --- which means that whatever process kill() is reporting about
784                  * isn't the one that made the lockfile.  (NOTE: this last
785                  * consideration is the only one that keeps us from blowing away a
786                  * Unix socket file belonging to an instance of Postgres being run by
787                  * someone else, at least on machines where /tmp hasn't got a
788                  * stickybit.)
789                  */
790                 if (other_pid != my_pid && other_pid != my_p_pid &&
791                         other_pid != my_gp_pid)
792                 {
793                         if (kill(other_pid, 0) == 0 ||
794                                 (errno != ESRCH && errno != EPERM))
795                         {
796                                 /* lockfile belongs to a live process */
797                                 ereport(FATAL,
798                                                 (errcode(ERRCODE_LOCK_FILE_EXISTS),
799                                                  errmsg("lock file \"%s\" already exists",
800                                                                 filename),
801                                                  isDDLock ?
802                                                  (encoded_pid < 0 ?
803                                                   errhint("Is another postgres (PID %d) running in data directory \"%s\"?",
804                                                                   (int) other_pid, refName) :
805                                                   errhint("Is another postmaster (PID %d) running in data directory \"%s\"?",
806                                                                   (int) other_pid, refName)) :
807                                                  (encoded_pid < 0 ?
808                                                   errhint("Is another postgres (PID %d) using socket file \"%s\"?",
809                                                                   (int) other_pid, refName) :
810                                                   errhint("Is another postmaster (PID %d) using socket file \"%s\"?",
811                                                                   (int) other_pid, refName))));
812                         }
813                 }
814
815                 /*
816                  * No, the creating process did not exist.      However, it could be that
817                  * the postmaster crashed (or more likely was kill -9'd by a clueless
818                  * admin) but has left orphan backends behind.  Check for this by
819                  * looking to see if there is an associated shmem segment that is
820                  * still in use.
821                  *
822                  * Note: because postmaster.pid is written in two steps, we might not
823                  * find the shmem ID values in it; we can't treat that as an error.
824                  */
825                 if (isDDLock)
826                 {
827                         char       *ptr;
828                         unsigned long id1,
829                                                 id2;
830
831                         ptr = strchr(buffer, '\n');
832                         if (ptr != NULL &&
833                                 (ptr = strchr(ptr + 1, '\n')) != NULL)
834                         {
835                                 ptr++;
836                                 if (sscanf(ptr, "%lu %lu", &id1, &id2) == 2)
837                                 {
838                                         if (PGSharedMemoryIsInUse(id1, id2))
839                                                 ereport(FATAL,
840                                                                 (errcode(ERRCODE_LOCK_FILE_EXISTS),
841                                                                  errmsg("pre-existing shared memory block "
842                                                                                 "(key %lu, ID %lu) is still in use",
843                                                                                 id1, id2),
844                                                                  errhint("If you're sure there are no old "
845                                                                         "server processes still running, remove "
846                                                                                  "the shared memory block "
847                                                                                  "or just delete the file \"%s\".",
848                                                                                  filename)));
849                                 }
850                         }
851                 }
852
853                 /*
854                  * Looks like nobody's home.  Unlink the file and try again to create
855                  * it.  Need a loop because of possible race condition against other
856                  * would-be creators.
857                  */
858                 if (unlink(filename) < 0)
859                         ereport(FATAL,
860                                         (errcode_for_file_access(),
861                                          errmsg("could not remove old lock file \"%s\": %m",
862                                                         filename),
863                                          errhint("The file seems accidentally left over, but "
864                                                    "it could not be removed. Please remove the file "
865                                                          "by hand and try again.")));
866         }
867
868         /*
869          * Successfully created the file, now fill it.
870          */
871         snprintf(buffer, sizeof(buffer), "%d\n%s\n",
872                          amPostmaster ? (int) my_pid : -((int) my_pid),
873                          DataDir);
874         errno = 0;
875         if (write(fd, buffer, strlen(buffer)) != strlen(buffer))
876         {
877                 int                     save_errno = errno;
878
879                 close(fd);
880                 unlink(filename);
881                 /* if write didn't set errno, assume problem is no disk space */
882                 errno = save_errno ? save_errno : ENOSPC;
883                 ereport(FATAL,
884                                 (errcode_for_file_access(),
885                                  errmsg("could not write lock file \"%s\": %m", filename)));
886         }
887         if (pg_fsync(fd) != 0)
888         {
889                 int                     save_errno = errno;
890
891                 close(fd);
892                 unlink(filename);
893                 errno = save_errno;
894                 ereport(FATAL,
895                                 (errcode_for_file_access(),
896                                  errmsg("could not write lock file \"%s\": %m", filename)));
897         }
898         if (close(fd) != 0)
899         {
900                 int                     save_errno = errno;
901
902                 unlink(filename);
903                 errno = save_errno;
904                 ereport(FATAL,
905                                 (errcode_for_file_access(),
906                                  errmsg("could not write lock file \"%s\": %m", filename)));
907         }
908
909         /*
910          * Arrange for automatic removal of lockfile at proc_exit.
911          */
912         on_proc_exit(UnlinkLockFile, PointerGetDatum(strdup(filename)));
913 }
914
915 /*
916  * Create the data directory lockfile.
917  *
918  * When this is called, we must have already switched the working
919  * directory to DataDir, so we can just use a relative path.  This
920  * helps ensure that we are locking the directory we should be.
921  */
922 void
923 CreateDataDirLockFile(bool amPostmaster)
924 {
925         CreateLockFile(DIRECTORY_LOCK_FILE, amPostmaster, true, DataDir);
926 }
927
928 /*
929  * Create a lockfile for the specified Unix socket file.
930  */
931 void
932 CreateSocketLockFile(const char *socketfile, bool amPostmaster)
933 {
934         char            lockfile[MAXPGPATH];
935
936         snprintf(lockfile, sizeof(lockfile), "%s.lock", socketfile);
937         CreateLockFile(lockfile, amPostmaster, false, socketfile);
938         /* Save name of lockfile for TouchSocketLockFile */
939         strcpy(socketLockFile, lockfile);
940 }
941
942 /*
943  * TouchSocketLockFile -- mark socket lock file as recently accessed
944  *
945  * This routine should be called every so often to ensure that the lock file
946  * has a recent mod or access date.  That saves it
947  * from being removed by overenthusiastic /tmp-directory-cleaner daemons.
948  * (Another reason we should never have put the socket file in /tmp...)
949  */
950 void
951 TouchSocketLockFile(void)
952 {
953         /* Do nothing if we did not create a socket... */
954         if (socketLockFile[0] != '\0')
955         {
956                 /*
957                  * utime() is POSIX standard, utimes() is a common alternative; if we
958                  * have neither, fall back to actually reading the file (which only
959                  * sets the access time not mod time, but that should be enough in
960                  * most cases).  In all paths, we ignore errors.
961                  */
962 #ifdef HAVE_UTIME
963                 utime(socketLockFile, NULL);
964 #else                                                   /* !HAVE_UTIME */
965 #ifdef HAVE_UTIMES
966                 utimes(socketLockFile, NULL);
967 #else                                                   /* !HAVE_UTIMES */
968                 int                     fd;
969                 char            buffer[1];
970
971                 fd = open(socketLockFile, O_RDONLY | PG_BINARY, 0);
972                 if (fd >= 0)
973                 {
974                         read(fd, buffer, sizeof(buffer));
975                         close(fd);
976                 }
977 #endif   /* HAVE_UTIMES */
978 #endif   /* HAVE_UTIME */
979         }
980 }
981
982 /*
983  * Append information about a shared memory segment to the data directory
984  * lock file.
985  *
986  * This may be called multiple times in the life of a postmaster, if we
987  * delete and recreate shmem due to backend crash.      Therefore, be prepared
988  * to overwrite existing information.  (As of 7.1, a postmaster only creates
989  * one shm seg at a time; but for the purposes here, if we did have more than
990  * one then any one of them would do anyway.)
991  */
992 void
993 RecordSharedMemoryInLockFile(unsigned long id1, unsigned long id2)
994 {
995         int                     fd;
996         int                     len;
997         char       *ptr;
998         char            buffer[BLCKSZ];
999
1000         fd = open(DIRECTORY_LOCK_FILE, O_RDWR | PG_BINARY, 0);
1001         if (fd < 0)
1002         {
1003                 ereport(LOG,
1004                                 (errcode_for_file_access(),
1005                                  errmsg("could not open file \"%s\": %m",
1006                                                 DIRECTORY_LOCK_FILE)));
1007                 return;
1008         }
1009         len = read(fd, buffer, sizeof(buffer) - 100);
1010         if (len < 0)
1011         {
1012                 ereport(LOG,
1013                                 (errcode_for_file_access(),
1014                                  errmsg("could not read from file \"%s\": %m",
1015                                                 DIRECTORY_LOCK_FILE)));
1016                 close(fd);
1017                 return;
1018         }
1019         buffer[len] = '\0';
1020
1021         /*
1022          * Skip over first two lines (PID and path).
1023          */
1024         ptr = strchr(buffer, '\n');
1025         if (ptr == NULL ||
1026                 (ptr = strchr(ptr + 1, '\n')) == NULL)
1027         {
1028                 elog(LOG, "bogus data in \"%s\"", DIRECTORY_LOCK_FILE);
1029                 close(fd);
1030                 return;
1031         }
1032         ptr++;
1033
1034         /*
1035          * Append key information.      Format to try to keep it the same length
1036          * always (trailing junk won't hurt, but might confuse humans).
1037          */
1038         sprintf(ptr, "%9lu %9lu\n", id1, id2);
1039
1040         /*
1041          * And rewrite the data.  Since we write in a single kernel call, this
1042          * update should appear atomic to onlookers.
1043          */
1044         len = strlen(buffer);
1045         errno = 0;
1046         if (lseek(fd, (off_t) 0, SEEK_SET) != 0 ||
1047                 (int) write(fd, buffer, len) != len)
1048         {
1049                 /* if write didn't set errno, assume problem is no disk space */
1050                 if (errno == 0)
1051                         errno = ENOSPC;
1052                 ereport(LOG,
1053                                 (errcode_for_file_access(),
1054                                  errmsg("could not write to file \"%s\": %m",
1055                                                 DIRECTORY_LOCK_FILE)));
1056                 close(fd);
1057                 return;
1058         }
1059         if (pg_fsync(fd) != 0)
1060         {
1061                 ereport(LOG,
1062                                 (errcode_for_file_access(),
1063                                  errmsg("could not write to file \"%s\": %m",
1064                                                 DIRECTORY_LOCK_FILE)));
1065         }
1066         if (close(fd) != 0)
1067         {
1068                 ereport(LOG,
1069                                 (errcode_for_file_access(),
1070                                  errmsg("could not write to file \"%s\": %m",
1071                                                 DIRECTORY_LOCK_FILE)));
1072         }
1073 }
1074
1075
1076 /*-------------------------------------------------------------------------
1077  *                              Version checking support
1078  *-------------------------------------------------------------------------
1079  */
1080
1081 /*
1082  * Determine whether the PG_VERSION file in directory `path' indicates
1083  * a data version compatible with the version of this program.
1084  *
1085  * If compatible, return. Otherwise, ereport(FATAL).
1086  */
1087 void
1088 ValidatePgVersion(const char *path)
1089 {
1090         char            full_path[MAXPGPATH];
1091         FILE       *file;
1092         int                     ret;
1093         long            file_major,
1094                                 file_minor;
1095         long            my_major = 0,
1096                                 my_minor = 0;
1097         char       *endptr;
1098         const char *version_string = PG_VERSION;
1099
1100         my_major = strtol(version_string, &endptr, 10);
1101         if (*endptr == '.')
1102                 my_minor = strtol(endptr + 1, NULL, 10);
1103
1104         snprintf(full_path, sizeof(full_path), "%s/PG_VERSION", path);
1105
1106         file = AllocateFile(full_path, "r");
1107         if (!file)
1108         {
1109                 if (errno == ENOENT)
1110                         ereport(FATAL,
1111                                         (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1112                                          errmsg("\"%s\" is not a valid data directory",
1113                                                         path),
1114                                          errdetail("File \"%s\" is missing.", full_path)));
1115                 else
1116                         ereport(FATAL,
1117                                         (errcode_for_file_access(),
1118                                          errmsg("could not open file \"%s\": %m", full_path)));
1119         }
1120
1121         ret = fscanf(file, "%ld.%ld", &file_major, &file_minor);
1122         if (ret != 2)
1123                 ereport(FATAL,
1124                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1125                                  errmsg("\"%s\" is not a valid data directory",
1126                                                 path),
1127                                  errdetail("File \"%s\" does not contain valid data.",
1128                                                    full_path),
1129                                  errhint("You might need to initdb.")));
1130
1131         FreeFile(file);
1132
1133         if (my_major != file_major || my_minor != file_minor)
1134                 ereport(FATAL,
1135                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1136                                  errmsg("database files are incompatible with server"),
1137                                  errdetail("The data directory was initialized by PostgreSQL version %ld.%ld, "
1138                                                    "which is not compatible with this version %s.",
1139                                                    file_major, file_minor, version_string)));
1140 }
1141
1142 /*-------------------------------------------------------------------------
1143  *                              Library preload support
1144  *-------------------------------------------------------------------------
1145  */
1146
1147 /*
1148  * GUC variables: lists of library names to be preloaded at postmaster
1149  * start and at backend start
1150  */
1151 char       *shared_preload_libraries_string = NULL;
1152 char       *local_preload_libraries_string = NULL;
1153
1154 /* Flag telling that we are loading shared_preload_libraries */
1155 bool            process_shared_preload_libraries_in_progress = false;
1156
1157 /*
1158  * load the shared libraries listed in 'libraries'
1159  *
1160  * 'gucname': name of GUC variable, for error reports
1161  * 'restricted': if true, force libraries to be in $libdir/plugins/
1162  */
1163 static void
1164 load_libraries(const char *libraries, const char *gucname, bool restricted)
1165 {
1166         char       *rawstring;
1167         List       *elemlist;
1168         int                     elevel;
1169         ListCell   *l;
1170
1171         if (libraries == NULL || libraries[0] == '\0')
1172                 return;                                 /* nothing to do */
1173
1174         /* Need a modifiable copy of string */
1175         rawstring = pstrdup(libraries);
1176
1177         /* Parse string into list of identifiers */
1178         if (!SplitIdentifierString(rawstring, ',', &elemlist))
1179         {
1180                 /* syntax error in list */
1181                 pfree(rawstring);
1182                 list_free(elemlist);
1183                 ereport(LOG,
1184                                 (errcode(ERRCODE_SYNTAX_ERROR),
1185                                  errmsg("invalid list syntax in parameter \"%s\"",
1186                                                 gucname)));
1187                 return;
1188         }
1189
1190         /*
1191          * Choose notice level: avoid repeat messages when re-loading a library
1192          * that was preloaded into the postmaster.      (Only possible in EXEC_BACKEND
1193          * configurations)
1194          */
1195 #ifdef EXEC_BACKEND
1196         if (IsUnderPostmaster && process_shared_preload_libraries_in_progress)
1197                 elevel = DEBUG2;
1198         else
1199 #endif
1200                 elevel = LOG;
1201
1202         foreach(l, elemlist)
1203         {
1204                 char       *tok = (char *) lfirst(l);
1205                 char       *filename;
1206
1207                 filename = pstrdup(tok);
1208                 canonicalize_path(filename);
1209                 /* If restricting, insert $libdir/plugins if not mentioned already */
1210                 if (restricted && first_dir_separator(filename) == NULL)
1211                 {
1212                         char       *expanded;
1213
1214                         expanded = palloc(strlen("$libdir/plugins/") + strlen(filename) + 1);
1215                         strcpy(expanded, "$libdir/plugins/");
1216                         strcat(expanded, filename);
1217                         pfree(filename);
1218                         filename = expanded;
1219                 }
1220                 load_file(filename, restricted);
1221                 ereport(elevel,
1222                                 (errmsg("loaded library \"%s\"", filename)));
1223                 pfree(filename);
1224         }
1225
1226         pfree(rawstring);
1227         list_free(elemlist);
1228 }
1229
1230 /*
1231  * process any libraries that should be preloaded at postmaster start
1232  */
1233 void
1234 process_shared_preload_libraries(void)
1235 {
1236         process_shared_preload_libraries_in_progress = true;
1237         load_libraries(shared_preload_libraries_string,
1238                                    "shared_preload_libraries",
1239                                    false);
1240         process_shared_preload_libraries_in_progress = false;
1241 }
1242
1243 /*
1244  * process any libraries that should be preloaded at backend start
1245  */
1246 void
1247 process_local_preload_libraries(void)
1248 {
1249         load_libraries(local_preload_libraries_string,
1250                                    "local_preload_libraries",
1251                                    true);
1252 }
1253
1254 void
1255 pg_bindtextdomain(const char *domain)
1256 {
1257 #ifdef ENABLE_NLS
1258         if (my_exec_path[0] != '\0')
1259         {
1260                 char            locale_path[MAXPGPATH];
1261
1262                 get_locale_path(my_exec_path, locale_path);
1263                 bindtextdomain(domain, locale_path);
1264                 pg_bind_textdomain_codeset(domain);
1265         }
1266 #endif
1267 }