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