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