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