]> granicus.if.org Git - postgresql/blob - src/backend/utils/init/miscinit.c
Repair some REINDEX problems per recent discussions. The relcache is
[postgresql] / src / backend / utils / init / miscinit.c
1 /*-------------------------------------------------------------------------
2  *
3  * miscinit.c
4  *        miscellaneous initialization support stuff
5  *
6  * Portions Copyright (c) 1996-2003, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *        $Header: /cvsroot/pgsql/src/backend/utils/init/miscinit.c,v 1.114 2003/09/24 18:54:01 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 <errno.h>
27 #include <netinet/in.h>
28 #include <arpa/inet.h>
29 #ifdef HAVE_UTIME_H
30 #include <utime.h>
31 #endif
32
33 #include "catalog/catname.h"
34 #include "catalog/pg_shadow.h"
35 #include "libpq/libpq-be.h"
36 #include "miscadmin.h"
37 #include "storage/ipc.h"
38 #include "storage/pg_shmem.h"
39 #include "utils/builtins.h"
40 #include "utils/guc.h"
41 #include "utils/lsyscache.h"
42 #include "utils/syscache.h"
43
44
45 ProcessingMode Mode = InitProcessing;
46
47 /* Note: we rely on these to initialize as zeroes */
48 static char directoryLockFile[MAXPGPATH];
49 static char socketLockFile[MAXPGPATH];
50
51
52 /* ----------------------------------------------------------------
53  *              ignoring system indexes support stuff
54  *
55  * NOTE: "ignoring system indexes" means we do not use the system indexes
56  * for lookups (either in hardwired catalog accesses or in planner-generated
57  * plans).  We do, however, still update the indexes when a catalog
58  * modification is made.
59  * ----------------------------------------------------------------
60  */
61
62 static bool isIgnoringSystemIndexes = false;
63
64 /*
65  * IsIgnoringSystemIndexes
66  *              True if ignoring system indexes.
67  */
68 bool
69 IsIgnoringSystemIndexes(void)
70 {
71         return isIgnoringSystemIndexes;
72 }
73
74 /*
75  * IgnoreSystemIndexes
76  *              Set true or false whether PostgreSQL ignores system indexes.
77  */
78 void
79 IgnoreSystemIndexes(bool mode)
80 {
81         isIgnoringSystemIndexes = mode;
82 }
83
84 /* ----------------------------------------------------------------
85  *              system index reindexing support
86  *
87  * When we are busy reindexing a system index, this code provides support
88  * for preventing catalog lookups from using that index.
89  * ----------------------------------------------------------------
90  */
91
92 static Oid      currentlyReindexedHeap = InvalidOid;
93 static Oid      currentlyReindexedIndex = InvalidOid;
94
95 /*
96  * ReindexIsProcessingHeap
97  *              True if heap specified by OID is currently being reindexed.
98  */
99 bool
100 ReindexIsProcessingHeap(Oid heapOid)
101 {
102         return heapOid == currentlyReindexedHeap;
103 }
104
105 /*
106  * ReindexIsProcessingIndex
107  *              True if index specified by OID is currently being reindexed.
108  */
109 bool
110 ReindexIsProcessingIndex(Oid indexOid)
111 {
112         return indexOid == currentlyReindexedIndex;
113 }
114
115 /*
116  * SetReindexProcessing
117  *              Set flag that specified heap/index are being reindexed.
118  *              Pass InvalidOid to indicate that reindexing is not active.
119  */
120 void
121 SetReindexProcessing(Oid heapOid, Oid indexOid)
122 {
123         /* Args should be both, or neither, InvalidOid */
124         Assert((heapOid == InvalidOid) == (indexOid == InvalidOid));
125         /* Reindexing is not re-entrant. */
126         Assert(indexOid == InvalidOid || currentlyReindexedIndex == InvalidOid);
127         currentlyReindexedHeap = heapOid;
128         currentlyReindexedIndex = indexOid;
129 }
130
131 /* ----------------------------------------------------------------
132  *                              database path / name support stuff
133  * ----------------------------------------------------------------
134  */
135
136 void
137 SetDatabasePath(const char *path)
138 {
139         if (DatabasePath)
140         {
141                 free(DatabasePath);
142                 DatabasePath = NULL;
143         }
144         /* use strdup since this is done before memory contexts are set up */
145         if (path)
146         {
147                 DatabasePath = strdup(path);
148                 AssertState(DatabasePath);
149         }
150 }
151
152 /*
153  * Set data directory, but make sure it's an absolute path.  Use this,
154  * never set DataDir directly.
155  */
156 void
157 SetDataDir(const char *dir)
158 {
159         char       *new;
160         int                     newlen;
161
162         AssertArg(dir);
163
164         /* If presented path is relative, convert to absolute */
165         if (!is_absolute_path(dir))
166         {
167                 char       *buf;
168                 size_t          buflen;
169
170                 buflen = MAXPGPATH;
171                 for (;;)
172                 {
173                         buf = malloc(buflen);
174                         if (!buf)
175                                 ereport(FATAL,
176                                                 (errcode(ERRCODE_OUT_OF_MEMORY),
177                                                  errmsg("out of memory")));
178
179                         if (getcwd(buf, buflen))
180                                 break;
181                         else if (errno == ERANGE)
182                         {
183                                 free(buf);
184                                 buflen *= 2;
185                                 continue;
186                         }
187                         else
188                         {
189                                 free(buf);
190                                 elog(FATAL, "could not get current working directory: %m");
191                         }
192                 }
193
194                 new = malloc(strlen(buf) + 1 + strlen(dir) + 1);
195                 if (!new)
196                         ereport(FATAL,
197                                         (errcode(ERRCODE_OUT_OF_MEMORY),
198                                          errmsg("out of memory")));
199                 sprintf(new, "%s/%s", buf, dir);
200                 free(buf);
201         }
202         else
203         {
204                 new = strdup(dir);
205                 if (!new)
206                         ereport(FATAL,
207                                         (errcode(ERRCODE_OUT_OF_MEMORY),
208                                          errmsg("out of memory")));
209         }
210
211         /*
212          * Strip any trailing slash.  Not strictly necessary, but avoids
213          * generating funny-looking paths to individual files.
214          */
215         newlen = strlen(new);
216         if (newlen > 1 && new[newlen - 1] == '/'
217 #ifdef WIN32
218                 || new[newlen - 1] == '\\'
219 #endif
220                 )
221                 new[newlen - 1] = '\0';
222
223         if (DataDir)
224                 free(DataDir);
225         DataDir = new;
226 }
227
228
229 /* ----------------------------------------------------------------
230  *      User ID things
231  *
232  * The authenticated user is determined at connection start and never
233  * changes.  The session user can be changed only by SET SESSION
234  * AUTHORIZATION.  The current user may change when "setuid" functions
235  * are implemented.  Conceptually there is a stack, whose bottom
236  * is the session user.  You are yourself responsible to save and
237  * restore the current user id if you need to change it.
238  * ----------------------------------------------------------------
239  */
240 static AclId AuthenticatedUserId = 0;
241 static AclId SessionUserId = 0;
242 static AclId CurrentUserId = 0;
243
244 static bool AuthenticatedUserIsSuperuser = false;
245
246 /*
247  * This function is relevant for all privilege checks.
248  */
249 AclId
250 GetUserId(void)
251 {
252         AssertState(AclIdIsValid(CurrentUserId));
253         return CurrentUserId;
254 }
255
256
257 void
258 SetUserId(AclId newid)
259 {
260         AssertArg(AclIdIsValid(newid));
261         CurrentUserId = newid;
262 }
263
264
265 /*
266  * This value is only relevant for informational purposes.
267  */
268 AclId
269 GetSessionUserId(void)
270 {
271         AssertState(AclIdIsValid(SessionUserId));
272         return SessionUserId;
273 }
274
275
276 void
277 SetSessionUserId(AclId newid)
278 {
279         AssertArg(AclIdIsValid(newid));
280         SessionUserId = newid;
281         /* Current user defaults to session user. */
282         if (!AclIdIsValid(CurrentUserId))
283                 CurrentUserId = newid;
284 }
285
286
287 void
288 InitializeSessionUserId(const char *username)
289 {
290         HeapTuple       userTup;
291         Datum           datum;
292         bool            isnull;
293         AclId           usesysid;
294
295         /*
296          * Don't do scans if we're bootstrapping, none of the system catalogs
297          * exist yet, and they should be owned by postgres anyway.
298          */
299         AssertState(!IsBootstrapProcessingMode());
300
301         /* call only once */
302         AssertState(!OidIsValid(AuthenticatedUserId));
303
304         userTup = SearchSysCache(SHADOWNAME,
305                                                          PointerGetDatum(username),
306                                                          0, 0, 0);
307         if (!HeapTupleIsValid(userTup))
308                 ereport(FATAL,
309                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
310                                  errmsg("user \"%s\" does not exist", username)));
311
312         usesysid = ((Form_pg_shadow) GETSTRUCT(userTup))->usesysid;
313
314         AuthenticatedUserId = usesysid;
315         AuthenticatedUserIsSuperuser = ((Form_pg_shadow) GETSTRUCT(userTup))->usesuper;
316
317         SetSessionUserId(usesysid); /* sets CurrentUserId too */
318
319         /* Record username and superuser status as GUC settings too */
320         SetConfigOption("session_authorization", username,
321                                         PGC_BACKEND, PGC_S_OVERRIDE);
322         SetConfigOption("is_superuser",
323                                         AuthenticatedUserIsSuperuser ? "on" : "off",
324                                         PGC_INTERNAL, PGC_S_OVERRIDE);
325
326         /*
327          * Set up user-specific configuration variables.  This is a good place
328          * to do it so we don't have to read pg_shadow twice during session
329          * startup.
330          */
331         datum = SysCacheGetAttr(SHADOWNAME, userTup,
332                                                         Anum_pg_shadow_useconfig, &isnull);
333         if (!isnull)
334         {
335                 ArrayType  *a = DatumGetArrayTypeP(datum);
336
337                 ProcessGUCArray(a, PGC_S_USER);
338         }
339
340         ReleaseSysCache(userTup);
341 }
342
343
344 void
345 InitializeSessionUserIdStandalone(void)
346 {
347         /* This function should only be called in a single-user backend. */
348         AssertState(!IsUnderPostmaster);
349
350         /* call only once */
351         AssertState(!OidIsValid(AuthenticatedUserId));
352
353         AuthenticatedUserId = BOOTSTRAP_USESYSID;
354         AuthenticatedUserIsSuperuser = true;
355
356         SetSessionUserId(BOOTSTRAP_USESYSID);
357 }
358
359
360 /*
361  * Change session auth ID while running
362  *
363  * Only a superuser may set auth ID to something other than himself.  Note
364  * that in case of multiple SETs in a single session, the original userid's
365  * superuserness is what matters.  But we set the GUC variable is_superuser
366  * to indicate whether the *current* session userid is a superuser.
367  */
368 void
369 SetSessionAuthorization(AclId userid, bool is_superuser)
370 {
371         /* Must have authenticated already, else can't make permission check */
372         AssertState(AclIdIsValid(AuthenticatedUserId));
373
374         if (userid != AuthenticatedUserId &&
375                 !AuthenticatedUserIsSuperuser)
376                 ereport(ERROR,
377                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
378                           errmsg("permission denied to set session authorization")));
379
380         SetSessionUserId(userid);
381         SetUserId(userid);
382
383         SetConfigOption("is_superuser",
384                                         is_superuser ? "on" : "off",
385                                         PGC_INTERNAL, PGC_S_OVERRIDE);
386 }
387
388
389 /*
390  * Get user name from user id
391  */
392 char *
393 GetUserNameFromId(AclId userid)
394 {
395         HeapTuple       tuple;
396         char       *result;
397
398         tuple = SearchSysCache(SHADOWSYSID,
399                                                    ObjectIdGetDatum(userid),
400                                                    0, 0, 0);
401         if (!HeapTupleIsValid(tuple))
402                 ereport(ERROR,
403                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
404                                  errmsg("invalid user id: %d", userid)));
405
406         result = pstrdup(NameStr(((Form_pg_shadow) GETSTRUCT(tuple))->usename));
407
408         ReleaseSysCache(tuple);
409         return result;
410 }
411
412
413
414 /*-------------------------------------------------------------------------
415  *                              Interlock-file support
416  *
417  * These routines are used to create both a data-directory lockfile
418  * ($DATADIR/postmaster.pid) and a Unix-socket-file lockfile ($SOCKFILE.lock).
419  * Both kinds of files contain the same info:
420  *
421  *              Owning process' PID
422  *              Data directory path
423  *
424  * By convention, the owning process' PID is negated if it is a standalone
425  * backend rather than a postmaster.  This is just for informational purposes.
426  * The path is also just for informational purposes (so that a socket lockfile
427  * can be more easily traced to the associated postmaster).
428  *
429  * A data-directory lockfile can optionally contain a third line, containing
430  * the key and ID for the shared memory block used by this postmaster.
431  *
432  * On successful lockfile creation, a proc_exit callback to remove the
433  * lockfile is automatically created.
434  *-------------------------------------------------------------------------
435  */
436
437 /*
438  * proc_exit callback to remove a lockfile.
439  */
440 static void
441 UnlinkLockFile(int status, Datum filename)
442 {
443         char       *fname = (char *) DatumGetPointer(filename);
444
445         if (fname != NULL)
446         {
447                 if (unlink(fname) != 0)
448                 {
449                         /* Should we complain if the unlink fails? */
450                 }
451                 free(fname);
452         }
453 }
454
455 /*
456  * Create a lockfile.
457  *
458  * filename is the name of the lockfile to create.
459  * amPostmaster is used to determine how to encode the output PID.
460  * isDDLock and refName are used to determine what error message to produce.
461  */
462 static void
463 CreateLockFile(const char *filename, bool amPostmaster,
464                            bool isDDLock, const char *refName)
465 {
466         int                     fd;
467         char            buffer[MAXPGPATH + 100];
468         int                     ntries;
469         int                     len;
470         int                     encoded_pid;
471         pid_t           other_pid;
472         pid_t           my_pid = getpid();
473
474         /*
475          * We need a loop here because of race conditions.      But don't loop
476          * forever (for example, a non-writable $PGDATA directory might cause
477          * a failure that won't go away).  100 tries seems like plenty.
478          */
479         for (ntries = 0;; ntries++)
480         {
481                 /*
482                  * Try to create the lock file --- O_EXCL makes this atomic.
483                  */
484                 fd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
485                 if (fd >= 0)
486                         break;                          /* Success; exit the retry loop */
487
488                 /*
489                  * Couldn't create the pid file. Probably it already exists.
490                  */
491                 if ((errno != EEXIST && errno != EACCES) || ntries > 100)
492                         ereport(FATAL,
493                                         (errcode_for_file_access(),
494                                          errmsg("could not create lock file \"%s\": %m",
495                                                         filename)));
496
497                 /*
498                  * Read the file to get the old owner's PID.  Note race condition
499                  * here: file might have been deleted since we tried to create it.
500                  */
501                 fd = open(filename, O_RDONLY, 0600);
502                 if (fd < 0)
503                 {
504                         if (errno == ENOENT)
505                                 continue;               /* race condition; try again */
506                         ereport(FATAL,
507                                         (errcode_for_file_access(),
508                                          errmsg("could not open lock file \"%s\": %m",
509                                                         filename)));
510                 }
511                 if ((len = read(fd, buffer, sizeof(buffer) - 1)) <= 0)
512                         ereport(FATAL,
513                                         (errcode_for_file_access(),
514                                          errmsg("could not read lock file \"%s\": %m",
515                                                         filename)));
516                 close(fd);
517
518                 buffer[len] = '\0';
519                 encoded_pid = atoi(buffer);
520
521                 /* if pid < 0, the pid is for postgres, not postmaster */
522                 other_pid = (pid_t) (encoded_pid < 0 ? -encoded_pid : encoded_pid);
523
524                 if (other_pid <= 0)
525                         elog(FATAL, "bogus data in lock file \"%s\"", filename);
526
527                 /*
528                  * Check to see if the other process still exists
529                  *
530                  * Normally kill() will fail with ESRCH if the given PID doesn't
531                  * exist.  BeOS returns EINVAL for some silly reason, however.
532                  */
533                 if (other_pid != my_pid)
534                 {
535                         if (kill(other_pid, 0) == 0 ||
536                                 (errno != ESRCH
537 #ifdef __BEOS__
538                                  && errno != EINVAL
539 #endif
540                                  ))
541                         {
542                                 /* lockfile belongs to a live process */
543                                 ereport(FATAL,
544                                                 (errcode(ERRCODE_LOCK_FILE_EXISTS),
545                                                  errmsg("lock file \"%s\" already exists",
546                                                                 filename),
547                                                  isDDLock ?
548                                          errhint("Is another %s (pid %d) running in \"%s\"?",
549                                                    (encoded_pid < 0 ? "postgres" : "postmaster"),
550                                                          (int) other_pid, refName) :
551                                                  errhint("Is another %s (pid %d) using \"%s\"?",
552                                                    (encoded_pid < 0 ? "postgres" : "postmaster"),
553                                                                  (int) other_pid, refName)));
554                         }
555                 }
556
557                 /*
558                  * No, the creating process did not exist.      However, it could be
559                  * that the postmaster crashed (or more likely was kill -9'd by a
560                  * clueless admin) but has left orphan backends behind.  Check for
561                  * this by looking to see if there is an associated shmem segment
562                  * that is still in use.
563                  */
564                 if (isDDLock)
565                 {
566                         char       *ptr;
567                         unsigned long id1,
568                                                 id2;
569
570                         ptr = strchr(buffer, '\n');
571                         if (ptr != NULL &&
572                                 (ptr = strchr(ptr + 1, '\n')) != NULL)
573                         {
574                                 ptr++;
575                                 if (sscanf(ptr, "%lu %lu", &id1, &id2) == 2)
576                                 {
577                                         if (PGSharedMemoryIsInUse(id1, id2))
578                                                 ereport(FATAL,
579                                                                 (errcode(ERRCODE_LOCK_FILE_EXISTS),
580                                                            errmsg("pre-existing shared memory block "
581                                                                           "(key %lu, id %lu) is still in use",
582                                                                           id1, id2),
583                                                            errhint("If you're sure there are no old "
584                                                                            "backends still running, remove "
585                                                                            "the shared memory block with "
586                                                                            "ipcrm(1), or just delete \"%s\".",
587                                                                            filename)));
588                                 }
589                         }
590                 }
591
592                 /*
593                  * Looks like nobody's home.  Unlink the file and try again to
594                  * create it.  Need a loop because of possible race condition
595                  * against other would-be creators.
596                  */
597                 if (unlink(filename) < 0)
598                         ereport(FATAL,
599                                         (errcode_for_file_access(),
600                                          errmsg("could not remove old lock file \"%s\": %m",
601                                                         filename),
602                                          errhint("The file seems accidentally left over, but "
603                                                   "I couldn't remove it. Please remove the file "
604                                                          "by hand and try again.")));
605         }
606
607         /*
608          * Successfully created the file, now fill it.
609          */
610         snprintf(buffer, sizeof(buffer), "%d\n%s\n",
611                          amPostmaster ? (int) my_pid : -((int) my_pid),
612                          DataDir);
613         errno = 0;
614         if (write(fd, buffer, strlen(buffer)) != strlen(buffer))
615         {
616                 int                     save_errno = errno;
617
618                 close(fd);
619                 unlink(filename);
620                 /* if write didn't set errno, assume problem is no disk space */
621                 errno = save_errno ? save_errno : ENOSPC;
622                 ereport(FATAL,
623                                 (errcode_for_file_access(),
624                           errmsg("could not write lock file \"%s\": %m", filename)));
625         }
626         close(fd);
627
628         /*
629          * Arrange for automatic removal of lockfile at proc_exit.
630          */
631         on_proc_exit(UnlinkLockFile, PointerGetDatum(strdup(filename)));
632 }
633
634 void
635 CreateDataDirLockFile(const char *datadir, bool amPostmaster)
636 {
637         char            lockfile[MAXPGPATH];
638
639         snprintf(lockfile, sizeof(lockfile), "%s/postmaster.pid", datadir);
640         CreateLockFile(lockfile, amPostmaster, true, datadir);
641         /* Save name of lockfile for RecordSharedMemoryInLockFile */
642         strcpy(directoryLockFile, lockfile);
643 }
644
645 void
646 CreateSocketLockFile(const char *socketfile, bool amPostmaster)
647 {
648         char            lockfile[MAXPGPATH];
649
650         snprintf(lockfile, sizeof(lockfile), "%s.lock", socketfile);
651         CreateLockFile(lockfile, amPostmaster, false, socketfile);
652         /* Save name of lockfile for TouchSocketLockFile */
653         strcpy(socketLockFile, lockfile);
654 }
655
656 /*
657  * TouchSocketLockFile -- mark socket lock file as recently accessed
658  *
659  * This routine should be called every so often to ensure that the lock file
660  * has a recent mod or access date.  That saves it
661  * from being removed by overenthusiastic /tmp-directory-cleaner daemons.
662  * (Another reason we should never have put the socket file in /tmp...)
663  */
664 void
665 TouchSocketLockFile(void)
666 {
667         /* Do nothing if we did not create a socket... */
668         if (socketLockFile[0] != '\0')
669         {
670                 /*
671                  * utime() is POSIX standard, utimes() is a common alternative; if
672                  * we have neither, fall back to actually reading the file (which
673                  * only sets the access time not mod time, but that should be
674                  * enough in most cases).  In all paths, we ignore errors.
675                  */
676 #ifdef HAVE_UTIME
677                 utime(socketLockFile, NULL);
678 #else                                                   /* !HAVE_UTIME */
679 #ifdef HAVE_UTIMES
680                 utimes(socketLockFile, NULL);
681 #else                                                   /* !HAVE_UTIMES */
682                 int                     fd;
683                 char            buffer[1];
684
685                 fd = open(socketLockFile, O_RDONLY | PG_BINARY, 0);
686                 if (fd >= 0)
687                 {
688                         read(fd, buffer, sizeof(buffer));
689                         close(fd);
690                 }
691 #endif   /* HAVE_UTIMES */
692 #endif   /* HAVE_UTIME */
693         }
694 }
695
696 /*
697  * Append information about a shared memory segment to the data directory
698  * lock file (if we have created one).
699  *
700  * This may be called multiple times in the life of a postmaster, if we
701  * delete and recreate shmem due to backend crash.      Therefore, be prepared
702  * to overwrite existing information.  (As of 7.1, a postmaster only creates
703  * one shm seg at a time; but for the purposes here, if we did have more than
704  * one then any one of them would do anyway.)
705  */
706 void
707 RecordSharedMemoryInLockFile(unsigned long id1, unsigned long id2)
708 {
709         int                     fd;
710         int                     len;
711         char       *ptr;
712         char            buffer[BLCKSZ];
713
714         /*
715          * Do nothing if we did not create a lockfile (probably because we are
716          * running standalone).
717          */
718         if (directoryLockFile[0] == '\0')
719                 return;
720
721         fd = open(directoryLockFile, O_RDWR | PG_BINARY, 0);
722         if (fd < 0)
723         {
724                 ereport(LOG,
725                                 (errcode_for_file_access(),
726                                  errmsg("could not rewrite \"%s\": %m",
727                                                 directoryLockFile)));
728                 return;
729         }
730         len = read(fd, buffer, sizeof(buffer) - 100);
731         if (len <= 0)
732         {
733                 ereport(LOG,
734                                 (errcode_for_file_access(),
735                                  errmsg("could not read \"%s\": %m",
736                                                 directoryLockFile)));
737                 close(fd);
738                 return;
739         }
740         buffer[len] = '\0';
741
742         /*
743          * Skip over first two lines (PID and path).
744          */
745         ptr = strchr(buffer, '\n');
746         if (ptr == NULL ||
747                 (ptr = strchr(ptr + 1, '\n')) == NULL)
748         {
749                 elog(LOG, "bogus data in \"%s\"", directoryLockFile);
750                 close(fd);
751                 return;
752         }
753         ptr++;
754
755         /*
756          * Append key information.      Format to try to keep it the same length
757          * always (trailing junk won't hurt, but might confuse humans).
758          */
759         sprintf(ptr, "%9lu %9lu\n", id1, id2);
760
761         /*
762          * And rewrite the data.  Since we write in a single kernel call, this
763          * update should appear atomic to onlookers.
764          */
765         len = strlen(buffer);
766         errno = 0;
767         if (lseek(fd, (off_t) 0, SEEK_SET) != 0 ||
768                 (int) write(fd, buffer, len) != len)
769         {
770                 /* if write didn't set errno, assume problem is no disk space */
771                 if (errno == 0)
772                         errno = ENOSPC;
773                 ereport(LOG,
774                                 (errcode_for_file_access(),
775                                  errmsg("could not write \"%s\": %m",
776                                                 directoryLockFile)));
777                 close(fd);
778                 return;
779         }
780         close(fd);
781 }
782
783
784 /*-------------------------------------------------------------------------
785  *                              Version checking support
786  *-------------------------------------------------------------------------
787  */
788
789 /*
790  * Determine whether the PG_VERSION file in directory `path' indicates
791  * a data version compatible with the version of this program.
792  *
793  * If compatible, return. Otherwise, ereport(FATAL).
794  */
795 void
796 ValidatePgVersion(const char *path)
797 {
798         char            full_path[MAXPGPATH];
799         FILE       *file;
800         int                     ret;
801         long            file_major,
802                                 file_minor;
803         long            my_major = 0,
804                                 my_minor = 0;
805         char       *endptr;
806         const char *version_string = PG_VERSION;
807
808         my_major = strtol(version_string, &endptr, 10);
809         if (*endptr == '.')
810                 my_minor = strtol(endptr + 1, NULL, 10);
811
812         snprintf(full_path, sizeof(full_path), "%s/PG_VERSION", path);
813
814         file = AllocateFile(full_path, "r");
815         if (!file)
816         {
817                 if (errno == ENOENT)
818                         ereport(FATAL,
819                                         (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
820                                          errmsg("\"%s\" is not a valid data directory",
821                                                         path),
822                                          errdetail("File \"%s\" is missing.", full_path)));
823                 else
824                         ereport(FATAL,
825                                         (errcode_for_file_access(),
826                                          errmsg("could not open \"%s\": %m", full_path)));
827         }
828
829         ret = fscanf(file, "%ld.%ld", &file_major, &file_minor);
830         if (ret != 2)
831                 ereport(FATAL,
832                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
833                                  errmsg("\"%s\" is not a valid data directory",
834                                                 path),
835                                  errdetail("File \"%s\" does not contain valid data.",
836                                                    full_path),
837                                  errhint("You may need to initdb.")));
838
839         FreeFile(file);
840
841         if (my_major != file_major || my_minor != file_minor)
842                 ereport(FATAL,
843                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
844                                  errmsg("database files are incompatible with server"),
845                                  errdetail("The data directory was initialized by PostgreSQL version %ld.%ld, "
846                                                  "which is not compatible with this version %s.",
847                                                    file_major, file_minor, version_string)));
848 }
849
850 /*-------------------------------------------------------------------------
851  *                              Library preload support
852  *-------------------------------------------------------------------------
853  */
854
855 #if defined(__mc68000__) && defined(__ELF__)
856 typedef int32 ((*func_ptr) ());
857
858 #else
859 typedef char *((*func_ptr) ());
860 #endif
861
862 /*
863  * process any libraries that should be preloaded and
864  * optionally pre-initialized
865  */
866 void
867 process_preload_libraries(char *preload_libraries_string)
868 {
869         char       *rawstring;
870         List       *elemlist;
871         List       *l;
872
873         if (preload_libraries_string == NULL)
874                 return;
875
876         /* Need a modifiable copy of string */
877         rawstring = pstrdup(preload_libraries_string);
878
879         /* Parse string into list of identifiers */
880         if (!SplitIdentifierString(rawstring, ',', &elemlist))
881         {
882                 /* syntax error in list */
883                 pfree(rawstring);
884                 freeList(elemlist);
885                 ereport(LOG,
886                                 (errcode(ERRCODE_SYNTAX_ERROR),
887                                  errmsg("invalid list syntax for preload_libraries configuration option")));
888                 return;
889         }
890
891         foreach(l, elemlist)
892         {
893                 char       *tok = (char *) lfirst(l);
894                 char       *sep = strstr(tok, ":");
895                 char       *filename = NULL;
896                 char       *funcname = NULL;
897                 func_ptr        initfunc;
898
899                 if (sep)
900                 {
901                         /*
902                          * a colon separator implies there is an initialization
903                          * function that we need to run in addition to loading the
904                          * library
905                          */
906                         size_t          filename_len = sep - tok;
907                         size_t          funcname_len = strlen(tok) - filename_len - 1;
908
909                         filename = (char *) palloc(filename_len + 1);
910                         memcpy(filename, tok, filename_len);
911                         filename[filename_len] = '\0';
912
913                         funcname = (char *) palloc(funcname_len + 1);
914                         strcpy(funcname, sep + 1);
915                 }
916                 else
917                 {
918                         /*
919                          * no separator -- just load the library
920                          */
921                         filename = pstrdup(tok);
922                         funcname = NULL;
923                 }
924
925                 initfunc = (func_ptr) load_external_function(filename, funcname,
926                                                                                                          true, NULL);
927                 if (initfunc)
928                         (*initfunc) ();
929
930                 if (funcname)
931                         ereport(LOG,
932                                         (errmsg("preloaded library \"%s\" with initialization function \"%s\"",
933                                                         filename, funcname)));
934                 else
935                         ereport(LOG,
936                                         (errmsg("preloaded library \"%s\"",
937                                                         filename)));
938
939                 pfree(filename);
940                 if (funcname)
941                         pfree(funcname);
942         }
943
944         pfree(rawstring);
945         freeList(elemlist);
946 }