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