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