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