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