]> granicus.if.org Git - postgresql/blob - src/backend/utils/init/miscinit.c
Tell gettext which codeset to use by calling bind_textdomain_codeset(). We
[postgresql] / src / backend / utils / init / miscinit.c
1 /*-------------------------------------------------------------------------
2  *
3  * miscinit.c
4  *        miscellaneous initialization support stuff
5  *
6  * Portions Copyright (c) 1996-2009, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *        $PostgreSQL: pgsql/src/backend/utils/init/miscinit.c,v 1.174 2009/04/08 09:50:48 heikki Exp $
12  *
13  *-------------------------------------------------------------------------
14  */
15 #include "postgres.h"
16
17 #include <sys/param.h>
18 #include <signal.h>
19 #include <sys/file.h>
20 #include <sys/stat.h>
21 #include <sys/time.h>
22 #include <fcntl.h>
23 #include <unistd.h>
24 #include <grp.h>
25 #include <pwd.h>
26 #include <netinet/in.h>
27 #include <arpa/inet.h>
28 #ifdef HAVE_UTIME_H
29 #include <utime.h>
30 #endif
31
32 #include "catalog/pg_authid.h"
33 #include "mb/pg_wchar.h"
34 #include "miscadmin.h"
35 #include "postmaster/autovacuum.h"
36 #include "storage/fd.h"
37 #include "storage/ipc.h"
38 #include "storage/pg_shmem.h"
39 #include "storage/proc.h"
40 #include "storage/procarray.h"
41 #include "utils/builtins.h"
42 #include "utils/guc.h"
43 #include "utils/syscache.h"
44
45
46 #define DIRECTORY_LOCK_FILE             "postmaster.pid"
47
48 ProcessingMode Mode = InitProcessing;
49
50 /* Note: we rely on this to initialize as zeroes */
51 static char socketLockFile[MAXPGPATH];
52
53
54 /* ----------------------------------------------------------------
55  *              ignoring system indexes support stuff
56  *
57  * NOTE: "ignoring system indexes" means we do not use the system indexes
58  * for lookups (either in hardwired catalog accesses or in planner-generated
59  * plans).      We do, however, still update the indexes when a catalog
60  * modification is made.
61  * ----------------------------------------------------------------
62  */
63
64 bool            IgnoreSystemIndexes = false;
65
66 /* ----------------------------------------------------------------
67  *              system index reindexing support
68  *
69  * When we are busy reindexing a system index, this code provides support
70  * for preventing catalog lookups from using that index.
71  * ----------------------------------------------------------------
72  */
73
74 static Oid      currentlyReindexedHeap = InvalidOid;
75 static Oid      currentlyReindexedIndex = InvalidOid;
76
77 /*
78  * ReindexIsProcessingHeap
79  *              True if heap specified by OID is currently being reindexed.
80  */
81 bool
82 ReindexIsProcessingHeap(Oid heapOid)
83 {
84         return heapOid == currentlyReindexedHeap;
85 }
86
87 /*
88  * ReindexIsProcessingIndex
89  *              True if index specified by OID is currently being reindexed.
90  */
91 bool
92 ReindexIsProcessingIndex(Oid indexOid)
93 {
94         return indexOid == currentlyReindexedIndex;
95 }
96
97 /*
98  * SetReindexProcessing
99  *              Set flag that specified heap/index are being reindexed.
100  */
101 void
102 SetReindexProcessing(Oid heapOid, Oid indexOid)
103 {
104         Assert(OidIsValid(heapOid) && OidIsValid(indexOid));
105         /* Reindexing is not re-entrant. */
106         if (OidIsValid(currentlyReindexedIndex))
107                 elog(ERROR, "cannot reindex while reindexing");
108         currentlyReindexedHeap = heapOid;
109         currentlyReindexedIndex = indexOid;
110 }
111
112 /*
113  * ResetReindexProcessing
114  *              Unset reindexing status.
115  */
116 void
117 ResetReindexProcessing(void)
118 {
119         currentlyReindexedHeap = InvalidOid;
120         currentlyReindexedIndex = InvalidOid;
121 }
122
123 /* ----------------------------------------------------------------
124  *                              database path / name support stuff
125  * ----------------------------------------------------------------
126  */
127
128 void
129 SetDatabasePath(const char *path)
130 {
131         if (DatabasePath)
132         {
133                 free(DatabasePath);
134                 DatabasePath = NULL;
135         }
136         /* use strdup since this is done before memory contexts are set up */
137         if (path)
138         {
139                 DatabasePath = strdup(path);
140                 AssertState(DatabasePath);
141         }
142 }
143
144 /*
145  * Set data directory, but make sure it's an absolute path.  Use this,
146  * never set DataDir directly.
147  */
148 void
149 SetDataDir(const char *dir)
150 {
151         char       *new;
152
153         AssertArg(dir);
154
155         /* If presented path is relative, convert to absolute */
156         new = make_absolute_path(dir);
157
158         if (DataDir)
159                 free(DataDir);
160         DataDir = new;
161 }
162
163 /*
164  * Change working directory to DataDir.  Most of the postmaster and backend
165  * code assumes that we are in DataDir so it can use relative paths to access
166  * stuff in and under the data directory.  For convenience during path
167  * setup, however, we don't force the chdir to occur during SetDataDir.
168  */
169 void
170 ChangeToDataDir(void)
171 {
172         AssertState(DataDir);
173
174         if (chdir(DataDir) < 0)
175                 ereport(FATAL,
176                                 (errcode_for_file_access(),
177                                  errmsg("could not change directory to \"%s\": %m",
178                                                 DataDir)));
179 }
180
181 /*
182  * If the given pathname isn't already absolute, make it so, interpreting
183  * it relative to the current working directory.
184  *
185  * Also canonicalizes the path.  The result is always a malloc'd copy.
186  *
187  * Note: interpretation of relative-path arguments during postmaster startup
188  * should happen before doing ChangeToDataDir(), else the user will probably
189  * not like the results.
190  */
191 char *
192 make_absolute_path(const char *path)
193 {
194         char       *new;
195
196         /* Returning null for null input is convenient for some callers */
197         if (path == NULL)
198                 return NULL;
199
200         if (!is_absolute_path(path))
201         {
202                 char       *buf;
203                 size_t          buflen;
204
205                 buflen = MAXPGPATH;
206                 for (;;)
207                 {
208                         buf = malloc(buflen);
209                         if (!buf)
210                                 ereport(FATAL,
211                                                 (errcode(ERRCODE_OUT_OF_MEMORY),
212                                                  errmsg("out of memory")));
213
214                         if (getcwd(buf, buflen))
215                                 break;
216                         else if (errno == ERANGE)
217                         {
218                                 free(buf);
219                                 buflen *= 2;
220                                 continue;
221                         }
222                         else
223                         {
224                                 free(buf);
225                                 elog(FATAL, "could not get current working directory: %m");
226                         }
227                 }
228
229                 new = malloc(strlen(buf) + strlen(path) + 2);
230                 if (!new)
231                         ereport(FATAL,
232                                         (errcode(ERRCODE_OUT_OF_MEMORY),
233                                          errmsg("out of memory")));
234                 sprintf(new, "%s/%s", buf, path);
235                 free(buf);
236         }
237         else
238         {
239                 new = strdup(path);
240                 if (!new)
241                         ereport(FATAL,
242                                         (errcode(ERRCODE_OUT_OF_MEMORY),
243                                          errmsg("out of memory")));
244         }
245
246         /* Make sure punctuation is canonical, too */
247         canonicalize_path(new);
248
249         return new;
250 }
251
252
253 /* ----------------------------------------------------------------
254  *      User ID state
255  *
256  * We have to track several different values associated with the concept
257  * of "user ID".
258  *
259  * AuthenticatedUserId is determined at connection start and never changes.
260  *
261  * SessionUserId is initially the same as AuthenticatedUserId, but can be
262  * changed by SET SESSION AUTHORIZATION (if AuthenticatedUserIsSuperuser).
263  * This is the ID reported by the SESSION_USER SQL function.
264  *
265  * OuterUserId is the current user ID in effect at the "outer level" (outside
266  * any transaction or function).  This is initially the same as SessionUserId,
267  * but can be changed by SET ROLE to any role that SessionUserId is a
268  * member of.  (XXX rename to something like CurrentRoleId?)
269  *
270  * CurrentUserId is the current effective user ID; this is the one to use
271  * for all normal permissions-checking purposes.  At outer level this will
272  * be the same as OuterUserId, but it changes during calls to SECURITY
273  * DEFINER functions, as well as locally in some specialized commands.
274  *
275  * SecurityDefinerContext is TRUE if we are within a SECURITY DEFINER function
276  * or another context that temporarily changes CurrentUserId.
277  * ----------------------------------------------------------------
278  */
279 static Oid      AuthenticatedUserId = InvalidOid;
280 static Oid      SessionUserId = InvalidOid;
281 static Oid      OuterUserId = InvalidOid;
282 static Oid      CurrentUserId = InvalidOid;
283
284 /* We also have to remember the superuser state of some of these levels */
285 static bool AuthenticatedUserIsSuperuser = false;
286 static bool SessionUserIsSuperuser = false;
287
288 static bool SecurityDefinerContext = false;
289
290 /* We also remember if a SET ROLE is currently active */
291 static bool SetRoleIsActive = false;
292
293
294 /*
295  * GetUserId - get the current effective user ID.
296  *
297  * Note: there's no SetUserId() anymore; use SetUserIdAndContext().
298  */
299 Oid
300 GetUserId(void)
301 {
302         AssertState(OidIsValid(CurrentUserId));
303         return CurrentUserId;
304 }
305
306
307 /*
308  * GetOuterUserId/SetOuterUserId - get/set the outer-level user ID.
309  */
310 Oid
311 GetOuterUserId(void)
312 {
313         AssertState(OidIsValid(OuterUserId));
314         return OuterUserId;
315 }
316
317
318 static void
319 SetOuterUserId(Oid userid)
320 {
321         AssertState(!SecurityDefinerContext);
322         AssertArg(OidIsValid(userid));
323         OuterUserId = userid;
324
325         /* We force the effective user ID to match, too */
326         CurrentUserId = userid;
327 }
328
329
330 /*
331  * GetSessionUserId/SetSessionUserId - get/set the session user ID.
332  */
333 Oid
334 GetSessionUserId(void)
335 {
336         AssertState(OidIsValid(SessionUserId));
337         return SessionUserId;
338 }
339
340
341 static void
342 SetSessionUserId(Oid userid, bool is_superuser)
343 {
344         AssertState(!SecurityDefinerContext);
345         AssertArg(OidIsValid(userid));
346         SessionUserId = userid;
347         SessionUserIsSuperuser = is_superuser;
348         SetRoleIsActive = false;
349
350         /* We force the effective user IDs to match, too */
351         OuterUserId = userid;
352         CurrentUserId = userid;
353 }
354
355
356 /*
357  * GetUserIdAndContext/SetUserIdAndContext - get/set the current user ID
358  * and the SecurityDefinerContext flag.
359  *
360  * Unlike GetUserId, GetUserIdAndContext does *not* Assert that the current
361  * value of CurrentUserId is valid; nor does SetUserIdAndContext require
362  * the new value to be valid.  In fact, these routines had better not
363  * ever throw any kind of error.  This is because they are used by
364  * StartTransaction and AbortTransaction to save/restore the settings,
365  * and during the first transaction within a backend, the value to be saved
366  * and perhaps restored is indeed invalid.  We have to be able to get
367  * through AbortTransaction without asserting in case InitPostgres fails.
368  */
369 void
370 GetUserIdAndContext(Oid *userid, bool *sec_def_context)
371 {
372         *userid = CurrentUserId;
373         *sec_def_context = SecurityDefinerContext;
374 }
375
376 void
377 SetUserIdAndContext(Oid userid, bool sec_def_context)
378 {
379         CurrentUserId = userid;
380         SecurityDefinerContext = sec_def_context;
381 }
382
383
384 /*
385  * InSecurityDefinerContext - are we inside a SECURITY DEFINER context?
386  */
387 bool
388 InSecurityDefinerContext(void)
389 {
390         return SecurityDefinerContext;
391 }
392
393
394 /*
395  * Initialize user identity during normal backend startup
396  */
397 void
398 InitializeSessionUserId(const char *rolename)
399 {
400         HeapTuple       roleTup;
401         Form_pg_authid rform;
402         Datum           datum;
403         bool            isnull;
404         Oid                     roleid;
405
406         /*
407          * Don't do scans if we're bootstrapping, none of the system catalogs
408          * exist yet, and they should be owned by postgres anyway.
409          */
410         AssertState(!IsBootstrapProcessingMode());
411
412         /* call only once */
413         AssertState(!OidIsValid(AuthenticatedUserId));
414
415         roleTup = SearchSysCache(AUTHNAME,
416                                                          PointerGetDatum(rolename),
417                                                          0, 0, 0);
418         if (!HeapTupleIsValid(roleTup))
419                 ereport(FATAL,
420                                 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
421                                  errmsg("role \"%s\" does not exist", rolename)));
422
423         rform = (Form_pg_authid) GETSTRUCT(roleTup);
424         roleid = HeapTupleGetOid(roleTup);
425
426         AuthenticatedUserId = roleid;
427         AuthenticatedUserIsSuperuser = rform->rolsuper;
428
429         /* This sets OuterUserId/CurrentUserId too */
430         SetSessionUserId(roleid, AuthenticatedUserIsSuperuser);
431
432         /* Also mark our PGPROC entry with the authenticated user id */
433         /* (We assume this is an atomic store so no lock is needed) */
434         MyProc->roleId = roleid;
435
436         /*
437          * These next checks are not enforced when in standalone mode, so that
438          * there is a way to recover from sillinesses like "UPDATE pg_authid SET
439          * rolcanlogin = false;".
440          *
441          * We do not enforce them for the autovacuum process either.
442          */
443         if (IsUnderPostmaster && !IsAutoVacuumWorkerProcess())
444         {
445                 /*
446                  * Is role allowed to login at all?
447                  */
448                 if (!rform->rolcanlogin)
449                         ereport(FATAL,
450                                         (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
451                                          errmsg("role \"%s\" is not permitted to log in",
452                                                         rolename)));
453
454                 /*
455                  * Check connection limit for this role.
456                  *
457                  * There is a race condition here --- we create our PGPROC before
458                  * checking for other PGPROCs.  If two backends did this at about the
459                  * same time, they might both think they were over the limit, while
460                  * ideally one should succeed and one fail.  Getting that to work
461                  * exactly seems more trouble than it is worth, however; instead we
462                  * just document that the connection limit is approximate.
463                  */
464                 if (rform->rolconnlimit >= 0 &&
465                         !AuthenticatedUserIsSuperuser &&
466                         CountUserBackends(roleid) > rform->rolconnlimit)
467                         ereport(FATAL,
468                                         (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
469                                          errmsg("too many connections for role \"%s\"",
470                                                         rolename)));
471         }
472
473         /* Record username and superuser status as GUC settings too */
474         SetConfigOption("session_authorization", rolename,
475                                         PGC_BACKEND, PGC_S_OVERRIDE);
476         SetConfigOption("is_superuser",
477                                         AuthenticatedUserIsSuperuser ? "on" : "off",
478                                         PGC_INTERNAL, PGC_S_OVERRIDE);
479
480         /*
481          * Set up user-specific configuration variables.  This is a good place to
482          * do it so we don't have to read pg_authid twice during session startup.
483          */
484         datum = SysCacheGetAttr(AUTHNAME, roleTup,
485                                                         Anum_pg_authid_rolconfig, &isnull);
486         if (!isnull)
487         {
488                 ArrayType  *a = DatumGetArrayTypeP(datum);
489
490                 /*
491                  * We process all the options at SUSET level.  We assume that the
492                  * right to insert an option into pg_authid was checked when it was
493                  * inserted.
494                  */
495                 ProcessGUCArray(a, PGC_SUSET, PGC_S_USER, GUC_ACTION_SET);
496         }
497
498         ReleaseSysCache(roleTup);
499 }
500
501
502 /*
503  * Initialize user identity during special backend startup
504  */
505 void
506 InitializeSessionUserIdStandalone(void)
507 {
508         /* This function should only be called in a single-user backend. */
509         AssertState(!IsUnderPostmaster || IsAutoVacuumWorkerProcess());
510
511         /* call only once */
512         AssertState(!OidIsValid(AuthenticatedUserId));
513
514         AuthenticatedUserId = BOOTSTRAP_SUPERUSERID;
515         AuthenticatedUserIsSuperuser = true;
516
517         SetSessionUserId(BOOTSTRAP_SUPERUSERID, true);
518 }
519
520
521 /*
522  * Change session auth ID while running
523  *
524  * Only a superuser may set auth ID to something other than himself.  Note
525  * that in case of multiple SETs in a single session, the original userid's
526  * superuserness is what matters.  But we set the GUC variable is_superuser
527  * to indicate whether the *current* session userid is a superuser.
528  *
529  * Note: this is not an especially clean place to do the permission check.
530  * It's OK because the check does not require catalog access and can't
531  * fail during an end-of-transaction GUC reversion, but we may someday
532  * have to push it up into assign_session_authorization.
533  */
534 void
535 SetSessionAuthorization(Oid userid, bool is_superuser)
536 {
537         /* Must have authenticated already, else can't make permission check */
538         AssertState(OidIsValid(AuthenticatedUserId));
539
540         if (userid != AuthenticatedUserId &&
541                 !AuthenticatedUserIsSuperuser)
542                 ereport(ERROR,
543                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
544                                  errmsg("permission denied to set session authorization")));
545
546         SetSessionUserId(userid, is_superuser);
547
548         SetConfigOption("is_superuser",
549                                         is_superuser ? "on" : "off",
550                                         PGC_INTERNAL, PGC_S_OVERRIDE);
551 }
552
553 /*
554  * Report current role id
555  *              This follows the semantics of SET ROLE, ie return the outer-level ID
556  *              not the current effective ID, and return InvalidOid when the setting
557  *              is logically SET ROLE NONE.
558  */
559 Oid
560 GetCurrentRoleId(void)
561 {
562         if (SetRoleIsActive)
563                 return OuterUserId;
564         else
565                 return InvalidOid;
566 }
567
568 /*
569  * Change Role ID while running (SET ROLE)
570  *
571  * If roleid is InvalidOid, we are doing SET ROLE NONE: revert to the
572  * session user authorization.  In this case the is_superuser argument
573  * is ignored.
574  *
575  * When roleid is not InvalidOid, the caller must have checked whether
576  * the session user has permission to become that role.  (We cannot check
577  * here because this routine must be able to execute in a failed transaction
578  * to restore a prior value of the ROLE GUC variable.)
579  */
580 void
581 SetCurrentRoleId(Oid roleid, bool is_superuser)
582 {
583         /*
584          * Get correct info if it's SET ROLE NONE
585          *
586          * If SessionUserId hasn't been set yet, just do nothing --- the eventual
587          * SetSessionUserId call will fix everything.  This is needed since we
588          * will get called during GUC initialization.
589          */
590         if (!OidIsValid(roleid))
591         {
592                 if (!OidIsValid(SessionUserId))
593                         return;
594
595                 roleid = SessionUserId;
596                 is_superuser = SessionUserIsSuperuser;
597
598                 SetRoleIsActive = false;
599         }
600         else
601                 SetRoleIsActive = true;
602
603         SetOuterUserId(roleid);
604
605         SetConfigOption("is_superuser",
606                                         is_superuser ? "on" : "off",
607                                         PGC_INTERNAL, PGC_S_OVERRIDE);
608 }
609
610
611 /*
612  * Get user name from user oid
613  */
614 char *
615 GetUserNameFromId(Oid roleid)
616 {
617         HeapTuple       tuple;
618         char       *result;
619
620         tuple = SearchSysCache(AUTHOID,
621                                                    ObjectIdGetDatum(roleid),
622                                                    0, 0, 0);
623         if (!HeapTupleIsValid(tuple))
624                 ereport(ERROR,
625                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
626                                  errmsg("invalid role OID: %u", roleid)));
627
628         result = pstrdup(NameStr(((Form_pg_authid) GETSTRUCT(tuple))->rolname));
629
630         ReleaseSysCache(tuple);
631         return result;
632 }
633
634
635 /*-------------------------------------------------------------------------
636  *                              Interlock-file support
637  *
638  * These routines are used to create both a data-directory lockfile
639  * ($DATADIR/postmaster.pid) and a Unix-socket-file lockfile ($SOCKFILE.lock).
640  * Both kinds of files contain the same info:
641  *
642  *              Owning process' PID
643  *              Data directory path
644  *
645  * By convention, the owning process' PID is negated if it is a standalone
646  * backend rather than a postmaster.  This is just for informational purposes.
647  * The path is also just for informational purposes (so that a socket lockfile
648  * can be more easily traced to the associated postmaster).
649  *
650  * A data-directory lockfile can optionally contain a third line, containing
651  * the key and ID for the shared memory block used by this postmaster.
652  *
653  * On successful lockfile creation, a proc_exit callback to remove the
654  * lockfile is automatically created.
655  *-------------------------------------------------------------------------
656  */
657
658 /*
659  * proc_exit callback to remove a lockfile.
660  */
661 static void
662 UnlinkLockFile(int status, Datum filename)
663 {
664         char       *fname = (char *) DatumGetPointer(filename);
665
666         if (fname != NULL)
667         {
668                 if (unlink(fname) != 0)
669                 {
670                         /* Should we complain if the unlink fails? */
671                 }
672                 free(fname);
673         }
674 }
675
676 /*
677  * Create a lockfile.
678  *
679  * filename is the name of the lockfile to create.
680  * amPostmaster is used to determine how to encode the output PID.
681  * isDDLock and refName are used to determine what error message to produce.
682  */
683 static void
684 CreateLockFile(const char *filename, bool amPostmaster,
685                            bool isDDLock, const char *refName)
686 {
687         int                     fd;
688         char            buffer[MAXPGPATH + 100];
689         int                     ntries;
690         int                     len;
691         int                     encoded_pid;
692         pid_t           other_pid;
693         pid_t           my_pid = getpid();
694
695         /*
696          * We need a loop here because of race conditions.      But don't loop forever
697          * (for example, a non-writable $PGDATA directory might cause a failure
698          * that won't go away).  100 tries seems like plenty.
699          */
700         for (ntries = 0;; ntries++)
701         {
702                 /*
703                  * Try to create the lock file --- O_EXCL makes this atomic.
704                  *
705                  * Think not to make the file protection weaker than 0600.      See
706                  * comments below.
707                  */
708                 fd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
709                 if (fd >= 0)
710                         break;                          /* Success; exit the retry loop */
711
712                 /*
713                  * Couldn't create the pid file. Probably it already exists.
714                  */
715                 if ((errno != EEXIST && errno != EACCES) || ntries > 100)
716                         ereport(FATAL,
717                                         (errcode_for_file_access(),
718                                          errmsg("could not create lock file \"%s\": %m",
719                                                         filename)));
720
721                 /*
722                  * Read the file to get the old owner's PID.  Note race condition
723                  * here: file might have been deleted since we tried to create it.
724                  */
725                 fd = open(filename, O_RDONLY, 0600);
726                 if (fd < 0)
727                 {
728                         if (errno == ENOENT)
729                                 continue;               /* race condition; try again */
730                         ereport(FATAL,
731                                         (errcode_for_file_access(),
732                                          errmsg("could not open lock file \"%s\": %m",
733                                                         filename)));
734                 }
735                 if ((len = read(fd, buffer, sizeof(buffer) - 1)) < 0)
736                         ereport(FATAL,
737                                         (errcode_for_file_access(),
738                                          errmsg("could not read lock file \"%s\": %m",
739                                                         filename)));
740                 close(fd);
741
742                 buffer[len] = '\0';
743                 encoded_pid = atoi(buffer);
744
745                 /* if pid < 0, the pid is for postgres, not postmaster */
746                 other_pid = (pid_t) (encoded_pid < 0 ? -encoded_pid : encoded_pid);
747
748                 if (other_pid <= 0)
749                         elog(FATAL, "bogus data in lock file \"%s\": \"%s\"",
750                                  filename, buffer);
751
752                 /*
753                  * Check to see if the other process still exists
754                  *
755                  * If the PID in the lockfile is our own PID or our parent's PID, then
756                  * the file must be stale (probably left over from a previous system
757                  * boot cycle).  We need this test because of the likelihood that a
758                  * reboot will assign exactly the same PID as we had in the previous
759                  * reboot.      Also, if there is just one more process launch in this
760                  * reboot than in the previous one, the lockfile might mention our
761                  * parent's PID.  We can reject that since we'd never be launched
762                  * directly by a competing postmaster.  We can't detect grandparent
763                  * processes unfortunately, but if the init script is written
764                  * carefully then all but the immediate parent shell will be
765                  * root-owned processes and so the kill test will fail with EPERM.
766                  *
767                  * We can treat the EPERM-error case as okay because that error
768                  * implies that the existing process has a different userid than we
769                  * do, which means it cannot be a competing postmaster.  A postmaster
770                  * cannot successfully attach to a data directory owned by a userid
771                  * other than its own.  (This is now checked directly in
772                  * checkDataDir(), but has been true for a long time because of the
773                  * restriction that the data directory isn't group- or
774                  * world-accessible.)  Also, since we create the lockfiles mode 600,
775                  * we'd have failed above if the lockfile belonged to another userid
776                  * --- which means that whatever process kill() is reporting about
777                  * isn't the one that made the lockfile.  (NOTE: this last
778                  * consideration is the only one that keeps us from blowing away a
779                  * Unix socket file belonging to an instance of Postgres being run by
780                  * someone else, at least on machines where /tmp hasn't got a
781                  * stickybit.)
782                  *
783                  * Windows hasn't got getppid(), but doesn't need it since it's not
784                  * using real kill() either...
785                  *
786                  * Normally kill() will fail with ESRCH if the given PID doesn't
787                  * exist.
788                  */
789                 if (other_pid != my_pid
790 #ifndef WIN32
791                         && other_pid != getppid()
792 #endif
793                         )
794                 {
795                         if (kill(other_pid, 0) == 0 ||
796                                 (errno != ESRCH && errno != EPERM))
797                         {
798                                 /* lockfile belongs to a live process */
799                                 ereport(FATAL,
800                                                 (errcode(ERRCODE_LOCK_FILE_EXISTS),
801                                                  errmsg("lock file \"%s\" already exists",
802                                                                 filename),
803                                                  isDDLock ?
804                                                  (encoded_pid < 0 ?
805                                                   errhint("Is another postgres (PID %d) running in data directory \"%s\"?",
806                                                                   (int) other_pid, refName) :
807                                                   errhint("Is another postmaster (PID %d) running in data directory \"%s\"?",
808                                                                   (int) other_pid, refName)) :
809                                                  (encoded_pid < 0 ?
810                                                   errhint("Is another postgres (PID %d) using socket file \"%s\"?",
811                                                                   (int) other_pid, refName) :
812                                                   errhint("Is another postmaster (PID %d) using socket file \"%s\"?",
813                                                                   (int) other_pid, refName))));
814                         }
815                 }
816
817                 /*
818                  * No, the creating process did not exist.      However, it could be that
819                  * the postmaster crashed (or more likely was kill -9'd by a clueless
820                  * admin) but has left orphan backends behind.  Check for this by
821                  * looking to see if there is an associated shmem segment that is
822                  * still in use.
823                  */
824                 if (isDDLock)
825                 {
826                         char       *ptr;
827                         unsigned long id1,
828                                                 id2;
829
830                         ptr = strchr(buffer, '\n');
831                         if (ptr != NULL &&
832                                 (ptr = strchr(ptr + 1, '\n')) != NULL)
833                         {
834                                 ptr++;
835                                 if (sscanf(ptr, "%lu %lu", &id1, &id2) == 2)
836                                 {
837                                         if (PGSharedMemoryIsInUse(id1, id2))
838                                                 ereport(FATAL,
839                                                                 (errcode(ERRCODE_LOCK_FILE_EXISTS),
840                                                                  errmsg("pre-existing shared memory block "
841                                                                                 "(key %lu, ID %lu) is still in use",
842                                                                                 id1, id2),
843                                                                  errhint("If you're sure there are no old "
844                                                                         "server processes still running, remove "
845                                                                                  "the shared memory block "
846                                                                                  "or just delete the file \"%s\".",
847                                                                                  filename)));
848                                 }
849                         }
850                 }
851
852                 /*
853                  * Looks like nobody's home.  Unlink the file and try again to create
854                  * it.  Need a loop because of possible race condition against other
855                  * would-be creators.
856                  */
857                 if (unlink(filename) < 0)
858                         ereport(FATAL,
859                                         (errcode_for_file_access(),
860                                          errmsg("could not remove old lock file \"%s\": %m",
861                                                         filename),
862                                          errhint("The file seems accidentally left over, but "
863                                                    "it could not be removed. Please remove the file "
864                                                          "by hand and try again.")));
865         }
866
867         /*
868          * Successfully created the file, now fill it.
869          */
870         snprintf(buffer, sizeof(buffer), "%d\n%s\n",
871                          amPostmaster ? (int) my_pid : -((int) my_pid),
872                          DataDir);
873         errno = 0;
874         if (write(fd, buffer, strlen(buffer)) != strlen(buffer))
875         {
876                 int                     save_errno = errno;
877
878                 close(fd);
879                 unlink(filename);
880                 /* if write didn't set errno, assume problem is no disk space */
881                 errno = save_errno ? save_errno : ENOSPC;
882                 ereport(FATAL,
883                                 (errcode_for_file_access(),
884                                  errmsg("could not write lock file \"%s\": %m", filename)));
885         }
886         if (close(fd))
887         {
888                 int                     save_errno = errno;
889
890                 unlink(filename);
891                 errno = save_errno;
892                 ereport(FATAL,
893                                 (errcode_for_file_access(),
894                                  errmsg("could not write lock file \"%s\": %m", filename)));
895         }
896
897         /*
898          * Arrange for automatic removal of lockfile at proc_exit.
899          */
900         on_proc_exit(UnlinkLockFile, PointerGetDatum(strdup(filename)));
901 }
902
903 /*
904  * Create the data directory lockfile.
905  *
906  * When this is called, we must have already switched the working
907  * directory to DataDir, so we can just use a relative path.  This
908  * helps ensure that we are locking the directory we should be.
909  */
910 void
911 CreateDataDirLockFile(bool amPostmaster)
912 {
913         CreateLockFile(DIRECTORY_LOCK_FILE, amPostmaster, true, DataDir);
914 }
915
916 /*
917  * Create a lockfile for the specified Unix socket file.
918  */
919 void
920 CreateSocketLockFile(const char *socketfile, bool amPostmaster)
921 {
922         char            lockfile[MAXPGPATH];
923
924         snprintf(lockfile, sizeof(lockfile), "%s.lock", socketfile);
925         CreateLockFile(lockfile, amPostmaster, false, socketfile);
926         /* Save name of lockfile for TouchSocketLockFile */
927         strcpy(socketLockFile, lockfile);
928 }
929
930 /*
931  * TouchSocketLockFile -- mark socket lock file as recently accessed
932  *
933  * This routine should be called every so often to ensure that the lock file
934  * has a recent mod or access date.  That saves it
935  * from being removed by overenthusiastic /tmp-directory-cleaner daemons.
936  * (Another reason we should never have put the socket file in /tmp...)
937  */
938 void
939 TouchSocketLockFile(void)
940 {
941         /* Do nothing if we did not create a socket... */
942         if (socketLockFile[0] != '\0')
943         {
944                 /*
945                  * utime() is POSIX standard, utimes() is a common alternative; if we
946                  * have neither, fall back to actually reading the file (which only
947                  * sets the access time not mod time, but that should be enough in
948                  * most cases).  In all paths, we ignore errors.
949                  */
950 #ifdef HAVE_UTIME
951                 utime(socketLockFile, NULL);
952 #else                                                   /* !HAVE_UTIME */
953 #ifdef HAVE_UTIMES
954                 utimes(socketLockFile, NULL);
955 #else                                                   /* !HAVE_UTIMES */
956                 int                     fd;
957                 char            buffer[1];
958
959                 fd = open(socketLockFile, O_RDONLY | PG_BINARY, 0);
960                 if (fd >= 0)
961                 {
962                         read(fd, buffer, sizeof(buffer));
963                         close(fd);
964                 }
965 #endif   /* HAVE_UTIMES */
966 #endif   /* HAVE_UTIME */
967         }
968 }
969
970 /*
971  * Append information about a shared memory segment to the data directory
972  * lock file.
973  *
974  * This may be called multiple times in the life of a postmaster, if we
975  * delete and recreate shmem due to backend crash.      Therefore, be prepared
976  * to overwrite existing information.  (As of 7.1, a postmaster only creates
977  * one shm seg at a time; but for the purposes here, if we did have more than
978  * one then any one of them would do anyway.)
979  */
980 void
981 RecordSharedMemoryInLockFile(unsigned long id1, unsigned long id2)
982 {
983         int                     fd;
984         int                     len;
985         char       *ptr;
986         char            buffer[BLCKSZ];
987
988         fd = open(DIRECTORY_LOCK_FILE, O_RDWR | PG_BINARY, 0);
989         if (fd < 0)
990         {
991                 ereport(LOG,
992                                 (errcode_for_file_access(),
993                                  errmsg("could not open file \"%s\": %m",
994                                                 DIRECTORY_LOCK_FILE)));
995                 return;
996         }
997         len = read(fd, buffer, sizeof(buffer) - 100);
998         if (len < 0)
999         {
1000                 ereport(LOG,
1001                                 (errcode_for_file_access(),
1002                                  errmsg("could not read from file \"%s\": %m",
1003                                                 DIRECTORY_LOCK_FILE)));
1004                 close(fd);
1005                 return;
1006         }
1007         buffer[len] = '\0';
1008
1009         /*
1010          * Skip over first two lines (PID and path).
1011          */
1012         ptr = strchr(buffer, '\n');
1013         if (ptr == NULL ||
1014                 (ptr = strchr(ptr + 1, '\n')) == NULL)
1015         {
1016                 elog(LOG, "bogus data in \"%s\"", DIRECTORY_LOCK_FILE);
1017                 close(fd);
1018                 return;
1019         }
1020         ptr++;
1021
1022         /*
1023          * Append key information.      Format to try to keep it the same length
1024          * always (trailing junk won't hurt, but might confuse humans).
1025          */
1026         sprintf(ptr, "%9lu %9lu\n", id1, id2);
1027
1028         /*
1029          * And rewrite the data.  Since we write in a single kernel call, this
1030          * update should appear atomic to onlookers.
1031          */
1032         len = strlen(buffer);
1033         errno = 0;
1034         if (lseek(fd, (off_t) 0, SEEK_SET) != 0 ||
1035                 (int) write(fd, buffer, len) != len)
1036         {
1037                 /* if write didn't set errno, assume problem is no disk space */
1038                 if (errno == 0)
1039                         errno = ENOSPC;
1040                 ereport(LOG,
1041                                 (errcode_for_file_access(),
1042                                  errmsg("could not write to file \"%s\": %m",
1043                                                 DIRECTORY_LOCK_FILE)));
1044                 close(fd);
1045                 return;
1046         }
1047         if (close(fd))
1048         {
1049                 ereport(LOG,
1050                                 (errcode_for_file_access(),
1051                                  errmsg("could not write to file \"%s\": %m",
1052                                                 DIRECTORY_LOCK_FILE)));
1053         }
1054 }
1055
1056
1057 /*-------------------------------------------------------------------------
1058  *                              Version checking support
1059  *-------------------------------------------------------------------------
1060  */
1061
1062 /*
1063  * Determine whether the PG_VERSION file in directory `path' indicates
1064  * a data version compatible with the version of this program.
1065  *
1066  * If compatible, return. Otherwise, ereport(FATAL).
1067  */
1068 void
1069 ValidatePgVersion(const char *path)
1070 {
1071         char            full_path[MAXPGPATH];
1072         FILE       *file;
1073         int                     ret;
1074         long            file_major,
1075                                 file_minor;
1076         long            my_major = 0,
1077                                 my_minor = 0;
1078         char       *endptr;
1079         const char *version_string = PG_VERSION;
1080
1081         my_major = strtol(version_string, &endptr, 10);
1082         if (*endptr == '.')
1083                 my_minor = strtol(endptr + 1, NULL, 10);
1084
1085         snprintf(full_path, sizeof(full_path), "%s/PG_VERSION", path);
1086
1087         file = AllocateFile(full_path, "r");
1088         if (!file)
1089         {
1090                 if (errno == ENOENT)
1091                         ereport(FATAL,
1092                                         (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1093                                          errmsg("\"%s\" is not a valid data directory",
1094                                                         path),
1095                                          errdetail("File \"%s\" is missing.", full_path)));
1096                 else
1097                         ereport(FATAL,
1098                                         (errcode_for_file_access(),
1099                                          errmsg("could not open file \"%s\": %m", full_path)));
1100         }
1101
1102         ret = fscanf(file, "%ld.%ld", &file_major, &file_minor);
1103         if (ret != 2)
1104                 ereport(FATAL,
1105                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1106                                  errmsg("\"%s\" is not a valid data directory",
1107                                                 path),
1108                                  errdetail("File \"%s\" does not contain valid data.",
1109                                                    full_path),
1110                                  errhint("You might need to initdb.")));
1111
1112         FreeFile(file);
1113
1114         if (my_major != file_major || my_minor != file_minor)
1115                 ereport(FATAL,
1116                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1117                                  errmsg("database files are incompatible with server"),
1118                                  errdetail("The data directory was initialized by PostgreSQL version %ld.%ld, "
1119                                                    "which is not compatible with this version %s.",
1120                                                    file_major, file_minor, version_string)));
1121 }
1122
1123 /*-------------------------------------------------------------------------
1124  *                              Library preload support
1125  *-------------------------------------------------------------------------
1126  */
1127
1128 /*
1129  * GUC variables: lists of library names to be preloaded at postmaster
1130  * start and at backend start
1131  */
1132 char       *shared_preload_libraries_string = NULL;
1133 char       *local_preload_libraries_string = NULL;
1134
1135 /* Flag telling that we are loading shared_preload_libraries */
1136 bool            process_shared_preload_libraries_in_progress = false;
1137
1138 /*
1139  * load the shared libraries listed in 'libraries'
1140  *
1141  * 'gucname': name of GUC variable, for error reports
1142  * 'restricted': if true, force libraries to be in $libdir/plugins/
1143  */
1144 static void
1145 load_libraries(const char *libraries, const char *gucname, bool restricted)
1146 {
1147         char       *rawstring;
1148         List       *elemlist;
1149         int                     elevel;
1150         ListCell   *l;
1151
1152         if (libraries == NULL || libraries[0] == '\0')
1153                 return;                                 /* nothing to do */
1154
1155         /* Need a modifiable copy of string */
1156         rawstring = pstrdup(libraries);
1157
1158         /* Parse string into list of identifiers */
1159         if (!SplitIdentifierString(rawstring, ',', &elemlist))
1160         {
1161                 /* syntax error in list */
1162                 pfree(rawstring);
1163                 list_free(elemlist);
1164                 ereport(LOG,
1165                                 (errcode(ERRCODE_SYNTAX_ERROR),
1166                                  errmsg("invalid list syntax in parameter \"%s\"",
1167                                                 gucname)));
1168                 return;
1169         }
1170
1171         /*
1172          * Choose notice level: avoid repeat messages when re-loading a library
1173          * that was preloaded into the postmaster.  (Only possible in EXEC_BACKEND
1174          * configurations)
1175          */
1176 #ifdef EXEC_BACKEND
1177         if (IsUnderPostmaster && process_shared_preload_libraries_in_progress)
1178                 elevel = DEBUG2;
1179         else
1180 #endif
1181                 elevel = LOG;
1182
1183         foreach(l, elemlist)
1184         {
1185                 char       *tok = (char *) lfirst(l);
1186                 char       *filename;
1187
1188                 filename = pstrdup(tok);
1189                 canonicalize_path(filename);
1190                 /* If restricting, insert $libdir/plugins if not mentioned already */
1191                 if (restricted && first_dir_separator(filename) == NULL)
1192                 {
1193                         char       *expanded;
1194
1195                         expanded = palloc(strlen("$libdir/plugins/") + strlen(filename) + 1);
1196                         strcpy(expanded, "$libdir/plugins/");
1197                         strcat(expanded, filename);
1198                         pfree(filename);
1199                         filename = expanded;
1200                 }
1201                 load_file(filename, restricted);
1202                 ereport(elevel,
1203                                 (errmsg("loaded library \"%s\"", filename)));
1204                 pfree(filename);
1205         }
1206
1207         pfree(rawstring);
1208         list_free(elemlist);
1209 }
1210
1211 /*
1212  * process any libraries that should be preloaded at postmaster start
1213  */
1214 void
1215 process_shared_preload_libraries(void)
1216 {
1217         process_shared_preload_libraries_in_progress = true;
1218         load_libraries(shared_preload_libraries_string,
1219                                    "shared_preload_libraries",
1220                                    false);
1221         process_shared_preload_libraries_in_progress = false;
1222 }
1223
1224 /*
1225  * process any libraries that should be preloaded at backend start
1226  */
1227 void
1228 process_local_preload_libraries(void)
1229 {
1230         load_libraries(local_preload_libraries_string,
1231                                    "local_preload_libraries",
1232                                    true);
1233 }
1234
1235 void
1236 pg_bindtextdomain(const char *domain)
1237 {
1238 #ifdef ENABLE_NLS
1239         if (my_exec_path[0] != '\0')
1240         {
1241                 char    locale_path[MAXPGPATH];
1242
1243                 get_locale_path(my_exec_path, locale_path);
1244                 bindtextdomain(domain, locale_path);
1245                 pg_bind_textdomain_codeset(domain);
1246         }
1247 #endif
1248 }