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