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