]> granicus.if.org Git - postgresql/blob - src/backend/utils/init/miscinit.c
Re-read Unix-socket lock file every so often (every CheckPoint interval,
[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.61 2001/01/27 00:05:31 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 "miscadmin.h"
32 #include "utils/builtins.h"
33 #include "utils/syscache.h"
34
35
36 #ifdef CYR_RECODE
37 unsigned char RecodeForwTable[128];
38 unsigned char RecodeBackTable[128];
39
40 #endif
41
42 ProcessingMode Mode = InitProcessing;
43
44 /* Note: we rely on this to initialize as zeroes */
45 static char socketLockFile[MAXPGPATH];
46
47
48 /* ----------------------------------------------------------------
49  *              ignoring system indexes support stuff
50  * ----------------------------------------------------------------
51  */
52
53 static bool isIgnoringSystemIndexes = false;
54
55 /*
56  * IsIgnoringSystemIndexes
57  *              True if ignoring system indexes.
58  */
59 bool
60 IsIgnoringSystemIndexes()
61 {
62         return isIgnoringSystemIndexes;
63 }
64
65 /*
66  * IgnoreSystemIndexes
67  *      Set true or false whether PostgreSQL ignores system indexes.
68  *
69  */
70 void
71 IgnoreSystemIndexes(bool mode)
72 {
73         isIgnoringSystemIndexes = mode;
74 }
75
76 /* ----------------------------------------------------------------
77  *                              database path / name support stuff
78  * ----------------------------------------------------------------
79  */
80
81 void
82 SetDatabasePath(const char *path)
83 {
84         free(DatabasePath);
85         /* use strdup since this is done before memory contexts are set up */
86         if (path)
87         {
88                 DatabasePath = strdup(path);
89                 AssertState(DatabasePath);
90         }
91 }
92
93 void
94 SetDatabaseName(const char *name)
95 {
96         free(DatabaseName);
97         if (name)
98         {
99                 DatabaseName = strdup(name);
100                 AssertState(DatabaseName);
101         }
102 }
103
104 /*
105  * Set data directory, but make sure it's an absolute path.  Use this,
106  * never set DataDir directly.
107  */
108 void
109 SetDataDir(const char *dir)
110 {
111         char *new;
112
113         AssertArg(dir);
114         if (DataDir)
115                 free(DataDir);
116
117         if (dir[0] != '/')
118         {
119                 char *buf;
120                 size_t buflen;
121
122                 buflen = MAXPGPATH;
123                 for (;;)
124                 {
125                         buf = malloc(buflen);
126                         if (!buf)
127                                 elog(FATAL, "out of memory");
128
129                         if (getcwd(buf, buflen))
130                                 break;
131                         else if (errno == ERANGE)
132                         {
133                                 free(buf);
134                                 buflen *= 2;
135                                 continue;
136                         }
137                         else
138                         {
139                                 free(buf);
140                                 elog(FATAL, "cannot get current working directory: %m");
141                         }
142                 }
143
144                 new = malloc(strlen(buf) + 1 + strlen(dir) + 1);
145                 sprintf(new, "%s/%s", buf, dir);
146                 free(buf);
147         }
148         else
149         {
150                 new = strdup(dir);
151         }
152
153         if (!new)
154                 elog(FATAL, "out of memory");
155         DataDir = new;          
156 }
157
158
159 /* ----------------------------------------------------------------
160  *                              MULTIBYTE stub code
161  *
162  * Even if MULTIBYTE is not enabled, these functions are necessary
163  * since pg_proc.h has references to them.
164  * ----------------------------------------------------------------
165  */
166
167 #ifndef MULTIBYTE
168
169 Datum
170 getdatabaseencoding(PG_FUNCTION_ARGS)
171 {
172         PG_RETURN_NAME("SQL_ASCII");
173 }
174
175 Datum
176 PG_encoding_to_char(PG_FUNCTION_ARGS)
177 {
178         PG_RETURN_NAME("SQL_ASCII");
179 }
180
181 Datum
182 PG_char_to_encoding(PG_FUNCTION_ARGS)
183 {
184         PG_RETURN_INT32(0);
185 }
186
187 #endif
188
189 /* ----------------------------------------------------------------
190  *                              CYR_RECODE support
191  * ----------------------------------------------------------------
192  */
193
194 #ifdef CYR_RECODE
195
196 #define MAX_TOKEN       80
197
198 /* Some standard C libraries, including GNU, have an isblank() function.
199    Others, including Solaris, do not.  So we have our own.
200 */
201 static bool
202 isblank(const char c)
203 {
204         return c == ' ' || c == 9 /* tab */ ;
205 }
206
207 static void
208 next_token(FILE *fp, char *buf, const int bufsz)
209 {
210 /*--------------------------------------------------------------------------
211   Grab one token out of fp.  Tokens are strings of non-blank
212   characters bounded by blank characters, beginning of line, and end
213   of line.      Blank means space or tab.  Return the token as *buf.
214   Leave file positioned to character immediately after the token or
215   EOF, whichever comes first.  If no more tokens on line, return null
216   string as *buf and position file to beginning of next line or EOF,
217   whichever comes first.
218 --------------------------------------------------------------------------*/
219         int                     c;
220         char       *eb = buf + (bufsz - 1);
221
222         /* Move over inital token-delimiting blanks */
223         while (isblank(c = getc(fp)));
224
225         if (c != '\n')
226         {
227
228                 /*
229                  * build a token in buf of next characters up to EOF, eol, or
230                  * blank.
231                  */
232                 while (c != EOF && c != '\n' && !isblank(c))
233                 {
234                         if (buf < eb)
235                                 *buf++ = c;
236                         c = getc(fp);
237
238                         /*
239                          * Put back the char right after the token (putting back EOF
240                          * is ok)
241                          */
242                 }
243                 ungetc(c, fp);
244         }
245         *buf = '\0';
246 }
247
248 static void
249 read_through_eol(FILE *file)
250 {
251         int                     c;
252
253         do
254                 c = getc(file);
255         while (c != '\n' && c != EOF);
256 }
257
258 void
259 SetCharSet()
260 {
261         FILE       *file;
262         char       *p,
263                                 c,
264                                 eof = false;
265         char       *map_file;
266         char            buf[MAX_TOKEN];
267         int                     i;
268         unsigned char FromChar,
269                                 ToChar;
270
271         for (i = 0; i < 128; i++)
272         {
273                 RecodeForwTable[i] = i + 128;
274                 RecodeBackTable[i] = i + 128;
275         }
276
277         p = getenv("PG_RECODETABLE");
278         if (p && *p != '\0')
279         {
280                 map_file = (char *) malloc((strlen(DataDir) +
281                                                                         strlen(p) + 2) * sizeof(char));
282                 sprintf(map_file, "%s/%s", DataDir, p);
283                 file = AllocateFile(map_file, PG_BINARY_R);
284                 if (file == NULL)
285                         return;
286                 eof = false;
287                 while (!eof)
288                 {
289                         c = getc(file);
290                         ungetc(c, file);
291                         if (c == EOF)
292                                 eof = true;
293                         else
294                         {
295                                 if (c == '#')
296                                         read_through_eol(file);
297                                 else
298                                 {
299                                         /* Read the FromChar */
300                                         next_token(file, buf, sizeof(buf));
301                                         if (buf[0] != '\0')
302                                         {
303                                                 FromChar = strtoul(buf, 0, 0);
304                                                 /* Read the ToChar */
305                                                 next_token(file, buf, sizeof(buf));
306                                                 if (buf[0] != '\0')
307                                                 {
308                                                         ToChar = strtoul(buf, 0, 0);
309                                                         RecodeForwTable[FromChar - 128] = ToChar;
310                                                         RecodeBackTable[ToChar - 128] = FromChar;
311                                                 }
312                                                 read_through_eol(file);
313                                         }
314                                 }
315                         }
316                 }
317                 FreeFile(file);
318                 free(map_file);
319         }
320 }
321
322 char *
323 convertstr(unsigned char *buff, int len, int dest)
324 {
325         int                     i;
326         char       *ch = buff;
327
328         for (i = 0; i < len; i++, buff++)
329         {
330                 if (*buff > 127)
331                 {
332                         if (dest)
333                                 *buff = RecodeForwTable[*buff - 128];
334                         else
335                                 *buff = RecodeBackTable[*buff - 128];
336                 }
337         }
338         return ch;
339 }
340
341 #endif
342
343
344
345 /* ----------------------------------------------------------------
346  *      User ID things
347  *
348  * The session user is determined at connection start and never
349  * changes.  The current user may change when "setuid" functions
350  * are implemented.  Conceptually there is a stack, whose bottom
351  * is the session user.  You are yourself responsible to save and
352  * restore the current user id if you need to change it.
353  * ----------------------------------------------------------------
354  */
355 static Oid      CurrentUserId = InvalidOid;
356 static Oid      SessionUserId = InvalidOid;
357
358
359 /*
360  * This function is relevant for all privilege checks.
361  */
362 Oid
363 GetUserId(void)
364 {
365         AssertState(OidIsValid(CurrentUserId));
366         return CurrentUserId;
367 }
368
369
370 void
371 SetUserId(Oid newid)
372 {
373         AssertArg(OidIsValid(newid));
374         CurrentUserId = newid;
375 }
376
377
378 /*
379  * This value is only relevant for informational purposes.
380  */
381 Oid
382 GetSessionUserId(void)
383 {
384         AssertState(OidIsValid(SessionUserId));
385         return SessionUserId;
386 }
387
388
389 void
390 SetSessionUserId(Oid newid)
391 {
392         AssertArg(OidIsValid(newid));
393         SessionUserId = newid;
394         /* Current user defaults to session user. */
395         if (!OidIsValid(CurrentUserId))
396                 CurrentUserId = newid;
397 }
398
399
400 void
401 SetSessionUserIdFromUserName(const char *username)
402 {
403         HeapTuple       userTup;
404
405         /*
406          * Don't do scans if we're bootstrapping, none of the system catalogs
407          * exist yet, and they should be owned by postgres anyway.
408          */
409         AssertState(!IsBootstrapProcessingMode());
410
411         userTup = SearchSysCache(SHADOWNAME,
412                                                          PointerGetDatum(username),
413                                                          0, 0, 0);
414         if (!HeapTupleIsValid(userTup))
415                 elog(FATAL, "user \"%s\" does not exist", username);
416
417         SetSessionUserId( ((Form_pg_shadow) GETSTRUCT(userTup))->usesysid );
418
419         ReleaseSysCache(userTup);
420 }
421
422
423 /*
424  * Get user name from user id
425  */
426 char *
427 GetUserName(Oid userid)
428 {
429         HeapTuple       tuple;
430         char       *result;
431
432         tuple = SearchSysCache(SHADOWSYSID,
433                                                    ObjectIdGetDatum(userid),
434                                                    0, 0, 0);
435         if (!HeapTupleIsValid(tuple))
436                 elog(ERROR, "invalid user id %u", (unsigned) userid);
437
438         result = pstrdup( NameStr(((Form_pg_shadow) GETSTRUCT(tuple))->usename) );
439
440         ReleaseSysCache(tuple);
441         return result;
442 }
443
444
445
446 /*-------------------------------------------------------------------------
447  *                              Interlock-file support
448  *
449  * These routines are used to create both a data-directory lockfile
450  * ($DATADIR/postmaster.pid) and a Unix-socket-file lockfile ($SOCKFILE.lock).
451  * Both kinds of files contain the same info:
452  *
453  *              Owning process' PID
454  *              Data directory path
455  *
456  * By convention, the owning process' PID is negated if it is a standalone
457  * backend rather than a postmaster.  This is just for informational purposes.
458  * The path is also just for informational purposes (so that a socket lockfile
459  * can be more easily traced to the associated postmaster).
460  *
461  * On successful lockfile creation, a proc_exit callback to remove the
462  * lockfile is automatically created.
463  *-------------------------------------------------------------------------
464  */
465
466 /*
467  * proc_exit callback to remove a lockfile.
468  */
469 static void
470 UnlinkLockFile(int status, Datum filename)
471 {
472         unlink((char *) DatumGetPointer(filename));
473         /* Should we complain if the unlink fails? */
474 }
475
476 /*
477  * Create a lockfile, if possible
478  *
479  * Call CreateLockFile with the name of the lockfile to be created.  If
480  * successful, it returns zero.  On detecting a collision, it returns
481  * the PID or negated PID of the lockfile owner --- the caller is responsible
482  * for producing an appropriate error message.
483  */
484 static int
485 CreateLockFile(const char *filename, bool amPostmaster)
486 {
487         int                     fd;
488         char            buffer[MAXPGPATH + 32];
489         int                     len;
490         int                     encoded_pid;
491         pid_t           other_pid;
492         pid_t           my_pid = getpid();
493
494         /*
495          * We need a loop here because of race conditions.
496          */
497         for (;;)
498         {
499                 /*
500                  * Try to create the lock file --- O_EXCL makes this atomic.
501                  */
502                 fd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
503                 if (fd >= 0)
504                         break;                          /* Success; exit the retry loop */
505                 /*
506                  * Couldn't create the pid file. Probably it already exists.
507                  */
508                 if (errno != EEXIST && errno != EACCES)
509                         elog(FATAL, "Can't create lock file %s: %m", filename);
510
511                 /*
512                  * Read the file to get the old owner's PID.  Note race condition
513                  * here: file might have been deleted since we tried to create it.
514                  */
515                 fd = open(filename, O_RDONLY, 0600);
516                 if (fd < 0)
517                 {
518                         if (errno == ENOENT)
519                                 continue;               /* race condition; try again */
520                         elog(FATAL, "Can't read lock file %s: %m", filename);
521                 }
522                 if ((len = read(fd, buffer, sizeof(buffer) - 1)) <= 0)
523                         elog(FATAL, "Can't read lock file %s: %m", filename);
524                 close(fd);
525
526                 buffer[len] = '\0';
527                 encoded_pid = atoi(buffer);
528
529                 /* if pid < 0, the pid is for postgres, not postmaster */
530                 other_pid = (pid_t) (encoded_pid < 0 ? -encoded_pid : encoded_pid);
531
532                 if (other_pid <= 0)
533                         elog(FATAL, "Bogus data in lock file %s", filename);
534
535                 /*
536                  * Check to see if the other process still exists
537                  */
538                 if (other_pid != my_pid)
539                 {
540                         if (kill(other_pid, 0) == 0 ||
541                                 errno != ESRCH)
542                                 return encoded_pid;     /* lockfile belongs to a live process */
543                 }
544
545                 /*
546                  * No, the process did not exist. Unlink the file and try again to
547                  * create it.  Need a loop because of possible race condition against
548                  * other would-be creators.
549                  */
550                 if (unlink(filename) < 0)
551                         elog(FATAL, "Can't remove old lock file %s: %m"
552                                  "\n\tThe file seems accidentally left, but I couldn't remove it."
553                                  "\n\tPlease remove the file by hand and try again.",
554                                  filename);
555         }
556
557         /*
558          * Successfully created the file, now fill it.
559          */
560         snprintf(buffer, sizeof(buffer), "%d\n%s\n",
561                          amPostmaster ? (int) my_pid : - ((int) my_pid),
562                          DataDir);
563         if (write(fd, buffer, strlen(buffer)) != strlen(buffer))
564         {
565                 int             save_errno = errno;
566
567                 close(fd);
568                 unlink(filename);
569                 errno = save_errno;
570                 elog(FATAL, "Can't write lock file %s: %m", filename);
571         }
572         close(fd);
573
574         /*
575          * Arrange for automatic removal of lockfile at proc_exit.
576          */
577         on_proc_exit(UnlinkLockFile, PointerGetDatum(strdup(filename)));
578
579         return 0;                                       /* Success! */
580 }
581
582 bool
583 CreateDataDirLockFile(const char *datadir, bool amPostmaster)
584 {
585         char    lockfile[MAXPGPATH];
586         int             encoded_pid;
587
588         snprintf(lockfile, sizeof(lockfile), "%s/postmaster.pid", datadir);
589         encoded_pid = CreateLockFile(lockfile, amPostmaster);
590         if (encoded_pid != 0)
591         {
592                 fprintf(stderr, "Lock file \"%s\" already exists.\n", lockfile);
593                 if (encoded_pid < 0)
594                         fprintf(stderr, "Is another postgres (pid %d) running in \"%s\"?\n",
595                                         -encoded_pid, datadir);
596                 else
597                         fprintf(stderr, "Is another postmaster (pid %d) running in \"%s\"?\n",
598                                         encoded_pid, datadir);
599                 return false;
600         }
601         return true;
602 }
603
604 bool
605 CreateSocketLockFile(const char *socketfile, bool amPostmaster)
606 {
607         char    lockfile[MAXPGPATH];
608         int             encoded_pid;
609
610         snprintf(lockfile, sizeof(lockfile), "%s.lock", socketfile);
611         encoded_pid = CreateLockFile(lockfile, amPostmaster);
612         if (encoded_pid != 0)
613         {
614                 fprintf(stderr, "Lock file \"%s\" already exists.\n", lockfile);
615                 if (encoded_pid < 0)
616                         fprintf(stderr, "Is another postgres (pid %d) using \"%s\"?\n",
617                                         -encoded_pid, socketfile);
618                 else
619                         fprintf(stderr, "Is another postmaster (pid %d) using \"%s\"?\n",
620                                         encoded_pid, socketfile);
621                 return false;
622         }
623         /* Save name of lockfile for TouchSocketLockFile */
624         strcpy(socketLockFile, lockfile);
625         return true;
626 }
627
628 /*
629  * Re-read the socket lock file.  This should be called every so often
630  * to ensure that the lock file has a recent access date.  That saves it
631  * from being removed by overenthusiastic /tmp-directory-cleaner daemons.
632  * (Another reason we should never have put the socket file in /tmp...)
633  */
634 void
635 TouchSocketLockFile(void)
636 {
637         int                     fd;
638         char            buffer[1];
639
640         /* Do nothing if we did not create a socket... */
641         if (socketLockFile[0] != '\0')
642         {
643                 /* XXX any need to complain about errors here? */
644                 fd = open(socketLockFile, O_RDONLY | PG_BINARY, 0);
645                 if (fd >= 0)
646                 {
647                         read(fd, buffer, sizeof(buffer));
648                         close(fd);
649                 }
650         }
651 }
652
653
654 /*-------------------------------------------------------------------------
655  *                              Version checking support
656  *-------------------------------------------------------------------------
657  */
658
659 /*
660  * Determine whether the PG_VERSION file in directory `path' indicates
661  * a data version compatible with the version of this program.
662  *
663  * If compatible, return. Otherwise, elog(FATAL).
664  */
665 void
666 ValidatePgVersion(const char *path)
667 {
668         char            full_path[MAXPGPATH];
669         FILE       *file;
670         int                     ret;
671         long        file_major, file_minor;
672         long        my_major = 0, my_minor = 0;
673         char       *endptr;
674         const char *version_string = PG_VERSION;
675
676         my_major = strtol(version_string, &endptr, 10);
677         if (*endptr == '.')
678                 my_minor = strtol(endptr+1, NULL, 10);
679
680         snprintf(full_path, MAXPGPATH, "%s/PG_VERSION", path);
681
682         file = AllocateFile(full_path, "r");
683         if (!file)
684         {
685                 if (errno == ENOENT)
686                         elog(FATAL, "File %s is missing. This is not a valid data directory.", full_path);
687                 else
688                         elog(FATAL, "cannot open %s: %m", full_path);
689         }
690
691         ret = fscanf(file, "%ld.%ld", &file_major, &file_minor);
692         if (ret == EOF)
693                 elog(FATAL, "cannot read %s: %m", full_path);
694         else if (ret != 2)
695                 elog(FATAL, "`%s' does not have a valid format. You need to initdb.", full_path);
696
697         FreeFile(file);
698
699         if (my_major != file_major || my_minor != file_minor)
700                 elog(FATAL, "The data directory was initialized by PostgreSQL version %ld.%ld, "
701                          "which is not compatible with this version %s.",
702                          file_major, file_minor, version_string);
703 }