]> granicus.if.org Git - postgresql/blob - src/backend/utils/init/miscinit.c
Move some things from builtins.h to new header files
[postgresql] / src / backend / utils / init / miscinit.c
1 /*-------------------------------------------------------------------------
2  *
3  * miscinit.c
4  *        miscellaneous initialization support stuff
5  *
6  * Portions Copyright (c) 1996-2017, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *        src/backend/utils/init/miscinit.c
12  *
13  *-------------------------------------------------------------------------
14  */
15 #include "postgres.h"
16
17 #include <sys/param.h>
18 #include <signal.h>
19 #include <time.h>
20 #include <sys/file.h>
21 #include <sys/stat.h>
22 #include <sys/time.h>
23 #include <sys/types.h>
24 #include <fcntl.h>
25 #include <unistd.h>
26 #include <grp.h>
27 #include <pwd.h>
28 #include <netinet/in.h>
29 #include <arpa/inet.h>
30 #ifdef HAVE_UTIME_H
31 #include <utime.h>
32 #endif
33
34 #include "access/htup_details.h"
35 #include "catalog/pg_authid.h"
36 #include "libpq/libpq.h"
37 #include "mb/pg_wchar.h"
38 #include "miscadmin.h"
39 #include "postmaster/autovacuum.h"
40 #include "postmaster/postmaster.h"
41 #include "storage/fd.h"
42 #include "storage/ipc.h"
43 #include "storage/latch.h"
44 #include "storage/pg_shmem.h"
45 #include "storage/proc.h"
46 #include "storage/procarray.h"
47 #include "utils/builtins.h"
48 #include "utils/guc.h"
49 #include "utils/memutils.h"
50 #include "utils/syscache.h"
51 #include "utils/varlena.h"
52
53
54 #define DIRECTORY_LOCK_FILE             "postmaster.pid"
55
56 ProcessingMode Mode = InitProcessing;
57
58 /* List of lock files to be removed at proc exit */
59 static List *lock_files = NIL;
60
61 static Latch LocalLatchData;
62
63 /* ----------------------------------------------------------------
64  *              ignoring system indexes support stuff
65  *
66  * NOTE: "ignoring system indexes" means we do not use the system indexes
67  * for lookups (either in hardwired catalog accesses or in planner-generated
68  * plans).  We do, however, still update the indexes when a catalog
69  * modification is made.
70  * ----------------------------------------------------------------
71  */
72
73 bool            IgnoreSystemIndexes = false;
74
75
76 /* ----------------------------------------------------------------
77  *                              database path / name support stuff
78  * ----------------------------------------------------------------
79  */
80
81 void
82 SetDatabasePath(const char *path)
83 {
84         /* This should happen only once per process */
85         Assert(!DatabasePath);
86         DatabasePath = MemoryContextStrdup(TopMemoryContext, path);
87 }
88
89 /*
90  * Set data directory, but make sure it's an absolute path.  Use this,
91  * never set DataDir directly.
92  */
93 void
94 SetDataDir(const char *dir)
95 {
96         char       *new;
97
98         AssertArg(dir);
99
100         /* If presented path is relative, convert to absolute */
101         new = make_absolute_path(dir);
102
103         if (DataDir)
104                 free(DataDir);
105         DataDir = new;
106 }
107
108 /*
109  * Change working directory to DataDir.  Most of the postmaster and backend
110  * code assumes that we are in DataDir so it can use relative paths to access
111  * stuff in and under the data directory.  For convenience during path
112  * setup, however, we don't force the chdir to occur during SetDataDir.
113  */
114 void
115 ChangeToDataDir(void)
116 {
117         AssertState(DataDir);
118
119         if (chdir(DataDir) < 0)
120                 ereport(FATAL,
121                                 (errcode_for_file_access(),
122                                  errmsg("could not change directory to \"%s\": %m",
123                                                 DataDir)));
124 }
125
126
127 /* ----------------------------------------------------------------
128  *      User ID state
129  *
130  * We have to track several different values associated with the concept
131  * of "user ID".
132  *
133  * AuthenticatedUserId is determined at connection start and never changes.
134  *
135  * SessionUserId is initially the same as AuthenticatedUserId, but can be
136  * changed by SET SESSION AUTHORIZATION (if AuthenticatedUserIsSuperuser).
137  * This is the ID reported by the SESSION_USER SQL function.
138  *
139  * OuterUserId is the current user ID in effect at the "outer level" (outside
140  * any transaction or function).  This is initially the same as SessionUserId,
141  * but can be changed by SET ROLE to any role that SessionUserId is a
142  * member of.  (XXX rename to something like CurrentRoleId?)
143  *
144  * CurrentUserId is the current effective user ID; this is the one to use
145  * for all normal permissions-checking purposes.  At outer level this will
146  * be the same as OuterUserId, but it changes during calls to SECURITY
147  * DEFINER functions, as well as locally in some specialized commands.
148  *
149  * SecurityRestrictionContext holds flags indicating reason(s) for changing
150  * CurrentUserId.  In some cases we need to lock down operations that are
151  * not directly controlled by privilege settings, and this provides a
152  * convenient way to do it.
153  * ----------------------------------------------------------------
154  */
155 static Oid      AuthenticatedUserId = InvalidOid;
156 static Oid      SessionUserId = InvalidOid;
157 static Oid      OuterUserId = InvalidOid;
158 static Oid      CurrentUserId = InvalidOid;
159
160 /* We also have to remember the superuser state of some of these levels */
161 static bool AuthenticatedUserIsSuperuser = false;
162 static bool SessionUserIsSuperuser = false;
163
164 static int      SecurityRestrictionContext = 0;
165
166 /* We also remember if a SET ROLE is currently active */
167 static bool SetRoleIsActive = false;
168
169 /*
170  * Initialize the basic environment for a postmaster child
171  *
172  * Should be called as early as possible after the child's startup.
173  */
174 void
175 InitPostmasterChild(void)
176 {
177         IsUnderPostmaster = true;       /* we are a postmaster subprocess now */
178
179         MyProcPid = getpid();           /* reset MyProcPid */
180
181         MyStartTime = time(NULL);       /* set our start time in case we call elog */
182
183         /*
184          * make sure stderr is in binary mode before anything can possibly be
185          * written to it, in case it's actually the syslogger pipe, so the pipe
186          * chunking protocol isn't disturbed. Non-logpipe data gets translated on
187          * redirection (e.g. via pg_ctl -l) anyway.
188          */
189 #ifdef WIN32
190         _setmode(fileno(stderr), _O_BINARY);
191 #endif
192
193         /* We don't want the postmaster's proc_exit() handlers */
194         on_exit_reset();
195
196         /* Initialize process-local latch support */
197         InitializeLatchSupport();
198         MyLatch = &LocalLatchData;
199         InitLatch(MyLatch);
200
201         /*
202          * If possible, make this process a group leader, so that the postmaster
203          * can signal any child processes too. Not all processes will have
204          * children, but for consistency we make all postmaster child processes do
205          * this.
206          */
207 #ifdef HAVE_SETSID
208         if (setsid() < 0)
209                 elog(FATAL, "setsid() failed: %m");
210 #endif
211 }
212
213 /*
214  * Initialize the basic environment for a standalone process.
215  *
216  * argv0 has to be suitable to find the program's executable.
217  */
218 void
219 InitStandaloneProcess(const char *argv0)
220 {
221         Assert(!IsPostmasterEnvironment);
222
223         MyProcPid = getpid();           /* reset MyProcPid */
224
225         MyStartTime = time(NULL);       /* set our start time in case we call elog */
226
227         /* Initialize process-local latch support */
228         InitializeLatchSupport();
229         MyLatch = &LocalLatchData;
230         InitLatch(MyLatch);
231
232         /* Compute paths, no postmaster to inherit from */
233         if (my_exec_path[0] == '\0')
234         {
235                 if (find_my_exec(argv0, my_exec_path) < 0)
236                         elog(FATAL, "%s: could not locate my own executable path",
237                                  argv0);
238         }
239
240         if (pkglib_path[0] == '\0')
241                 get_pkglib_path(my_exec_path, pkglib_path);
242 }
243
244 void
245 SwitchToSharedLatch(void)
246 {
247         Assert(MyLatch == &LocalLatchData);
248         Assert(MyProc != NULL);
249
250         MyLatch = &MyProc->procLatch;
251
252         if (FeBeWaitSet)
253                 ModifyWaitEvent(FeBeWaitSet, 1, WL_LATCH_SET, MyLatch);
254
255         /*
256          * Set the shared latch as the local one might have been set. This
257          * shouldn't normally be necessary as code is supposed to check the
258          * condition before waiting for the latch, but a bit care can't hurt.
259          */
260         SetLatch(MyLatch);
261 }
262
263 void
264 SwitchBackToLocalLatch(void)
265 {
266         Assert(MyLatch != &LocalLatchData);
267         Assert(MyProc != NULL && MyLatch == &MyProc->procLatch);
268
269         MyLatch = &LocalLatchData;
270
271         if (FeBeWaitSet)
272                 ModifyWaitEvent(FeBeWaitSet, 1, WL_LATCH_SET, MyLatch);
273
274         SetLatch(MyLatch);
275 }
276
277 /*
278  * GetUserId - get the current effective user ID.
279  *
280  * Note: there's no SetUserId() anymore; use SetUserIdAndSecContext().
281  */
282 Oid
283 GetUserId(void)
284 {
285         AssertState(OidIsValid(CurrentUserId));
286         return CurrentUserId;
287 }
288
289
290 /*
291  * GetOuterUserId/SetOuterUserId - get/set the outer-level user ID.
292  */
293 Oid
294 GetOuterUserId(void)
295 {
296         AssertState(OidIsValid(OuterUserId));
297         return OuterUserId;
298 }
299
300
301 static void
302 SetOuterUserId(Oid userid)
303 {
304         AssertState(SecurityRestrictionContext == 0);
305         AssertArg(OidIsValid(userid));
306         OuterUserId = userid;
307
308         /* We force the effective user ID to match, too */
309         CurrentUserId = userid;
310 }
311
312
313 /*
314  * GetSessionUserId/SetSessionUserId - get/set the session user ID.
315  */
316 Oid
317 GetSessionUserId(void)
318 {
319         AssertState(OidIsValid(SessionUserId));
320         return SessionUserId;
321 }
322
323
324 static void
325 SetSessionUserId(Oid userid, bool is_superuser)
326 {
327         AssertState(SecurityRestrictionContext == 0);
328         AssertArg(OidIsValid(userid));
329         SessionUserId = userid;
330         SessionUserIsSuperuser = is_superuser;
331         SetRoleIsActive = false;
332
333         /* We force the effective user IDs to match, too */
334         OuterUserId = userid;
335         CurrentUserId = userid;
336 }
337
338 /*
339  * GetAuthenticatedUserId - get the authenticated user ID
340  */
341 Oid
342 GetAuthenticatedUserId(void)
343 {
344         AssertState(OidIsValid(AuthenticatedUserId));
345         return AuthenticatedUserId;
346 }
347
348
349 /*
350  * GetUserIdAndSecContext/SetUserIdAndSecContext - get/set the current user ID
351  * and the SecurityRestrictionContext flags.
352  *
353  * Currently there are three valid bits in SecurityRestrictionContext:
354  *
355  * SECURITY_LOCAL_USERID_CHANGE indicates that we are inside an operation
356  * that is temporarily changing CurrentUserId via these functions.  This is
357  * needed to indicate that the actual value of CurrentUserId is not in sync
358  * with guc.c's internal state, so SET ROLE has to be disallowed.
359  *
360  * SECURITY_RESTRICTED_OPERATION indicates that we are inside an operation
361  * that does not wish to trust called user-defined functions at all.  This
362  * bit prevents not only SET ROLE, but various other changes of session state
363  * that normally is unprotected but might possibly be used to subvert the
364  * calling session later.  An example is replacing an existing prepared
365  * statement with new code, which will then be executed with the outer
366  * session's permissions when the prepared statement is next used.  Since
367  * these restrictions are fairly draconian, we apply them only in contexts
368  * where the called functions are really supposed to be side-effect-free
369  * anyway, such as VACUUM/ANALYZE/REINDEX.
370  *
371  * SECURITY_NOFORCE_RLS indicates that we are inside an operation which should
372  * ignore the FORCE ROW LEVEL SECURITY per-table indication.  This is used to
373  * ensure that FORCE RLS does not mistakenly break referential integrity
374  * checks.  Note that this is intentionally only checked when running as the
375  * owner of the table (which should always be the case for referential
376  * integrity checks).
377  *
378  * Unlike GetUserId, GetUserIdAndSecContext does *not* Assert that the current
379  * value of CurrentUserId is valid; nor does SetUserIdAndSecContext require
380  * the new value to be valid.  In fact, these routines had better not
381  * ever throw any kind of error.  This is because they are used by
382  * StartTransaction and AbortTransaction to save/restore the settings,
383  * and during the first transaction within a backend, the value to be saved
384  * and perhaps restored is indeed invalid.  We have to be able to get
385  * through AbortTransaction without asserting in case InitPostgres fails.
386  */
387 void
388 GetUserIdAndSecContext(Oid *userid, int *sec_context)
389 {
390         *userid = CurrentUserId;
391         *sec_context = SecurityRestrictionContext;
392 }
393
394 void
395 SetUserIdAndSecContext(Oid userid, int sec_context)
396 {
397         CurrentUserId = userid;
398         SecurityRestrictionContext = sec_context;
399 }
400
401
402 /*
403  * InLocalUserIdChange - are we inside a local change of CurrentUserId?
404  */
405 bool
406 InLocalUserIdChange(void)
407 {
408         return (SecurityRestrictionContext & SECURITY_LOCAL_USERID_CHANGE) != 0;
409 }
410
411 /*
412  * InSecurityRestrictedOperation - are we inside a security-restricted command?
413  */
414 bool
415 InSecurityRestrictedOperation(void)
416 {
417         return (SecurityRestrictionContext & SECURITY_RESTRICTED_OPERATION) != 0;
418 }
419
420 /*
421  * InNoForceRLSOperation - are we ignoring FORCE ROW LEVEL SECURITY ?
422  */
423 bool
424 InNoForceRLSOperation(void)
425 {
426         return (SecurityRestrictionContext & SECURITY_NOFORCE_RLS) != 0;
427 }
428
429
430 /*
431  * These are obsolete versions of Get/SetUserIdAndSecContext that are
432  * only provided for bug-compatibility with some rather dubious code in
433  * pljava.  We allow the userid to be set, but only when not inside a
434  * security restriction context.
435  */
436 void
437 GetUserIdAndContext(Oid *userid, bool *sec_def_context)
438 {
439         *userid = CurrentUserId;
440         *sec_def_context = InLocalUserIdChange();
441 }
442
443 void
444 SetUserIdAndContext(Oid userid, bool sec_def_context)
445 {
446         /* We throw the same error SET ROLE would. */
447         if (InSecurityRestrictedOperation())
448                 ereport(ERROR,
449                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
450                                  errmsg("cannot set parameter \"%s\" within security-restricted operation",
451                                                 "role")));
452         CurrentUserId = userid;
453         if (sec_def_context)
454                 SecurityRestrictionContext |= SECURITY_LOCAL_USERID_CHANGE;
455         else
456                 SecurityRestrictionContext &= ~SECURITY_LOCAL_USERID_CHANGE;
457 }
458
459
460 /*
461  * Check whether specified role has explicit REPLICATION privilege
462  */
463 bool
464 has_rolreplication(Oid roleid)
465 {
466         bool            result = false;
467         HeapTuple       utup;
468
469         utup = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
470         if (HeapTupleIsValid(utup))
471         {
472                 result = ((Form_pg_authid) GETSTRUCT(utup))->rolreplication;
473                 ReleaseSysCache(utup);
474         }
475         return result;
476 }
477
478 /*
479  * Initialize user identity during normal backend startup
480  */
481 void
482 InitializeSessionUserId(const char *rolename, Oid roleid)
483 {
484         HeapTuple       roleTup;
485         Form_pg_authid rform;
486         char       *rname;
487
488         /*
489          * Don't do scans if we're bootstrapping, none of the system catalogs
490          * exist yet, and they should be owned by postgres anyway.
491          */
492         AssertState(!IsBootstrapProcessingMode());
493
494         /* call only once */
495         AssertState(!OidIsValid(AuthenticatedUserId));
496
497         if (rolename != NULL)
498         {
499                 roleTup = SearchSysCache1(AUTHNAME, PointerGetDatum(rolename));
500                 if (!HeapTupleIsValid(roleTup))
501                         ereport(FATAL,
502                                         (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
503                                          errmsg("role \"%s\" does not exist", rolename)));
504         }
505         else
506         {
507                 roleTup = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
508                 if (!HeapTupleIsValid(roleTup))
509                         ereport(FATAL,
510                                         (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
511                                          errmsg("role with OID %u does not exist", roleid)));
512         }
513
514         rform = (Form_pg_authid) GETSTRUCT(roleTup);
515         roleid = HeapTupleGetOid(roleTup);
516         rname = NameStr(rform->rolname);
517
518         AuthenticatedUserId = roleid;
519         AuthenticatedUserIsSuperuser = rform->rolsuper;
520
521         /* This sets OuterUserId/CurrentUserId too */
522         SetSessionUserId(roleid, AuthenticatedUserIsSuperuser);
523
524         /* Also mark our PGPROC entry with the authenticated user id */
525         /* (We assume this is an atomic store so no lock is needed) */
526         MyProc->roleId = roleid;
527
528         /*
529          * These next checks are not enforced when in standalone mode, so that
530          * there is a way to recover from sillinesses like "UPDATE pg_authid SET
531          * rolcanlogin = false;".
532          */
533         if (IsUnderPostmaster)
534         {
535                 /*
536                  * Is role allowed to login at all?
537                  */
538                 if (!rform->rolcanlogin)
539                         ereport(FATAL,
540                                         (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
541                                          errmsg("role \"%s\" is not permitted to log in",
542                                                         rname)));
543
544                 /*
545                  * Check connection limit for this role.
546                  *
547                  * There is a race condition here --- we create our PGPROC before
548                  * checking for other PGPROCs.  If two backends did this at about the
549                  * same time, they might both think they were over the limit, while
550                  * ideally one should succeed and one fail.  Getting that to work
551                  * exactly seems more trouble than it is worth, however; instead we
552                  * just document that the connection limit is approximate.
553                  */
554                 if (rform->rolconnlimit >= 0 &&
555                         !AuthenticatedUserIsSuperuser &&
556                         CountUserBackends(roleid) > rform->rolconnlimit)
557                         ereport(FATAL,
558                                         (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
559                                          errmsg("too many connections for role \"%s\"",
560                                                         rname)));
561         }
562
563         /* Record username and superuser status as GUC settings too */
564         SetConfigOption("session_authorization", rname,
565                                         PGC_BACKEND, PGC_S_OVERRIDE);
566         SetConfigOption("is_superuser",
567                                         AuthenticatedUserIsSuperuser ? "on" : "off",
568                                         PGC_INTERNAL, PGC_S_OVERRIDE);
569
570         ReleaseSysCache(roleTup);
571 }
572
573
574 /*
575  * Initialize user identity during special backend startup
576  */
577 void
578 InitializeSessionUserIdStandalone(void)
579 {
580         /*
581          * This function should only be called in single-user mode, in autovacuum
582          * workers, and in background workers.
583          */
584         AssertState(!IsUnderPostmaster || IsAutoVacuumWorkerProcess() || IsBackgroundWorker);
585
586         /* call only once */
587         AssertState(!OidIsValid(AuthenticatedUserId));
588
589         AuthenticatedUserId = BOOTSTRAP_SUPERUSERID;
590         AuthenticatedUserIsSuperuser = true;
591
592         SetSessionUserId(BOOTSTRAP_SUPERUSERID, true);
593 }
594
595
596 /*
597  * Change session auth ID while running
598  *
599  * Only a superuser may set auth ID to something other than himself.  Note
600  * that in case of multiple SETs in a single session, the original userid's
601  * superuserness is what matters.  But we set the GUC variable is_superuser
602  * to indicate whether the *current* session userid is a superuser.
603  *
604  * Note: this is not an especially clean place to do the permission check.
605  * It's OK because the check does not require catalog access and can't
606  * fail during an end-of-transaction GUC reversion, but we may someday
607  * have to push it up into assign_session_authorization.
608  */
609 void
610 SetSessionAuthorization(Oid userid, bool is_superuser)
611 {
612         /* Must have authenticated already, else can't make permission check */
613         AssertState(OidIsValid(AuthenticatedUserId));
614
615         if (userid != AuthenticatedUserId &&
616                 !AuthenticatedUserIsSuperuser)
617                 ereport(ERROR,
618                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
619                                  errmsg("permission denied to set session authorization")));
620
621         SetSessionUserId(userid, is_superuser);
622
623         SetConfigOption("is_superuser",
624                                         is_superuser ? "on" : "off",
625                                         PGC_INTERNAL, PGC_S_OVERRIDE);
626 }
627
628 /*
629  * Report current role id
630  *              This follows the semantics of SET ROLE, ie return the outer-level ID
631  *              not the current effective ID, and return InvalidOid when the setting
632  *              is logically SET ROLE NONE.
633  */
634 Oid
635 GetCurrentRoleId(void)
636 {
637         if (SetRoleIsActive)
638                 return OuterUserId;
639         else
640                 return InvalidOid;
641 }
642
643 /*
644  * Change Role ID while running (SET ROLE)
645  *
646  * If roleid is InvalidOid, we are doing SET ROLE NONE: revert to the
647  * session user authorization.  In this case the is_superuser argument
648  * is ignored.
649  *
650  * When roleid is not InvalidOid, the caller must have checked whether
651  * the session user has permission to become that role.  (We cannot check
652  * here because this routine must be able to execute in a failed transaction
653  * to restore a prior value of the ROLE GUC variable.)
654  */
655 void
656 SetCurrentRoleId(Oid roleid, bool is_superuser)
657 {
658         /*
659          * Get correct info if it's SET ROLE NONE
660          *
661          * If SessionUserId hasn't been set yet, just do nothing --- the eventual
662          * SetSessionUserId call will fix everything.  This is needed since we
663          * will get called during GUC initialization.
664          */
665         if (!OidIsValid(roleid))
666         {
667                 if (!OidIsValid(SessionUserId))
668                         return;
669
670                 roleid = SessionUserId;
671                 is_superuser = SessionUserIsSuperuser;
672
673                 SetRoleIsActive = false;
674         }
675         else
676                 SetRoleIsActive = true;
677
678         SetOuterUserId(roleid);
679
680         SetConfigOption("is_superuser",
681                                         is_superuser ? "on" : "off",
682                                         PGC_INTERNAL, PGC_S_OVERRIDE);
683 }
684
685
686 /*
687  * Get user name from user oid, returns NULL for nonexistent roleid if noerr
688  * is true.
689  */
690 char *
691 GetUserNameFromId(Oid roleid, bool noerr)
692 {
693         HeapTuple       tuple;
694         char       *result;
695
696         tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
697         if (!HeapTupleIsValid(tuple))
698         {
699                 if (!noerr)
700                         ereport(ERROR,
701                                         (errcode(ERRCODE_UNDEFINED_OBJECT),
702                                          errmsg("invalid role OID: %u", roleid)));
703                 result = NULL;
704         }
705         else
706         {
707                 result = pstrdup(NameStr(((Form_pg_authid) GETSTRUCT(tuple))->rolname));
708                 ReleaseSysCache(tuple);
709         }
710         return result;
711 }
712
713
714 /*-------------------------------------------------------------------------
715  *                              Interlock-file support
716  *
717  * These routines are used to create both a data-directory lockfile
718  * ($DATADIR/postmaster.pid) and Unix-socket-file lockfiles ($SOCKFILE.lock).
719  * Both kinds of files contain the same info initially, although we can add
720  * more information to a data-directory lockfile after it's created, using
721  * AddToDataDirLockFile().  See miscadmin.h for documentation of the contents
722  * of these lockfiles.
723  *
724  * On successful lockfile creation, a proc_exit callback to remove the
725  * lockfile is automatically created.
726  *-------------------------------------------------------------------------
727  */
728
729 /*
730  * proc_exit callback to remove lockfiles.
731  */
732 static void
733 UnlinkLockFiles(int status, Datum arg)
734 {
735         ListCell   *l;
736
737         foreach(l, lock_files)
738         {
739                 char       *curfile = (char *) lfirst(l);
740
741                 unlink(curfile);
742                 /* Should we complain if the unlink fails? */
743         }
744         /* Since we're about to exit, no need to reclaim storage */
745         lock_files = NIL;
746
747         /*
748          * Lock file removal should always be the last externally visible action
749          * of a postmaster or standalone backend, while we won't come here at all
750          * when exiting postmaster child processes.  Therefore, this is a good
751          * place to log completion of shutdown.  We could alternatively teach
752          * proc_exit() to do it, but that seems uglier.  In a standalone backend,
753          * use NOTICE elevel to be less chatty.
754          */
755         ereport(IsPostmasterEnvironment ? LOG : NOTICE,
756                         (errmsg("database system is shut down")));
757 }
758
759 /*
760  * Create a lockfile.
761  *
762  * filename is the path name of the lockfile to create.
763  * amPostmaster is used to determine how to encode the output PID.
764  * socketDir is the Unix socket directory path to include (possibly empty).
765  * isDDLock and refName are used to determine what error message to produce.
766  */
767 static void
768 CreateLockFile(const char *filename, bool amPostmaster,
769                            const char *socketDir,
770                            bool isDDLock, const char *refName)
771 {
772         int                     fd;
773         char            buffer[MAXPGPATH * 2 + 256];
774         int                     ntries;
775         int                     len;
776         int                     encoded_pid;
777         pid_t           other_pid;
778         pid_t           my_pid,
779                                 my_p_pid,
780                                 my_gp_pid;
781         const char *envvar;
782
783         /*
784          * If the PID in the lockfile is our own PID or our parent's or
785          * grandparent's PID, then the file must be stale (probably left over from
786          * a previous system boot cycle).  We need to check this because of the
787          * likelihood that a reboot will assign exactly the same PID as we had in
788          * the previous reboot, or one that's only one or two counts larger and
789          * hence the lockfile's PID now refers to an ancestor shell process.  We
790          * allow pg_ctl to pass down its parent shell PID (our grandparent PID)
791          * via the environment variable PG_GRANDPARENT_PID; this is so that
792          * launching the postmaster via pg_ctl can be just as reliable as
793          * launching it directly.  There is no provision for detecting
794          * further-removed ancestor processes, but if the init script is written
795          * carefully then all but the immediate parent shell will be root-owned
796          * processes and so the kill test will fail with EPERM.  Note that we
797          * cannot get a false negative this way, because an existing postmaster
798          * would surely never launch a competing postmaster or pg_ctl process
799          * directly.
800          */
801         my_pid = getpid();
802
803 #ifndef WIN32
804         my_p_pid = getppid();
805 #else
806
807         /*
808          * Windows hasn't got getppid(), but doesn't need it since it's not using
809          * real kill() either...
810          */
811         my_p_pid = 0;
812 #endif
813
814         envvar = getenv("PG_GRANDPARENT_PID");
815         if (envvar)
816                 my_gp_pid = atoi(envvar);
817         else
818                 my_gp_pid = 0;
819
820         /*
821          * We need a loop here because of race conditions.  But don't loop forever
822          * (for example, a non-writable $PGDATA directory might cause a failure
823          * that won't go away).  100 tries seems like plenty.
824          */
825         for (ntries = 0;; ntries++)
826         {
827                 /*
828                  * Try to create the lock file --- O_EXCL makes this atomic.
829                  *
830                  * Think not to make the file protection weaker than 0600.  See
831                  * comments below.
832                  */
833                 fd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
834                 if (fd >= 0)
835                         break;                          /* Success; exit the retry loop */
836
837                 /*
838                  * Couldn't create the pid file. Probably it already exists.
839                  */
840                 if ((errno != EEXIST && errno != EACCES) || ntries > 100)
841                         ereport(FATAL,
842                                         (errcode_for_file_access(),
843                                          errmsg("could not create lock file \"%s\": %m",
844                                                         filename)));
845
846                 /*
847                  * Read the file to get the old owner's PID.  Note race condition
848                  * here: file might have been deleted since we tried to create it.
849                  */
850                 fd = open(filename, O_RDONLY, 0600);
851                 if (fd < 0)
852                 {
853                         if (errno == ENOENT)
854                                 continue;               /* race condition; try again */
855                         ereport(FATAL,
856                                         (errcode_for_file_access(),
857                                          errmsg("could not open lock file \"%s\": %m",
858                                                         filename)));
859                 }
860                 if ((len = read(fd, buffer, sizeof(buffer) - 1)) < 0)
861                         ereport(FATAL,
862                                         (errcode_for_file_access(),
863                                          errmsg("could not read lock file \"%s\": %m",
864                                                         filename)));
865                 close(fd);
866
867                 if (len == 0)
868                 {
869                         ereport(FATAL,
870                                         (errcode(ERRCODE_LOCK_FILE_EXISTS),
871                                          errmsg("lock file \"%s\" is empty", filename),
872                                          errhint("Either another server is starting, or the lock file is the remnant of a previous server startup crash.")));
873                 }
874
875                 buffer[len] = '\0';
876                 encoded_pid = atoi(buffer);
877
878                 /* if pid < 0, the pid is for postgres, not postmaster */
879                 other_pid = (pid_t) (encoded_pid < 0 ? -encoded_pid : encoded_pid);
880
881                 if (other_pid <= 0)
882                         elog(FATAL, "bogus data in lock file \"%s\": \"%s\"",
883                                  filename, buffer);
884
885                 /*
886                  * Check to see if the other process still exists
887                  *
888                  * Per discussion above, my_pid, my_p_pid, and my_gp_pid can be
889                  * ignored as false matches.
890                  *
891                  * Normally kill() will fail with ESRCH if the given PID doesn't
892                  * exist.
893                  *
894                  * We can treat the EPERM-error case as okay because that error
895                  * implies that the existing process has a different userid than we
896                  * do, which means it cannot be a competing postmaster.  A postmaster
897                  * cannot successfully attach to a data directory owned by a userid
898                  * other than its own.  (This is now checked directly in
899                  * checkDataDir(), but has been true for a long time because of the
900                  * restriction that the data directory isn't group- or
901                  * world-accessible.)  Also, since we create the lockfiles mode 600,
902                  * we'd have failed above if the lockfile belonged to another userid
903                  * --- which means that whatever process kill() is reporting about
904                  * isn't the one that made the lockfile.  (NOTE: this last
905                  * consideration is the only one that keeps us from blowing away a
906                  * Unix socket file belonging to an instance of Postgres being run by
907                  * someone else, at least on machines where /tmp hasn't got a
908                  * stickybit.)
909                  */
910                 if (other_pid != my_pid && other_pid != my_p_pid &&
911                         other_pid != my_gp_pid)
912                 {
913                         if (kill(other_pid, 0) == 0 ||
914                                 (errno != ESRCH && errno != EPERM))
915                         {
916                                 /* lockfile belongs to a live process */
917                                 ereport(FATAL,
918                                                 (errcode(ERRCODE_LOCK_FILE_EXISTS),
919                                                  errmsg("lock file \"%s\" already exists",
920                                                                 filename),
921                                                  isDDLock ?
922                                                  (encoded_pid < 0 ?
923                                                   errhint("Is another postgres (PID %d) running in data directory \"%s\"?",
924                                                                   (int) other_pid, refName) :
925                                                   errhint("Is another postmaster (PID %d) running in data directory \"%s\"?",
926                                                                   (int) other_pid, refName)) :
927                                                  (encoded_pid < 0 ?
928                                                   errhint("Is another postgres (PID %d) using socket file \"%s\"?",
929                                                                   (int) other_pid, refName) :
930                                                   errhint("Is another postmaster (PID %d) using socket file \"%s\"?",
931                                                                   (int) other_pid, refName))));
932                         }
933                 }
934
935                 /*
936                  * No, the creating process did not exist.  However, it could be that
937                  * the postmaster crashed (or more likely was kill -9'd by a clueless
938                  * admin) but has left orphan backends behind.  Check for this by
939                  * looking to see if there is an associated shmem segment that is
940                  * still in use.
941                  *
942                  * Note: because postmaster.pid is written in multiple steps, we might
943                  * not find the shmem ID values in it; we can't treat that as an
944                  * error.
945                  */
946                 if (isDDLock)
947                 {
948                         char       *ptr = buffer;
949                         unsigned long id1,
950                                                 id2;
951                         int                     lineno;
952
953                         for (lineno = 1; lineno < LOCK_FILE_LINE_SHMEM_KEY; lineno++)
954                         {
955                                 if ((ptr = strchr(ptr, '\n')) == NULL)
956                                         break;
957                                 ptr++;
958                         }
959
960                         if (ptr != NULL &&
961                                 sscanf(ptr, "%lu %lu", &id1, &id2) == 2)
962                         {
963                                 if (PGSharedMemoryIsInUse(id1, id2))
964                                         ereport(FATAL,
965                                                         (errcode(ERRCODE_LOCK_FILE_EXISTS),
966                                                          errmsg("pre-existing shared memory block "
967                                                                         "(key %lu, ID %lu) is still in use",
968                                                                         id1, id2),
969                                                          errhint("If you're sure there are no old "
970                                                                          "server processes still running, remove "
971                                                                          "the shared memory block "
972                                                                          "or just delete the file \"%s\".",
973                                                                          filename)));
974                         }
975                 }
976
977                 /*
978                  * Looks like nobody's home.  Unlink the file and try again to create
979                  * it.  Need a loop because of possible race condition against other
980                  * would-be creators.
981                  */
982                 if (unlink(filename) < 0)
983                         ereport(FATAL,
984                                         (errcode_for_file_access(),
985                                          errmsg("could not remove old lock file \"%s\": %m",
986                                                         filename),
987                                          errhint("The file seems accidentally left over, but "
988                                                    "it could not be removed. Please remove the file "
989                                                          "by hand and try again.")));
990         }
991
992         /*
993          * Successfully created the file, now fill it.  See comment in miscadmin.h
994          * about the contents.  Note that we write the same first five lines into
995          * both datadir and socket lockfiles; although more stuff may get added to
996          * the datadir lockfile later.
997          */
998         snprintf(buffer, sizeof(buffer), "%d\n%s\n%ld\n%d\n%s\n",
999                          amPostmaster ? (int) my_pid : -((int) my_pid),
1000                          DataDir,
1001                          (long) MyStartTime,
1002                          PostPortNumber,
1003                          socketDir);
1004
1005         /*
1006          * In a standalone backend, the next line (LOCK_FILE_LINE_LISTEN_ADDR)
1007          * will never receive data, so fill it in as empty now.
1008          */
1009         if (isDDLock && !amPostmaster)
1010                 strlcat(buffer, "\n", sizeof(buffer));
1011
1012         errno = 0;
1013         if (write(fd, buffer, strlen(buffer)) != strlen(buffer))
1014         {
1015                 int                     save_errno = errno;
1016
1017                 close(fd);
1018                 unlink(filename);
1019                 /* if write didn't set errno, assume problem is no disk space */
1020                 errno = save_errno ? save_errno : ENOSPC;
1021                 ereport(FATAL,
1022                                 (errcode_for_file_access(),
1023                                  errmsg("could not write lock file \"%s\": %m", filename)));
1024         }
1025         if (pg_fsync(fd) != 0)
1026         {
1027                 int                     save_errno = errno;
1028
1029                 close(fd);
1030                 unlink(filename);
1031                 errno = save_errno;
1032                 ereport(FATAL,
1033                                 (errcode_for_file_access(),
1034                                  errmsg("could not write lock file \"%s\": %m", filename)));
1035         }
1036         if (close(fd) != 0)
1037         {
1038                 int                     save_errno = errno;
1039
1040                 unlink(filename);
1041                 errno = save_errno;
1042                 ereport(FATAL,
1043                                 (errcode_for_file_access(),
1044                                  errmsg("could not write lock file \"%s\": %m", filename)));
1045         }
1046
1047         /*
1048          * Arrange to unlink the lock file(s) at proc_exit.  If this is the first
1049          * one, set up the on_proc_exit function to do it; then add this lock file
1050          * to the list of files to unlink.
1051          */
1052         if (lock_files == NIL)
1053                 on_proc_exit(UnlinkLockFiles, 0);
1054
1055         /*
1056          * Use lcons so that the lock files are unlinked in reverse order of
1057          * creation; this is critical!
1058          */
1059         lock_files = lcons(pstrdup(filename), lock_files);
1060 }
1061
1062 /*
1063  * Create the data directory lockfile.
1064  *
1065  * When this is called, we must have already switched the working
1066  * directory to DataDir, so we can just use a relative path.  This
1067  * helps ensure that we are locking the directory we should be.
1068  *
1069  * Note that the socket directory path line is initially written as empty.
1070  * postmaster.c will rewrite it upon creating the first Unix socket.
1071  */
1072 void
1073 CreateDataDirLockFile(bool amPostmaster)
1074 {
1075         CreateLockFile(DIRECTORY_LOCK_FILE, amPostmaster, "", true, DataDir);
1076 }
1077
1078 /*
1079  * Create a lockfile for the specified Unix socket file.
1080  */
1081 void
1082 CreateSocketLockFile(const char *socketfile, bool amPostmaster,
1083                                          const char *socketDir)
1084 {
1085         char            lockfile[MAXPGPATH];
1086
1087         snprintf(lockfile, sizeof(lockfile), "%s.lock", socketfile);
1088         CreateLockFile(lockfile, amPostmaster, socketDir, false, socketfile);
1089 }
1090
1091 /*
1092  * TouchSocketLockFiles -- mark socket lock files as recently accessed
1093  *
1094  * This routine should be called every so often to ensure that the socket
1095  * lock files have a recent mod or access date.  That saves them
1096  * from being removed by overenthusiastic /tmp-directory-cleaner daemons.
1097  * (Another reason we should never have put the socket file in /tmp...)
1098  */
1099 void
1100 TouchSocketLockFiles(void)
1101 {
1102         ListCell   *l;
1103
1104         foreach(l, lock_files)
1105         {
1106                 char       *socketLockFile = (char *) lfirst(l);
1107
1108                 /* No need to touch the data directory lock file, we trust */
1109                 if (strcmp(socketLockFile, DIRECTORY_LOCK_FILE) == 0)
1110                         continue;
1111
1112                 /*
1113                  * utime() is POSIX standard, utimes() is a common alternative; if we
1114                  * have neither, fall back to actually reading the file (which only
1115                  * sets the access time not mod time, but that should be enough in
1116                  * most cases).  In all paths, we ignore errors.
1117                  */
1118 #ifdef HAVE_UTIME
1119                 utime(socketLockFile, NULL);
1120 #else                                                   /* !HAVE_UTIME */
1121 #ifdef HAVE_UTIMES
1122                 utimes(socketLockFile, NULL);
1123 #else                                                   /* !HAVE_UTIMES */
1124                 int                     fd;
1125                 char            buffer[1];
1126
1127                 fd = open(socketLockFile, O_RDONLY | PG_BINARY, 0);
1128                 if (fd >= 0)
1129                 {
1130                         read(fd, buffer, sizeof(buffer));
1131                         close(fd);
1132                 }
1133 #endif   /* HAVE_UTIMES */
1134 #endif   /* HAVE_UTIME */
1135         }
1136 }
1137
1138
1139 /*
1140  * Add (or replace) a line in the data directory lock file.
1141  * The given string should not include a trailing newline.
1142  *
1143  * Note: because we don't truncate the file, if we were to rewrite a line
1144  * with less data than it had before, there would be garbage after the last
1145  * line.  We don't ever actually do that, so not worth adding another kernel
1146  * call to cover the possibility.
1147  */
1148 void
1149 AddToDataDirLockFile(int target_line, const char *str)
1150 {
1151         int                     fd;
1152         int                     len;
1153         int                     lineno;
1154         char       *srcptr;
1155         char       *destptr;
1156         char            srcbuffer[BLCKSZ];
1157         char            destbuffer[BLCKSZ];
1158
1159         fd = open(DIRECTORY_LOCK_FILE, O_RDWR | PG_BINARY, 0);
1160         if (fd < 0)
1161         {
1162                 ereport(LOG,
1163                                 (errcode_for_file_access(),
1164                                  errmsg("could not open file \"%s\": %m",
1165                                                 DIRECTORY_LOCK_FILE)));
1166                 return;
1167         }
1168         len = read(fd, srcbuffer, sizeof(srcbuffer) - 1);
1169         if (len < 0)
1170         {
1171                 ereport(LOG,
1172                                 (errcode_for_file_access(),
1173                                  errmsg("could not read from file \"%s\": %m",
1174                                                 DIRECTORY_LOCK_FILE)));
1175                 close(fd);
1176                 return;
1177         }
1178         srcbuffer[len] = '\0';
1179
1180         /*
1181          * Advance over lines we are not supposed to rewrite, then copy them to
1182          * destbuffer.
1183          */
1184         srcptr = srcbuffer;
1185         for (lineno = 1; lineno < target_line; lineno++)
1186         {
1187                 if ((srcptr = strchr(srcptr, '\n')) == NULL)
1188                 {
1189                         elog(LOG, "incomplete data in \"%s\": found only %d newlines while trying to add line %d",
1190                                  DIRECTORY_LOCK_FILE, lineno - 1, target_line);
1191                         close(fd);
1192                         return;
1193                 }
1194                 srcptr++;
1195         }
1196         memcpy(destbuffer, srcbuffer, srcptr - srcbuffer);
1197         destptr = destbuffer + (srcptr - srcbuffer);
1198
1199         /*
1200          * Write or rewrite the target line.
1201          */
1202         snprintf(destptr, destbuffer + sizeof(destbuffer) - destptr, "%s\n", str);
1203         destptr += strlen(destptr);
1204
1205         /*
1206          * If there are more lines in the old file, append them to destbuffer.
1207          */
1208         if ((srcptr = strchr(srcptr, '\n')) != NULL)
1209         {
1210                 srcptr++;
1211                 snprintf(destptr, destbuffer + sizeof(destbuffer) - destptr, "%s",
1212                                  srcptr);
1213         }
1214
1215         /*
1216          * And rewrite the data.  Since we write in a single kernel call, this
1217          * update should appear atomic to onlookers.
1218          */
1219         len = strlen(destbuffer);
1220         errno = 0;
1221         if (lseek(fd, (off_t) 0, SEEK_SET) != 0 ||
1222                 (int) write(fd, destbuffer, len) != len)
1223         {
1224                 /* if write didn't set errno, assume problem is no disk space */
1225                 if (errno == 0)
1226                         errno = ENOSPC;
1227                 ereport(LOG,
1228                                 (errcode_for_file_access(),
1229                                  errmsg("could not write to file \"%s\": %m",
1230                                                 DIRECTORY_LOCK_FILE)));
1231                 close(fd);
1232                 return;
1233         }
1234         if (pg_fsync(fd) != 0)
1235         {
1236                 ereport(LOG,
1237                                 (errcode_for_file_access(),
1238                                  errmsg("could not write to file \"%s\": %m",
1239                                                 DIRECTORY_LOCK_FILE)));
1240         }
1241         if (close(fd) != 0)
1242         {
1243                 ereport(LOG,
1244                                 (errcode_for_file_access(),
1245                                  errmsg("could not write to file \"%s\": %m",
1246                                                 DIRECTORY_LOCK_FILE)));
1247         }
1248 }
1249
1250
1251 /*
1252  * Recheck that the data directory lock file still exists with expected
1253  * content.  Return TRUE if the lock file appears OK, FALSE if it isn't.
1254  *
1255  * We call this periodically in the postmaster.  The idea is that if the
1256  * lock file has been removed or replaced by another postmaster, we should
1257  * do a panic database shutdown.  Therefore, we should return TRUE if there
1258  * is any doubt: we do not want to cause a panic shutdown unnecessarily.
1259  * Transient failures like EINTR or ENFILE should not cause us to fail.
1260  * (If there really is something wrong, we'll detect it on a future recheck.)
1261  */
1262 bool
1263 RecheckDataDirLockFile(void)
1264 {
1265         int                     fd;
1266         int                     len;
1267         long            file_pid;
1268         char            buffer[BLCKSZ];
1269
1270         fd = open(DIRECTORY_LOCK_FILE, O_RDWR | PG_BINARY, 0);
1271         if (fd < 0)
1272         {
1273                 /*
1274                  * There are many foreseeable false-positive error conditions.  For
1275                  * safety, fail only on enumerated clearly-something-is-wrong
1276                  * conditions.
1277                  */
1278                 switch (errno)
1279                 {
1280                         case ENOENT:
1281                         case ENOTDIR:
1282                                 /* disaster */
1283                                 ereport(LOG,
1284                                                 (errcode_for_file_access(),
1285                                                  errmsg("could not open file \"%s\": %m",
1286                                                                 DIRECTORY_LOCK_FILE)));
1287                                 return false;
1288                         default:
1289                                 /* non-fatal, at least for now */
1290                                 ereport(LOG,
1291                                                 (errcode_for_file_access(),
1292                                   errmsg("could not open file \"%s\": %m; continuing anyway",
1293                                                  DIRECTORY_LOCK_FILE)));
1294                                 return true;
1295                 }
1296         }
1297         len = read(fd, buffer, sizeof(buffer) - 1);
1298         if (len < 0)
1299         {
1300                 ereport(LOG,
1301                                 (errcode_for_file_access(),
1302                                  errmsg("could not read from file \"%s\": %m",
1303                                                 DIRECTORY_LOCK_FILE)));
1304                 close(fd);
1305                 return true;                    /* treat read failure as nonfatal */
1306         }
1307         buffer[len] = '\0';
1308         close(fd);
1309         file_pid = atol(buffer);
1310         if (file_pid == getpid())
1311                 return true;                    /* all is well */
1312
1313         /* Trouble: someone's overwritten the lock file */
1314         ereport(LOG,
1315                         (errmsg("lock file \"%s\" contains wrong PID: %ld instead of %ld",
1316                                         DIRECTORY_LOCK_FILE, file_pid, (long) getpid())));
1317         return false;
1318 }
1319
1320
1321 /*-------------------------------------------------------------------------
1322  *                              Version checking support
1323  *-------------------------------------------------------------------------
1324  */
1325
1326 /*
1327  * Determine whether the PG_VERSION file in directory `path' indicates
1328  * a data version compatible with the version of this program.
1329  *
1330  * If compatible, return. Otherwise, ereport(FATAL).
1331  */
1332 void
1333 ValidatePgVersion(const char *path)
1334 {
1335         char            full_path[MAXPGPATH];
1336         FILE       *file;
1337         int                     ret;
1338         long            file_major;
1339         long            my_major;
1340         char       *endptr;
1341         char            file_version_string[64];
1342         const char *my_version_string = PG_VERSION;
1343
1344         my_major = strtol(my_version_string, &endptr, 10);
1345
1346         snprintf(full_path, sizeof(full_path), "%s/PG_VERSION", path);
1347
1348         file = AllocateFile(full_path, "r");
1349         if (!file)
1350         {
1351                 if (errno == ENOENT)
1352                         ereport(FATAL,
1353                                         (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1354                                          errmsg("\"%s\" is not a valid data directory",
1355                                                         path),
1356                                          errdetail("File \"%s\" is missing.", full_path)));
1357                 else
1358                         ereport(FATAL,
1359                                         (errcode_for_file_access(),
1360                                          errmsg("could not open file \"%s\": %m", full_path)));
1361         }
1362
1363         file_version_string[0] = '\0';
1364         ret = fscanf(file, "%63s", file_version_string);
1365         file_major = strtol(file_version_string, &endptr, 10);
1366
1367         if (ret != 1 || endptr == file_version_string)
1368                 ereport(FATAL,
1369                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1370                                  errmsg("\"%s\" is not a valid data directory",
1371                                                 path),
1372                                  errdetail("File \"%s\" does not contain valid data.",
1373                                                    full_path),
1374                                  errhint("You might need to initdb.")));
1375
1376         FreeFile(file);
1377
1378         if (my_major != file_major)
1379                 ereport(FATAL,
1380                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1381                                  errmsg("database files are incompatible with server"),
1382                                  errdetail("The data directory was initialized by PostgreSQL version %s, "
1383                                                    "which is not compatible with this version %s.",
1384                                                    file_version_string, my_version_string)));
1385 }
1386
1387 /*-------------------------------------------------------------------------
1388  *                              Library preload support
1389  *-------------------------------------------------------------------------
1390  */
1391
1392 /*
1393  * GUC variables: lists of library names to be preloaded at postmaster
1394  * start and at backend start
1395  */
1396 char       *session_preload_libraries_string = NULL;
1397 char       *shared_preload_libraries_string = NULL;
1398 char       *local_preload_libraries_string = NULL;
1399
1400 /* Flag telling that we are loading shared_preload_libraries */
1401 bool            process_shared_preload_libraries_in_progress = false;
1402
1403 /*
1404  * load the shared libraries listed in 'libraries'
1405  *
1406  * 'gucname': name of GUC variable, for error reports
1407  * 'restricted': if true, force libraries to be in $libdir/plugins/
1408  */
1409 static void
1410 load_libraries(const char *libraries, const char *gucname, bool restricted)
1411 {
1412         char       *rawstring;
1413         List       *elemlist;
1414         ListCell   *l;
1415
1416         if (libraries == NULL || libraries[0] == '\0')
1417                 return;                                 /* nothing to do */
1418
1419         /* Need a modifiable copy of string */
1420         rawstring = pstrdup(libraries);
1421
1422         /* Parse string into list of identifiers */
1423         if (!SplitIdentifierString(rawstring, ',', &elemlist))
1424         {
1425                 /* syntax error in list */
1426                 pfree(rawstring);
1427                 list_free(elemlist);
1428                 ereport(LOG,
1429                                 (errcode(ERRCODE_SYNTAX_ERROR),
1430                                  errmsg("invalid list syntax in parameter \"%s\"",
1431                                                 gucname)));
1432                 return;
1433         }
1434
1435         foreach(l, elemlist)
1436         {
1437                 char       *tok = (char *) lfirst(l);
1438                 char       *filename;
1439
1440                 filename = pstrdup(tok);
1441                 canonicalize_path(filename);
1442                 /* If restricting, insert $libdir/plugins if not mentioned already */
1443                 if (restricted && first_dir_separator(filename) == NULL)
1444                 {
1445                         char       *expanded;
1446
1447                         expanded = psprintf("$libdir/plugins/%s", filename);
1448                         pfree(filename);
1449                         filename = expanded;
1450                 }
1451                 load_file(filename, restricted);
1452                 ereport(DEBUG1,
1453                                 (errmsg("loaded library \"%s\"", filename)));
1454                 pfree(filename);
1455         }
1456
1457         pfree(rawstring);
1458         list_free(elemlist);
1459 }
1460
1461 /*
1462  * process any libraries that should be preloaded at postmaster start
1463  */
1464 void
1465 process_shared_preload_libraries(void)
1466 {
1467         process_shared_preload_libraries_in_progress = true;
1468         load_libraries(shared_preload_libraries_string,
1469                                    "shared_preload_libraries",
1470                                    false);
1471         process_shared_preload_libraries_in_progress = false;
1472 }
1473
1474 /*
1475  * process any libraries that should be preloaded at backend start
1476  */
1477 void
1478 process_session_preload_libraries(void)
1479 {
1480         load_libraries(session_preload_libraries_string,
1481                                    "session_preload_libraries",
1482                                    false);
1483         load_libraries(local_preload_libraries_string,
1484                                    "local_preload_libraries",
1485                                    true);
1486 }
1487
1488 void
1489 pg_bindtextdomain(const char *domain)
1490 {
1491 #ifdef ENABLE_NLS
1492         if (my_exec_path[0] != '\0')
1493         {
1494                 char            locale_path[MAXPGPATH];
1495
1496                 get_locale_path(my_exec_path, locale_path);
1497                 bindtextdomain(domain, locale_path);
1498                 pg_bind_textdomain_codeset(domain);
1499         }
1500 #endif
1501 }