]> granicus.if.org Git - postgresql/blob - src/backend/utils/init/miscinit.c
Set optreset on platforms that have it before launching postmaster
[postgresql] / src / backend / utils / init / miscinit.c
1 /*-------------------------------------------------------------------------
2  *
3  * miscinit.c
4  *        miscellaneous initialization support stuff
5  *
6  * Portions Copyright (c) 1996-2001, 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.80 2001/10/19 18:19:41 tgl Exp $
12  *
13  *-------------------------------------------------------------------------
14  */
15 #include "postgres.h"
16
17 #include <sys/param.h>
18 #include <sys/types.h>
19 #include <signal.h>
20 #include <sys/stat.h>
21 #include <sys/file.h>
22 #include <fcntl.h>
23 #include <unistd.h>
24 #include <grp.h>
25 #include <pwd.h>
26 #include <stdlib.h>
27 #include <errno.h>
28
29 #include "catalog/catname.h"
30 #include "catalog/pg_shadow.h"
31 #include "libpq/libpq-be.h"
32 #include "miscadmin.h"
33 #include "utils/builtins.h"
34 #include "utils/lsyscache.h"
35 #include "utils/syscache.h"
36
37
38 #ifdef CYR_RECODE
39 unsigned char RecodeForwTable[128];
40 unsigned char RecodeBackTable[128];
41 #endif
42
43 ProcessingMode Mode = InitProcessing;
44
45 /* Note: we rely on these to initialize as zeroes */
46 static char directoryLockFile[MAXPGPATH];
47 static char socketLockFile[MAXPGPATH];
48
49
50 /* ----------------------------------------------------------------
51  *              ignoring system indexes support stuff
52  * ----------------------------------------------------------------
53  */
54
55 static bool isIgnoringSystemIndexes = false;
56
57 /*
58  * IsIgnoringSystemIndexes
59  *              True if ignoring system indexes.
60  */
61 bool
62 IsIgnoringSystemIndexes()
63 {
64         return isIgnoringSystemIndexes;
65 }
66
67 /*
68  * IgnoreSystemIndexes
69  *      Set true or false whether PostgreSQL ignores system indexes.
70  *
71  */
72 void
73 IgnoreSystemIndexes(bool mode)
74 {
75         isIgnoringSystemIndexes = mode;
76 }
77
78 /* ----------------------------------------------------------------
79  *                              database path / name support stuff
80  * ----------------------------------------------------------------
81  */
82
83 void
84 SetDatabasePath(const char *path)
85 {
86         if (DatabasePath)
87         {
88                 free(DatabasePath);
89                 DatabasePath = NULL;
90         }
91         /* use strdup since this is done before memory contexts are set up */
92         if (path)
93         {
94                 DatabasePath = strdup(path);
95                 AssertState(DatabasePath);
96         }
97 }
98
99 void
100 SetDatabaseName(const char *name)
101 {
102         if (DatabaseName)
103         {
104                 free(DatabaseName);
105                 DatabaseName = NULL;
106         }
107         /* use strdup since this is done before memory contexts are set up */
108         if (name)
109         {
110                 DatabaseName = strdup(name);
111                 AssertState(DatabaseName);
112         }
113 }
114
115 /*
116  * Set data directory, but make sure it's an absolute path.  Use this,
117  * never set DataDir directly.
118  */
119 void
120 SetDataDir(const char *dir)
121 {
122         char       *new;
123
124         AssertArg(dir);
125
126         if (dir[0] != '/')
127         {
128                 char       *buf;
129                 size_t          buflen;
130
131                 buflen = MAXPGPATH;
132                 for (;;)
133                 {
134                         buf = malloc(buflen);
135                         if (!buf)
136                                 elog(FATAL, "out of memory");
137
138                         if (getcwd(buf, buflen))
139                                 break;
140                         else if (errno == ERANGE)
141                         {
142                                 free(buf);
143                                 buflen *= 2;
144                                 continue;
145                         }
146                         else
147                         {
148                                 free(buf);
149                                 elog(FATAL, "cannot get current working directory: %m");
150                         }
151                 }
152
153                 new = malloc(strlen(buf) + 1 + strlen(dir) + 1);
154                 if (!new)
155                         elog(FATAL, "out of memory");
156                 sprintf(new, "%s/%s", buf, dir);
157                 free(buf);
158         }
159         else
160         {
161                 new = strdup(dir);
162                 if (!new)
163                         elog(FATAL, "out of memory");
164         }
165
166         if (DataDir)
167                 free(DataDir);
168         DataDir = new;
169 }
170
171
172 /* ----------------------------------------------------------------
173  *                              MULTIBYTE stub code
174  *
175  * Even if MULTIBYTE is not enabled, these functions are necessary
176  * since pg_proc.h has references to them.
177  * ----------------------------------------------------------------
178  */
179
180 #ifndef MULTIBYTE
181
182 Datum
183 getdatabaseencoding(PG_FUNCTION_ARGS)
184 {
185         return DirectFunctionCall1(namein, CStringGetDatum("SQL_ASCII"));
186 }
187
188 Datum
189 pg_client_encoding(PG_FUNCTION_ARGS)
190 {
191         return DirectFunctionCall1(namein, CStringGetDatum("SQL_ASCII"));
192 }
193
194 Datum
195 PG_encoding_to_char(PG_FUNCTION_ARGS)
196 {
197         return DirectFunctionCall1(namein, CStringGetDatum("SQL_ASCII"));
198 }
199
200 Datum
201 PG_char_to_encoding(PG_FUNCTION_ARGS)
202 {
203         PG_RETURN_INT32(0);
204 }
205
206 Datum
207 pg_convert(PG_FUNCTION_ARGS)
208 {
209         elog(ERROR, "convert is not supported. To use convert, you need to enable multibyte capability");
210         return DirectFunctionCall1(textin, CStringGetDatum(""));
211 }
212
213 Datum
214 pg_convert2(PG_FUNCTION_ARGS)
215 {
216         elog(ERROR, "convert is not supported. To use convert, you need to enable multibyte capability");
217         return DirectFunctionCall1(textin, CStringGetDatum(""));
218 }
219 #endif
220
221 /* ----------------------------------------------------------------
222  *                              CYR_RECODE support
223  * ----------------------------------------------------------------
224  */
225
226 #ifdef CYR_RECODE
227
228 #define MAX_TOKEN       80
229
230 /* Some standard C libraries, including GNU, have an isblank() function.
231    Others, including Solaris, do not.  So we have our own.
232 */
233 static bool
234 isblank(const char c)
235 {
236         return c == ' ' || c == 9 /* tab */ ;
237 }
238
239 static void
240 next_token(FILE *fp, char *buf, const int bufsz)
241 {
242 /*--------------------------------------------------------------------------
243   Grab one token out of fp.  Tokens are strings of non-blank
244   characters bounded by blank characters, beginning of line, and end
245   of line.      Blank means space or tab.  Return the token as *buf.
246   Leave file positioned to character immediately after the token or
247   EOF, whichever comes first.  If no more tokens on line, return null
248   string as *buf and position file to beginning of next line or EOF,
249   whichever comes first.
250 --------------------------------------------------------------------------*/
251         int                     c;
252         char       *eb = buf + (bufsz - 1);
253
254         /* Move over inital token-delimiting blanks */
255         while (isblank(c = getc(fp)));
256
257         if (c != '\n')
258         {
259
260                 /*
261                  * build a token in buf of next characters up to EOF, eol, or
262                  * blank.
263                  */
264                 while (c != EOF && c != '\n' && !isblank(c))
265                 {
266                         if (buf < eb)
267                                 *buf++ = c;
268                         c = getc(fp);
269
270                         /*
271                          * Put back the char right after the token (putting back EOF
272                          * is ok)
273                          */
274                 }
275                 ungetc(c, fp);
276         }
277         *buf = '\0';
278 }
279
280 static void
281 read_through_eol(FILE *file)
282 {
283         int                     c;
284
285         do
286                 c = getc(file);
287         while (c != '\n' && c != EOF);
288 }
289
290 void
291 SetCharSet()
292 {
293         FILE       *file;
294         char       *p,
295                                 c,
296                                 eof = false;
297         char       *map_file;
298         char            buf[MAX_TOKEN];
299         int                     i;
300         unsigned char FromChar,
301                                 ToChar;
302         char            ChTable[80];
303
304         for (i = 0; i < 128; i++)
305         {
306                 RecodeForwTable[i] = i + 128;
307                 RecodeBackTable[i] = i + 128;
308         }
309
310         if (IsUnderPostmaster)
311         {
312                 GetCharSetByHost(ChTable, MyProcPort->raddr.in.sin_addr.s_addr, DataDir);
313                 p = ChTable;
314         }
315         else
316                 p = getenv("PG_RECODETABLE");
317
318         if (p && *p != '\0')
319         {
320                 map_file = malloc(strlen(DataDir) +     strlen(p) + 2);
321                 if (! map_file)
322                         elog(FATAL, "out of memory");
323                 sprintf(map_file, "%s/%s", DataDir, p);
324                 file = AllocateFile(map_file, PG_BINARY_R);
325                 if (file == NULL)
326                 {
327                         free(map_file);
328                         return;
329                 }
330                 eof = false;
331                 while (!eof)
332                 {
333                         c = getc(file);
334                         ungetc(c, file);
335                         if (c == EOF)
336                                 eof = true;
337                         else
338                         {
339                                 if (c == '#')
340                                         read_through_eol(file);
341                                 else
342                                 {
343                                         /* Read the FromChar */
344                                         next_token(file, buf, sizeof(buf));
345                                         if (buf[0] != '\0')
346                                         {
347                                                 FromChar = strtoul(buf, 0, 0);
348                                                 /* Read the ToChar */
349                                                 next_token(file, buf, sizeof(buf));
350                                                 if (buf[0] != '\0')
351                                                 {
352                                                         ToChar = strtoul(buf, 0, 0);
353                                                         RecodeForwTable[FromChar - 128] = ToChar;
354                                                         RecodeBackTable[ToChar - 128] = FromChar;
355                                                 }
356                                                 read_through_eol(file);
357                                         }
358                                 }
359                         }
360                 }
361                 FreeFile(file);
362                 free(map_file);
363         }
364 }
365
366 char *
367 convertstr(unsigned char *buff, int len, int dest)
368 {
369         int                     i;
370         char       *ch = buff;
371
372         for (i = 0; i < len; i++, buff++)
373         {
374                 if (*buff > 127)
375                 {
376                         if (dest)
377                                 *buff = RecodeForwTable[*buff - 128];
378                         else
379                                 *buff = RecodeBackTable[*buff - 128];
380                 }
381         }
382         return ch;
383 }
384
385 #endif
386
387
388
389 /* ----------------------------------------------------------------
390  *      User ID things
391  *
392  * The session user is determined at connection start and never
393  * changes.  The current user may change when "setuid" functions
394  * are implemented.  Conceptually there is a stack, whose bottom
395  * is the session user.  You are yourself responsible to save and
396  * restore the current user id if you need to change it.
397  * ----------------------------------------------------------------
398  */
399 static Oid      CurrentUserId = InvalidOid;
400 static Oid      SessionUserId = InvalidOid;
401
402 static bool AuthenticatedUserIsSuperuser = false;
403
404 /*
405  * This function is relevant for all privilege checks.
406  */
407 Oid
408 GetUserId(void)
409 {
410         AssertState(OidIsValid(CurrentUserId));
411         return CurrentUserId;
412 }
413
414
415 void
416 SetUserId(Oid newid)
417 {
418         AssertArg(OidIsValid(newid));
419         CurrentUserId = newid;
420 }
421
422
423 /*
424  * This value is only relevant for informational purposes.
425  */
426 Oid
427 GetSessionUserId(void)
428 {
429         AssertState(OidIsValid(SessionUserId));
430         return SessionUserId;
431 }
432
433
434 void
435 SetSessionUserId(Oid newid)
436 {
437         AssertArg(OidIsValid(newid));
438         SessionUserId = newid;
439         /* Current user defaults to session user. */
440         if (!OidIsValid(CurrentUserId))
441                 CurrentUserId = newid;
442 }
443
444
445 void
446 InitializeSessionUserId(const char *username)
447 {
448         HeapTuple       userTup;
449
450         /*
451          * Don't do scans if we're bootstrapping, none of the system catalogs
452          * exist yet, and they should be owned by postgres anyway.
453          */
454         AssertState(!IsBootstrapProcessingMode());
455
456         /* call only once */
457         AssertState(!OidIsValid(SessionUserId));
458
459         userTup = SearchSysCache(SHADOWNAME,
460                                                          PointerGetDatum(username),
461                                                          0, 0, 0);
462         if (!HeapTupleIsValid(userTup))
463                 elog(FATAL, "user \"%s\" does not exist", username);
464
465         SetSessionUserId(((Form_pg_shadow) GETSTRUCT(userTup))->usesysid);
466
467         AuthenticatedUserIsSuperuser = ((Form_pg_shadow) GETSTRUCT(userTup))->usesuper;
468
469         ReleaseSysCache(userTup);
470 }
471
472
473 void
474 InitializeSessionUserIdStandalone(void)
475 {
476         /* This function should only be called in a single-user backend. */
477         AssertState(!IsUnderPostmaster);
478
479         /* call only once */
480         AssertState(!OidIsValid(SessionUserId));
481
482         SetSessionUserId(BOOTSTRAP_USESYSID);
483         AuthenticatedUserIsSuperuser = true;
484 }
485
486
487 /*
488  * Change session auth ID while running
489  */
490 void SetSessionAuthorization(const char * username)
491 {
492         int32           userid;
493
494         if (!AuthenticatedUserIsSuperuser)
495                 elog(ERROR, "permission denied");
496
497         userid = get_usesysid(username);
498
499         SetSessionUserId(userid);
500         SetUserId(userid);
501 }
502
503
504 /*
505  * Get user name from user id
506  */
507 char *
508 GetUserName(Oid userid)
509 {
510         HeapTuple       tuple;
511         char       *result;
512
513         tuple = SearchSysCache(SHADOWSYSID,
514                                                    ObjectIdGetDatum(userid),
515                                                    0, 0, 0);
516         if (!HeapTupleIsValid(tuple))
517                 elog(ERROR, "invalid user id %u", (unsigned) userid);
518
519         result = pstrdup(NameStr(((Form_pg_shadow) GETSTRUCT(tuple))->usename));
520
521         ReleaseSysCache(tuple);
522         return result;
523 }
524
525
526
527 /*-------------------------------------------------------------------------
528  *                              Interlock-file support
529  *
530  * These routines are used to create both a data-directory lockfile
531  * ($DATADIR/postmaster.pid) and a Unix-socket-file lockfile ($SOCKFILE.lock).
532  * Both kinds of files contain the same info:
533  *
534  *              Owning process' PID
535  *              Data directory path
536  *
537  * By convention, the owning process' PID is negated if it is a standalone
538  * backend rather than a postmaster.  This is just for informational purposes.
539  * The path is also just for informational purposes (so that a socket lockfile
540  * can be more easily traced to the associated postmaster).
541  *
542  * A data-directory lockfile can optionally contain a third line, containing
543  * the key and ID for the shared memory block used by this postmaster.
544  *
545  * On successful lockfile creation, a proc_exit callback to remove the
546  * lockfile is automatically created.
547  *-------------------------------------------------------------------------
548  */
549
550 /*
551  * proc_exit callback to remove a lockfile.
552  */
553 static void
554 UnlinkLockFile(int status, Datum filename)
555 {
556         unlink((char *) DatumGetPointer(filename));
557         /* Should we complain if the unlink fails? */
558 }
559
560 /*
561  * Create a lockfile, if possible
562  *
563  * Call CreateLockFile with the name of the lockfile to be created.
564  * Returns true if successful, false if not (with a message on stderr).
565  *
566  * amPostmaster is used to determine how to encode the output PID.
567  * isDDLock and refName are used to determine what error message to produce.
568  */
569 static bool
570 CreateLockFile(const char *filename, bool amPostmaster,
571                            bool isDDLock, const char *refName)
572 {
573         int                     fd;
574         char            buffer[MAXPGPATH + 100];
575         int                     ntries;
576         int                     len;
577         int                     encoded_pid;
578         pid_t           other_pid;
579         pid_t           my_pid = getpid();
580
581         /*
582          * We need a loop here because of race conditions.  But don't loop
583          * forever (for example, a non-writable $PGDATA directory might cause
584          * a failure that won't go away).  100 tries seems like plenty.
585          */
586         for (ntries = 0; ; ntries++)
587         {
588
589                 /*
590                  * Try to create the lock file --- O_EXCL makes this atomic.
591                  */
592                 fd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
593                 if (fd >= 0)
594                         break;                          /* Success; exit the retry loop */
595
596                 /*
597                  * Couldn't create the pid file. Probably it already exists.
598                  */
599                 if ((errno != EEXIST && errno != EACCES) || ntries > 100)
600                         elog(FATAL, "Can't create lock file %s: %m", filename);
601
602                 /*
603                  * Read the file to get the old owner's PID.  Note race condition
604                  * here: file might have been deleted since we tried to create it.
605                  */
606                 fd = open(filename, O_RDONLY, 0600);
607                 if (fd < 0)
608                 {
609                         if (errno == ENOENT)
610                                 continue;               /* race condition; try again */
611                         elog(FATAL, "Can't read lock file %s: %m", filename);
612                 }
613                 if ((len = read(fd, buffer, sizeof(buffer) - 1)) <= 0)
614                         elog(FATAL, "Can't read lock file %s: %m", filename);
615                 close(fd);
616
617                 buffer[len] = '\0';
618                 encoded_pid = atoi(buffer);
619
620                 /* if pid < 0, the pid is for postgres, not postmaster */
621                 other_pid = (pid_t) (encoded_pid < 0 ? -encoded_pid : encoded_pid);
622
623                 if (other_pid <= 0)
624                         elog(FATAL, "Bogus data in lock file %s", filename);
625
626                 /*
627                  * Check to see if the other process still exists
628                  *
629                  * Normally kill() will fail with ESRCH if the given PID doesn't
630                  * exist.  BeOS returns EINVAL for some silly reason, however.
631                  */
632                 if (other_pid != my_pid)
633                 {
634                         if (kill(other_pid, 0) == 0 ||
635                                 (errno != ESRCH
636 #ifdef __BEOS__
637                                  && errno != EINVAL
638 #endif
639                                  ))
640                         {
641                                 /* lockfile belongs to a live process */
642                                 fprintf(stderr, "Lock file \"%s\" already exists.\n",
643                                                 filename);
644                                 if (isDDLock)
645                                         fprintf(stderr,
646                                                         "Is another %s (pid %d) running in \"%s\"?\n",
647                                                         (encoded_pid < 0 ? "postgres" : "postmaster"),
648                                                         (int) other_pid, refName);
649                                 else
650                                         fprintf(stderr,
651                                                         "Is another %s (pid %d) using \"%s\"?\n",
652                                                         (encoded_pid < 0 ? "postgres" : "postmaster"),
653                                                         (int) other_pid, refName);
654                                 return false;
655                         }
656                 }
657
658                 /*
659                  * No, the creating process did not exist.      However, it could be
660                  * that the postmaster crashed (or more likely was kill -9'd by a
661                  * clueless admin) but has left orphan backends behind.  Check for
662                  * this by looking to see if there is an associated shmem segment
663                  * that is still in use.
664                  */
665                 if (isDDLock)
666                 {
667                         char       *ptr;
668                         unsigned long shmKey,
669                                                 shmId;
670
671                         ptr = strchr(buffer, '\n');
672                         if (ptr != NULL &&
673                                 (ptr = strchr(ptr + 1, '\n')) != NULL)
674                         {
675                                 ptr++;
676                                 if (sscanf(ptr, "%lu %lu", &shmKey, &shmId) == 2)
677                                 {
678                                         if (SharedMemoryIsInUse((IpcMemoryKey) shmKey,
679                                                                                         (IpcMemoryId) shmId))
680                                         {
681                                                 fprintf(stderr,
682                                                                 "Found a pre-existing shared memory block (ID %d) still in use.\n"
683                                                                 "If you're sure there are no old backends still running,\n"
684                                                                 "remove the shared memory block with ipcrm(1), or just\n"
685                                                                 "delete \"%s\".\n",
686                                                                 (int) shmId, filename);
687                                                 return false;
688                                         }
689                                 }
690                         }
691                 }
692
693                 /*
694                  * Looks like nobody's home.  Unlink the file and try again to
695                  * create it.  Need a loop because of possible race condition
696                  * against other would-be creators.
697                  */
698                 if (unlink(filename) < 0)
699                         elog(FATAL, "Can't remove old lock file %s: %m"
700                                  "\n\tThe file seems accidentally left, but I couldn't remove it."
701                                  "\n\tPlease remove the file by hand and try again.",
702                                  filename);
703         }
704
705         /*
706          * Successfully created the file, now fill it.
707          */
708         snprintf(buffer, sizeof(buffer), "%d\n%s\n",
709                          amPostmaster ? (int) my_pid : -((int) my_pid),
710                          DataDir);
711         errno = 0;
712         if (write(fd, buffer, strlen(buffer)) != strlen(buffer))
713         {
714                 int                     save_errno = errno;
715
716                 close(fd);
717                 unlink(filename);
718                 /* if write didn't set errno, assume problem is no disk space */
719                 errno = save_errno ? save_errno : ENOSPC;
720                 elog(FATAL, "Can't write lock file %s: %m", filename);
721         }
722         close(fd);
723
724         /*
725          * Arrange for automatic removal of lockfile at proc_exit.
726          */
727         on_proc_exit(UnlinkLockFile, PointerGetDatum(strdup(filename)));
728
729         return true;                            /* Success! */
730 }
731
732 bool
733 CreateDataDirLockFile(const char *datadir, bool amPostmaster)
734 {
735         char            lockfile[MAXPGPATH];
736
737         snprintf(lockfile, sizeof(lockfile), "%s/postmaster.pid", datadir);
738         if (!CreateLockFile(lockfile, amPostmaster, true, datadir))
739                 return false;
740         /* Save name of lockfile for RecordSharedMemoryInLockFile */
741         strcpy(directoryLockFile, lockfile);
742         return true;
743 }
744
745 bool
746 CreateSocketLockFile(const char *socketfile, bool amPostmaster)
747 {
748         char            lockfile[MAXPGPATH];
749
750         snprintf(lockfile, sizeof(lockfile), "%s.lock", socketfile);
751         if (!CreateLockFile(lockfile, amPostmaster, false, socketfile))
752                 return false;
753         /* Save name of lockfile for TouchSocketLockFile */
754         strcpy(socketLockFile, lockfile);
755         return true;
756 }
757
758 /*
759  * Re-read the socket lock file.  This should be called every so often
760  * to ensure that the lock file has a recent access date.  That saves it
761  * from being removed by overenthusiastic /tmp-directory-cleaner daemons.
762  * (Another reason we should never have put the socket file in /tmp...)
763  */
764 void
765 TouchSocketLockFile(void)
766 {
767         int                     fd;
768         char            buffer[1];
769
770         /* Do nothing if we did not create a socket... */
771         if (socketLockFile[0] != '\0')
772         {
773                 /* XXX any need to complain about errors here? */
774                 fd = open(socketLockFile, O_RDONLY | PG_BINARY, 0);
775                 if (fd >= 0)
776                 {
777                         read(fd, buffer, sizeof(buffer));
778                         close(fd);
779                 }
780         }
781 }
782
783 /*
784  * Append information about a shared memory segment to the data directory
785  * lock file (if we have created one).
786  *
787  * This may be called multiple times in the life of a postmaster, if we
788  * delete and recreate shmem due to backend crash.      Therefore, be prepared
789  * to overwrite existing information.  (As of 7.1, a postmaster only creates
790  * one shm seg anyway; but for the purposes here, if we did have more than
791  * one then any one of them would do anyway.)
792  */
793 void
794 RecordSharedMemoryInLockFile(IpcMemoryKey shmKey, IpcMemoryId shmId)
795 {
796         int                     fd;
797         int                     len;
798         char       *ptr;
799         char            buffer[BLCKSZ];
800
801         /*
802          * Do nothing if we did not create a lockfile (probably because we are
803          * running standalone).
804          */
805         if (directoryLockFile[0] == '\0')
806                 return;
807
808         fd = open(directoryLockFile, O_RDWR | PG_BINARY, 0);
809         if (fd < 0)
810         {
811                 elog(DEBUG, "Failed to rewrite %s: %m", directoryLockFile);
812                 return;
813         }
814         len = read(fd, buffer, sizeof(buffer) - 100);
815         if (len <= 0)
816         {
817                 elog(DEBUG, "Failed to read %s: %m", directoryLockFile);
818                 close(fd);
819                 return;
820         }
821         buffer[len] = '\0';
822
823         /*
824          * Skip over first two lines (PID and path).
825          */
826         ptr = strchr(buffer, '\n');
827         if (ptr == NULL ||
828                 (ptr = strchr(ptr + 1, '\n')) == NULL)
829         {
830                 elog(DEBUG, "Bogus data in %s", directoryLockFile);
831                 close(fd);
832                 return;
833         }
834         ptr++;
835
836         /*
837          * Append shm key and ID.  Format to try to keep it the same length
838          * always (trailing junk won't hurt, but might confuse humans).
839          */
840         sprintf(ptr, "%9lu %9lu\n",
841                         (unsigned long) shmKey, (unsigned long) shmId);
842
843         /*
844          * And rewrite the data.  Since we write in a single kernel call, this
845          * update should appear atomic to onlookers.
846          */
847         len = strlen(buffer);
848         errno = 0;
849         if (lseek(fd, (off_t) 0, SEEK_SET) != 0 ||
850                 (int) write(fd, buffer, len) != len)
851         {
852                 /* if write didn't set errno, assume problem is no disk space */
853                 if (errno == 0)
854                         errno = ENOSPC;
855                 elog(DEBUG, "Failed to write %s: %m", directoryLockFile);
856                 close(fd);
857                 return;
858         }
859         close(fd);
860 }
861
862
863 /*-------------------------------------------------------------------------
864  *                              Version checking support
865  *-------------------------------------------------------------------------
866  */
867
868 /*
869  * Determine whether the PG_VERSION file in directory `path' indicates
870  * a data version compatible with the version of this program.
871  *
872  * If compatible, return. Otherwise, elog(FATAL).
873  */
874 void
875 ValidatePgVersion(const char *path)
876 {
877         char            full_path[MAXPGPATH];
878         FILE       *file;
879         int                     ret;
880         long            file_major,
881                                 file_minor;
882         long            my_major = 0,
883                                 my_minor = 0;
884         char       *endptr;
885         const char *version_string = PG_VERSION;
886
887         my_major = strtol(version_string, &endptr, 10);
888         if (*endptr == '.')
889                 my_minor = strtol(endptr + 1, NULL, 10);
890
891         snprintf(full_path, MAXPGPATH, "%s/PG_VERSION", path);
892
893         file = AllocateFile(full_path, "r");
894         if (!file)
895         {
896                 if (errno == ENOENT)
897                         elog(FATAL, "File %s is missing. This is not a valid data directory.", full_path);
898                 else
899                         elog(FATAL, "cannot open %s: %m", full_path);
900         }
901
902         ret = fscanf(file, "%ld.%ld", &file_major, &file_minor);
903         if (ret != 2)
904                 elog(FATAL, "File %s does not contain valid data. You need to initdb.", full_path);
905
906         FreeFile(file);
907
908         if (my_major != file_major || my_minor != file_minor)
909                 elog(FATAL, "The data directory was initialized by PostgreSQL version %ld.%ld, "
910                          "which is not compatible with this version %s.",
911                          file_major, file_minor, version_string);
912 }