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