]> granicus.if.org Git - postgresql/blob - src/backend/utils/init/miscinit.c
Seems some C compilers think 'restrict' is a fully reserved word.
[postgresql] / src / backend / utils / init / miscinit.c
1 /*-------------------------------------------------------------------------
2  *
3  * miscinit.c
4  *        miscellaneous initialization support stuff
5  *
6  * Portions Copyright (c) 1996-2006, 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.158 2006/08/16 04:32:48 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 && !IsAutoVacuumProcess())
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                 ProcessGUCArray(a, PGC_S_USER);
452         }
453
454         ReleaseSysCache(roleTup);
455 }
456
457
458 /*
459  * Initialize user identity during special backend startup
460  */
461 void
462 InitializeSessionUserIdStandalone(void)
463 {
464         /* This function should only be called in a single-user backend. */
465         AssertState(!IsUnderPostmaster || IsAutoVacuumProcess());
466
467         /* call only once */
468         AssertState(!OidIsValid(AuthenticatedUserId));
469
470         AuthenticatedUserId = BOOTSTRAP_SUPERUSERID;
471         AuthenticatedUserIsSuperuser = true;
472
473         SetSessionUserId(BOOTSTRAP_SUPERUSERID, true);
474 }
475
476
477 /*
478  * Reset effective userid during AbortTransaction
479  *
480  * This is essentially SetUserId(GetOuterUserId()), but without the Asserts.
481  * The reason is that if a backend's InitPostgres transaction fails (eg,
482  * because an invalid user name was given), we have to be able to get through
483  * AbortTransaction without asserting.
484  */
485 void
486 AtAbort_UserId(void)
487 {
488         CurrentUserId = OuterUserId;
489 }
490
491
492 /*
493  * Change session auth ID while running
494  *
495  * Only a superuser may set auth ID to something other than himself.  Note
496  * that in case of multiple SETs in a single session, the original userid's
497  * superuserness is what matters.  But we set the GUC variable is_superuser
498  * to indicate whether the *current* session userid is a superuser.
499  *
500  * Note: this is not an especially clean place to do the permission check.
501  * It's OK because the check does not require catalog access and can't
502  * fail during an end-of-transaction GUC reversion, but we may someday
503  * have to push it up into assign_session_authorization.
504  */
505 void
506 SetSessionAuthorization(Oid userid, bool is_superuser)
507 {
508         /* Must have authenticated already, else can't make permission check */
509         AssertState(OidIsValid(AuthenticatedUserId));
510
511         if (userid != AuthenticatedUserId &&
512                 !AuthenticatedUserIsSuperuser)
513                 ereport(ERROR,
514                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
515                                  errmsg("permission denied to set session authorization")));
516
517         SetSessionUserId(userid, is_superuser);
518
519         SetConfigOption("is_superuser",
520                                         is_superuser ? "on" : "off",
521                                         PGC_INTERNAL, PGC_S_OVERRIDE);
522 }
523
524 /*
525  * Report current role id
526  *              This follows the semantics of SET ROLE, ie return the outer-level ID
527  *              not the current effective ID, and return InvalidOid when the setting
528  *              is logically SET ROLE NONE.
529  */
530 Oid
531 GetCurrentRoleId(void)
532 {
533         if (SetRoleIsActive)
534                 return OuterUserId;
535         else
536                 return InvalidOid;
537 }
538
539 /*
540  * Change Role ID while running (SET ROLE)
541  *
542  * If roleid is InvalidOid, we are doing SET ROLE NONE: revert to the
543  * session user authorization.  In this case the is_superuser argument
544  * is ignored.
545  *
546  * When roleid is not InvalidOid, the caller must have checked whether
547  * the session user has permission to become that role.  (We cannot check
548  * here because this routine must be able to execute in a failed transaction
549  * to restore a prior value of the ROLE GUC variable.)
550  */
551 void
552 SetCurrentRoleId(Oid roleid, bool is_superuser)
553 {
554         /*
555          * Get correct info if it's SET ROLE NONE
556          *
557          * If SessionUserId hasn't been set yet, just do nothing --- the eventual
558          * SetSessionUserId call will fix everything.  This is needed since we
559          * will get called during GUC initialization.
560          */
561         if (!OidIsValid(roleid))
562         {
563                 if (!OidIsValid(SessionUserId))
564                         return;
565
566                 roleid = SessionUserId;
567                 is_superuser = SessionUserIsSuperuser;
568
569                 SetRoleIsActive = false;
570         }
571         else
572                 SetRoleIsActive = true;
573
574         SetOuterUserId(roleid);
575
576         SetConfigOption("is_superuser",
577                                         is_superuser ? "on" : "off",
578                                         PGC_INTERNAL, PGC_S_OVERRIDE);
579 }
580
581
582 /*
583  * Get user name from user oid
584  */
585 char *
586 GetUserNameFromId(Oid roleid)
587 {
588         HeapTuple       tuple;
589         char       *result;
590
591         tuple = SearchSysCache(AUTHOID,
592                                                    ObjectIdGetDatum(roleid),
593                                                    0, 0, 0);
594         if (!HeapTupleIsValid(tuple))
595                 ereport(ERROR,
596                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
597                                  errmsg("invalid role OID: %u", roleid)));
598
599         result = pstrdup(NameStr(((Form_pg_authid) GETSTRUCT(tuple))->rolname));
600
601         ReleaseSysCache(tuple);
602         return result;
603 }
604
605
606 /*-------------------------------------------------------------------------
607  *                              Interlock-file support
608  *
609  * These routines are used to create both a data-directory lockfile
610  * ($DATADIR/postmaster.pid) and a Unix-socket-file lockfile ($SOCKFILE.lock).
611  * Both kinds of files contain the same info:
612  *
613  *              Owning process' PID
614  *              Data directory path
615  *
616  * By convention, the owning process' PID is negated if it is a standalone
617  * backend rather than a postmaster.  This is just for informational purposes.
618  * The path is also just for informational purposes (so that a socket lockfile
619  * can be more easily traced to the associated postmaster).
620  *
621  * A data-directory lockfile can optionally contain a third line, containing
622  * the key and ID for the shared memory block used by this postmaster.
623  *
624  * On successful lockfile creation, a proc_exit callback to remove the
625  * lockfile is automatically created.
626  *-------------------------------------------------------------------------
627  */
628
629 /*
630  * proc_exit callback to remove a lockfile.
631  */
632 static void
633 UnlinkLockFile(int status, Datum filename)
634 {
635         char       *fname = (char *) DatumGetPointer(filename);
636
637         if (fname != NULL)
638         {
639                 if (unlink(fname) != 0)
640                 {
641                         /* Should we complain if the unlink fails? */
642                 }
643                 free(fname);
644         }
645 }
646
647 /*
648  * Create a lockfile.
649  *
650  * filename is the name of the lockfile to create.
651  * amPostmaster is used to determine how to encode the output PID.
652  * isDDLock and refName are used to determine what error message to produce.
653  */
654 static void
655 CreateLockFile(const char *filename, bool amPostmaster,
656                            bool isDDLock, const char *refName)
657 {
658         int                     fd;
659         char            buffer[MAXPGPATH + 100];
660         int                     ntries;
661         int                     len;
662         int                     encoded_pid;
663         pid_t           other_pid;
664         pid_t           my_pid = getpid();
665
666         /*
667          * We need a loop here because of race conditions.      But don't loop forever
668          * (for example, a non-writable $PGDATA directory might cause a failure
669          * that won't go away).  100 tries seems like plenty.
670          */
671         for (ntries = 0;; ntries++)
672         {
673                 /*
674                  * Try to create the lock file --- O_EXCL makes this atomic.
675                  *
676                  * Think not to make the file protection weaker than 0600.      See
677                  * comments below.
678                  */
679                 fd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
680                 if (fd >= 0)
681                         break;                          /* Success; exit the retry loop */
682
683                 /*
684                  * Couldn't create the pid file. Probably it already exists.
685                  */
686                 if ((errno != EEXIST && errno != EACCES) || ntries > 100)
687                         ereport(FATAL,
688                                         (errcode_for_file_access(),
689                                          errmsg("could not create lock file \"%s\": %m",
690                                                         filename)));
691
692                 /*
693                  * Read the file to get the old owner's PID.  Note race condition
694                  * here: file might have been deleted since we tried to create it.
695                  */
696                 fd = open(filename, O_RDONLY, 0600);
697                 if (fd < 0)
698                 {
699                         if (errno == ENOENT)
700                                 continue;               /* race condition; try again */
701                         ereport(FATAL,
702                                         (errcode_for_file_access(),
703                                          errmsg("could not open lock file \"%s\": %m",
704                                                         filename)));
705                 }
706                 if ((len = read(fd, buffer, sizeof(buffer) - 1)) < 0)
707                         ereport(FATAL,
708                                         (errcode_for_file_access(),
709                                          errmsg("could not read lock file \"%s\": %m",
710                                                         filename)));
711                 close(fd);
712
713                 buffer[len] = '\0';
714                 encoded_pid = atoi(buffer);
715
716                 /* if pid < 0, the pid is for postgres, not postmaster */
717                 other_pid = (pid_t) (encoded_pid < 0 ? -encoded_pid : encoded_pid);
718
719                 if (other_pid <= 0)
720                         elog(FATAL, "bogus data in lock file \"%s\": \"%s\"",
721                                  filename, buffer);
722
723                 /*
724                  * Check to see if the other process still exists
725                  *
726                  * If the PID in the lockfile is our own PID or our parent's PID, then
727                  * the file must be stale (probably left over from a previous system
728                  * boot cycle).  We need this test because of the likelihood that a
729                  * reboot will assign exactly the same PID as we had in the previous
730                  * reboot.      Also, if there is just one more process launch in this
731                  * reboot than in the previous one, the lockfile might mention our
732                  * parent's PID.  We can reject that since we'd never be launched
733                  * directly by a competing postmaster.  We can't detect grandparent
734                  * processes unfortunately, but if the init script is written
735                  * carefully then all but the immediate parent shell will be
736                  * root-owned processes and so the kill test will fail with EPERM.
737                  *
738                  * We can treat the EPERM-error case as okay because that error
739                  * implies that the existing process has a different userid than we
740                  * do, which means it cannot be a competing postmaster.  A postmaster
741                  * cannot successfully attach to a data directory owned by a userid
742                  * other than its own.  (This is now checked directly in
743                  * checkDataDir(), but has been true for a long time because of the
744                  * restriction that the data directory isn't group- or
745                  * world-accessible.)  Also, since we create the lockfiles mode 600,
746                  * we'd have failed above if the lockfile belonged to another userid
747                  * --- which means that whatever process kill() is reporting about
748                  * isn't the one that made the lockfile.  (NOTE: this last
749                  * consideration is the only one that keeps us from blowing away a
750                  * Unix socket file belonging to an instance of Postgres being run by
751                  * someone else, at least on machines where /tmp hasn't got a
752                  * stickybit.)
753                  *
754                  * Windows hasn't got getppid(), but doesn't need it since it's not
755                  * using real kill() either...
756                  *
757                  * Normally kill() will fail with ESRCH if the given PID doesn't
758                  * exist.
759                  */
760                 if (other_pid != my_pid
761 #ifndef WIN32
762                         && other_pid != getppid()
763 #endif
764                         )
765                 {
766                         if (kill(other_pid, 0) == 0 ||
767                                 (errno != ESRCH && errno != EPERM))
768                         {
769                                 /* lockfile belongs to a live process */
770                                 ereport(FATAL,
771                                                 (errcode(ERRCODE_LOCK_FILE_EXISTS),
772                                                  errmsg("lock file \"%s\" already exists",
773                                                                 filename),
774                                                  isDDLock ?
775                                                  (encoded_pid < 0 ?
776                                                   errhint("Is another postgres (PID %d) running in data directory \"%s\"?",
777                                                                   (int) other_pid, refName) :
778                                                   errhint("Is another postmaster (PID %d) running in data directory \"%s\"?",
779                                                                   (int) other_pid, refName)) :
780                                                  (encoded_pid < 0 ?
781                                                   errhint("Is another postgres (PID %d) using socket file \"%s\"?",
782                                                                   (int) other_pid, refName) :
783                                                   errhint("Is another postmaster (PID %d) using socket file \"%s\"?",
784                                                                   (int) other_pid, refName))));
785                         }
786                 }
787
788                 /*
789                  * No, the creating process did not exist.      However, it could be that
790                  * the postmaster crashed (or more likely was kill -9'd by a clueless
791                  * admin) but has left orphan backends behind.  Check for this by
792                  * looking to see if there is an associated shmem segment that is
793                  * still in use.
794                  */
795                 if (isDDLock)
796                 {
797                         char       *ptr;
798                         unsigned long id1,
799                                                 id2;
800
801                         ptr = strchr(buffer, '\n');
802                         if (ptr != NULL &&
803                                 (ptr = strchr(ptr + 1, '\n')) != NULL)
804                         {
805                                 ptr++;
806                                 if (sscanf(ptr, "%lu %lu", &id1, &id2) == 2)
807                                 {
808                                         if (PGSharedMemoryIsInUse(id1, id2))
809                                                 ereport(FATAL,
810                                                                 (errcode(ERRCODE_LOCK_FILE_EXISTS),
811                                                                  errmsg("pre-existing shared memory block "
812                                                                                 "(key %lu, ID %lu) is still in use",
813                                                                                 id1, id2),
814                                                                  errhint("If you're sure there are no old "
815                                                                         "server processes still running, remove "
816                                                                                  "the shared memory block with "
817                                                                           "the command \"ipcclean\", \"ipcrm\", "
818                                                                                  "or just delete the file \"%s\".",
819                                                                                  filename)));
820                                 }
821                         }
822                 }
823
824                 /*
825                  * Looks like nobody's home.  Unlink the file and try again to create
826                  * it.  Need a loop because of possible race condition against other
827                  * would-be creators.
828                  */
829                 if (unlink(filename) < 0)
830                         ereport(FATAL,
831                                         (errcode_for_file_access(),
832                                          errmsg("could not remove old lock file \"%s\": %m",
833                                                         filename),
834                                          errhint("The file seems accidentally left over, but "
835                                                    "it could not be removed. Please remove the file "
836                                                          "by hand and try again.")));
837         }
838
839         /*
840          * Successfully created the file, now fill it.
841          */
842         snprintf(buffer, sizeof(buffer), "%d\n%s\n",
843                          amPostmaster ? (int) my_pid : -((int) my_pid),
844                          DataDir);
845         errno = 0;
846         if (write(fd, buffer, strlen(buffer)) != strlen(buffer))
847         {
848                 int                     save_errno = errno;
849
850                 close(fd);
851                 unlink(filename);
852                 /* if write didn't set errno, assume problem is no disk space */
853                 errno = save_errno ? save_errno : ENOSPC;
854                 ereport(FATAL,
855                                 (errcode_for_file_access(),
856                                  errmsg("could not write lock file \"%s\": %m", filename)));
857         }
858         if (close(fd))
859         {
860                 int                     save_errno = errno;
861
862                 unlink(filename);
863                 errno = save_errno;
864                 ereport(FATAL,
865                                 (errcode_for_file_access(),
866                                  errmsg("could not write lock file \"%s\": %m", filename)));
867         }
868
869         /*
870          * Arrange for automatic removal of lockfile at proc_exit.
871          */
872         on_proc_exit(UnlinkLockFile, PointerGetDatum(strdup(filename)));
873 }
874
875 /*
876  * Create the data directory lockfile.
877  *
878  * When this is called, we must have already switched the working
879  * directory to DataDir, so we can just use a relative path.  This
880  * helps ensure that we are locking the directory we should be.
881  */
882 void
883 CreateDataDirLockFile(bool amPostmaster)
884 {
885         CreateLockFile(DIRECTORY_LOCK_FILE, amPostmaster, true, DataDir);
886 }
887
888 /*
889  * Create a lockfile for the specified Unix socket file.
890  */
891 void
892 CreateSocketLockFile(const char *socketfile, bool amPostmaster)
893 {
894         char            lockfile[MAXPGPATH];
895
896         snprintf(lockfile, sizeof(lockfile), "%s.lock", socketfile);
897         CreateLockFile(lockfile, amPostmaster, false, socketfile);
898         /* Save name of lockfile for TouchSocketLockFile */
899         strcpy(socketLockFile, lockfile);
900 }
901
902 /*
903  * TouchSocketLockFile -- mark socket lock file as recently accessed
904  *
905  * This routine should be called every so often to ensure that the lock file
906  * has a recent mod or access date.  That saves it
907  * from being removed by overenthusiastic /tmp-directory-cleaner daemons.
908  * (Another reason we should never have put the socket file in /tmp...)
909  */
910 void
911 TouchSocketLockFile(void)
912 {
913         /* Do nothing if we did not create a socket... */
914         if (socketLockFile[0] != '\0')
915         {
916                 /*
917                  * utime() is POSIX standard, utimes() is a common alternative; if we
918                  * have neither, fall back to actually reading the file (which only
919                  * sets the access time not mod time, but that should be enough in
920                  * most cases).  In all paths, we ignore errors.
921                  */
922 #ifdef HAVE_UTIME
923                 utime(socketLockFile, NULL);
924 #else                                                   /* !HAVE_UTIME */
925 #ifdef HAVE_UTIMES
926                 utimes(socketLockFile, NULL);
927 #else                                                   /* !HAVE_UTIMES */
928                 int                     fd;
929                 char            buffer[1];
930
931                 fd = open(socketLockFile, O_RDONLY | PG_BINARY, 0);
932                 if (fd >= 0)
933                 {
934                         read(fd, buffer, sizeof(buffer));
935                         close(fd);
936                 }
937 #endif   /* HAVE_UTIMES */
938 #endif   /* HAVE_UTIME */
939         }
940 }
941
942 /*
943  * Append information about a shared memory segment to the data directory
944  * lock file.
945  *
946  * This may be called multiple times in the life of a postmaster, if we
947  * delete and recreate shmem due to backend crash.      Therefore, be prepared
948  * to overwrite existing information.  (As of 7.1, a postmaster only creates
949  * one shm seg at a time; but for the purposes here, if we did have more than
950  * one then any one of them would do anyway.)
951  */
952 void
953 RecordSharedMemoryInLockFile(unsigned long id1, unsigned long id2)
954 {
955         int                     fd;
956         int                     len;
957         char       *ptr;
958         char            buffer[BLCKSZ];
959
960         fd = open(DIRECTORY_LOCK_FILE, O_RDWR | PG_BINARY, 0);
961         if (fd < 0)
962         {
963                 ereport(LOG,
964                                 (errcode_for_file_access(),
965                                  errmsg("could not open file \"%s\": %m",
966                                                 DIRECTORY_LOCK_FILE)));
967                 return;
968         }
969         len = read(fd, buffer, sizeof(buffer) - 100);
970         if (len < 0)
971         {
972                 ereport(LOG,
973                                 (errcode_for_file_access(),
974                                  errmsg("could not read from file \"%s\": %m",
975                                                 DIRECTORY_LOCK_FILE)));
976                 close(fd);
977                 return;
978         }
979         buffer[len] = '\0';
980
981         /*
982          * Skip over first two lines (PID and path).
983          */
984         ptr = strchr(buffer, '\n');
985         if (ptr == NULL ||
986                 (ptr = strchr(ptr + 1, '\n')) == NULL)
987         {
988                 elog(LOG, "bogus data in \"%s\"", DIRECTORY_LOCK_FILE);
989                 close(fd);
990                 return;
991         }
992         ptr++;
993
994         /*
995          * Append key information.      Format to try to keep it the same length
996          * always (trailing junk won't hurt, but might confuse humans).
997          */
998         sprintf(ptr, "%9lu %9lu\n", id1, id2);
999
1000         /*
1001          * And rewrite the data.  Since we write in a single kernel call, this
1002          * update should appear atomic to onlookers.
1003          */
1004         len = strlen(buffer);
1005         errno = 0;
1006         if (lseek(fd, (off_t) 0, SEEK_SET) != 0 ||
1007                 (int) write(fd, buffer, len) != len)
1008         {
1009                 /* if write didn't set errno, assume problem is no disk space */
1010                 if (errno == 0)
1011                         errno = ENOSPC;
1012                 ereport(LOG,
1013                                 (errcode_for_file_access(),
1014                                  errmsg("could not write to file \"%s\": %m",
1015                                                 DIRECTORY_LOCK_FILE)));
1016                 close(fd);
1017                 return;
1018         }
1019         if (close(fd))
1020         {
1021                 ereport(LOG,
1022                                 (errcode_for_file_access(),
1023                                  errmsg("could not write to file \"%s\": %m",
1024                                                 DIRECTORY_LOCK_FILE)));
1025         }
1026 }
1027
1028
1029 /*-------------------------------------------------------------------------
1030  *                              Version checking support
1031  *-------------------------------------------------------------------------
1032  */
1033
1034 /*
1035  * Determine whether the PG_VERSION file in directory `path' indicates
1036  * a data version compatible with the version of this program.
1037  *
1038  * If compatible, return. Otherwise, ereport(FATAL).
1039  */
1040 void
1041 ValidatePgVersion(const char *path)
1042 {
1043         char            full_path[MAXPGPATH];
1044         FILE       *file;
1045         int                     ret;
1046         long            file_major,
1047                                 file_minor;
1048         long            my_major = 0,
1049                                 my_minor = 0;
1050         char       *endptr;
1051         const char *version_string = PG_VERSION;
1052
1053         my_major = strtol(version_string, &endptr, 10);
1054         if (*endptr == '.')
1055                 my_minor = strtol(endptr + 1, NULL, 10);
1056
1057         snprintf(full_path, sizeof(full_path), "%s/PG_VERSION", path);
1058
1059         file = AllocateFile(full_path, "r");
1060         if (!file)
1061         {
1062                 if (errno == ENOENT)
1063                         ereport(FATAL,
1064                                         (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1065                                          errmsg("\"%s\" is not a valid data directory",
1066                                                         path),
1067                                          errdetail("File \"%s\" is missing.", full_path)));
1068                 else
1069                         ereport(FATAL,
1070                                         (errcode_for_file_access(),
1071                                          errmsg("could not open file \"%s\": %m", full_path)));
1072         }
1073
1074         ret = fscanf(file, "%ld.%ld", &file_major, &file_minor);
1075         if (ret != 2)
1076                 ereport(FATAL,
1077                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1078                                  errmsg("\"%s\" is not a valid data directory",
1079                                                 path),
1080                                  errdetail("File \"%s\" does not contain valid data.",
1081                                                    full_path),
1082                                  errhint("You may need to initdb.")));
1083
1084         FreeFile(file);
1085
1086         if (my_major != file_major || my_minor != file_minor)
1087                 ereport(FATAL,
1088                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1089                                  errmsg("database files are incompatible with server"),
1090                                  errdetail("The data directory was initialized by PostgreSQL version %ld.%ld, "
1091                                                    "which is not compatible with this version %s.",
1092                                                    file_major, file_minor, version_string)));
1093 }
1094
1095 /*-------------------------------------------------------------------------
1096  *                              Library preload support
1097  *-------------------------------------------------------------------------
1098  */
1099
1100 /* 
1101  * GUC variables: lists of library names to be preloaded at postmaster
1102  * start and at backend start
1103  */
1104 char       *shared_preload_libraries_string = NULL;
1105 char       *local_preload_libraries_string = NULL;
1106
1107 /*
1108  * load the shared libraries listed in 'libraries'
1109  *
1110  * 'gucname': name of GUC variable, for error reports
1111  * 'restricted': if true, force libraries to be in $libdir/plugins/
1112  */
1113 static void
1114 load_libraries(const char *libraries, const char *gucname, bool restricted)
1115 {
1116         char       *rawstring;
1117         List       *elemlist;
1118         ListCell   *l;
1119
1120         if (libraries == NULL || libraries[0] == '\0')
1121                 return;                                 /* nothing to do */
1122
1123         /* Need a modifiable copy of string */
1124         rawstring = pstrdup(libraries);
1125
1126         /* Parse string into list of identifiers */
1127         if (!SplitIdentifierString(rawstring, ',', &elemlist))
1128         {
1129                 /* syntax error in list */
1130                 pfree(rawstring);
1131                 list_free(elemlist);
1132                 ereport(LOG,
1133                                 (errcode(ERRCODE_SYNTAX_ERROR),
1134                                  errmsg("invalid list syntax in parameter \"%s\"",
1135                                                 gucname)));
1136                 return;
1137         }
1138
1139         foreach(l, elemlist)
1140         {
1141                 char       *tok = (char *) lfirst(l);
1142                 char       *filename;
1143
1144                 filename = pstrdup(tok);
1145                 canonicalize_path(filename);
1146                 /* If restricting, insert $libdir/plugins if not mentioned already */
1147                 if (restricted && first_dir_separator(filename) == NULL)
1148                 {
1149                         char   *expanded;
1150
1151                         expanded = palloc(strlen("$libdir/plugins/") + strlen(filename) + 1);
1152                         strcpy(expanded, "$libdir/plugins/");
1153                         strcat(expanded, filename);
1154                         pfree(filename);
1155                         filename = expanded;
1156                 }
1157                 load_file(filename, restricted);
1158                 ereport(LOG,
1159                                 (errmsg("loaded library \"%s\"", filename)));
1160                 pfree(filename);
1161         }
1162
1163         pfree(rawstring);
1164         list_free(elemlist);
1165 }
1166
1167 /*
1168  * process any libraries that should be preloaded at postmaster start
1169  */
1170 void
1171 process_shared_preload_libraries(void)
1172 {
1173         load_libraries(shared_preload_libraries_string,
1174                                    "shared_preload_libraries",
1175                                    false);
1176 }
1177
1178 /*
1179  * process any libraries that should be preloaded at backend start
1180  */
1181 void
1182 process_local_preload_libraries(void)
1183 {
1184         load_libraries(local_preload_libraries_string,
1185                                    "local_preload_libraries",
1186                                    true);
1187 }