OSDN Git Service

pgindent run.
[pg-rex/syncrep.git] / src / backend / utils / misc / database.c
1 /*-------------------------------------------------------------------------
2  *
3  * database.c
4  *        miscellaneous initialization support stuff
5  *
6  * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *        $Header: /cvsroot/pgsql/src/backend/utils/misc/Attic/database.c,v 1.53 2002/09/04 20:31:32 momjian Exp $
12  *
13  *-------------------------------------------------------------------------
14  */
15 #include "postgres.h"
16
17 #include <fcntl.h>
18 #include <stdlib.h>
19 #include <string.h>
20 #include <unistd.h>
21
22 #include "access/xact.h"
23 #include "catalog/catname.h"
24 #include "catalog/catalog.h"
25 #include "catalog/pg_database.h"
26 #include "miscadmin.h"
27 #include "utils/syscache.h"
28
29
30 static bool PhonyHeapTupleSatisfiesNow(HeapTupleHeader tuple);
31
32
33 /*
34  * ExpandDatabasePath resolves a proposed database path (obtained from
35  * pg_database.datpath) to a full absolute path for further consumption.
36  * NULL means an error, which the caller should process. One reason for
37  * such an error would be an absolute alternative path when no absolute
38  * paths are alllowed.
39  */
40
41 char *
42 ExpandDatabasePath(const char *dbpath)
43 {
44         char            buf[MAXPGPATH];
45         const char *cp;
46         int                     len;
47
48         AssertArg(dbpath);
49         Assert(DataDir);
50
51         if (strlen(dbpath) >= MAXPGPATH)
52                 return NULL;                    /* ain't gonna fit nohow */
53
54         /* leading path delimiter? then already absolute path */
55         if (*dbpath == '/')
56         {
57 #ifdef ALLOW_ABSOLUTE_DBPATHS
58                 cp = strrchr(dbpath, '/');
59                 len = cp - dbpath;
60                 strncpy(buf, dbpath, len);
61                 snprintf(&buf[len], MAXPGPATH - len, "/base/%s", (cp + 1));
62 #else
63                 return NULL;
64 #endif
65         }
66         /* path delimiter somewhere? then has leading environment variable */
67         else if ((cp = strchr(dbpath, '/')) != NULL)
68         {
69                 const char *envvar;
70
71                 len = cp - dbpath;
72                 strncpy(buf, dbpath, len);
73                 buf[len] = '\0';
74                 envvar = getenv(buf);
75                 if (envvar == NULL)
76                         return NULL;
77
78                 snprintf(buf, sizeof(buf), "%s/base/%s", envvar, (cp + 1));
79         }
80         else
81         {
82                 /* no path delimiter? then add the default path prefix */
83                 snprintf(buf, sizeof(buf), "%s/base/%s", DataDir, dbpath);
84         }
85
86         /*
87          * check for illegal characters in dbpath these should really throw an
88          * error, shouldn't they? or else all callers need to test for NULL
89          */
90         for (cp = buf; *cp; cp++)
91         {
92                 /*
93                  * The following characters will not be allowed anywhere in the
94                  * database path. (Do not include the slash  or '.' here.)
95                  */
96                 char            illegal_dbpath_chars[] =
97                 "\001\002\003\004\005\006\007\010"
98                 "\011\012\013\014\015\016\017\020"
99                 "\021\022\023\024\025\026\027\030"
100                 "\031\032\033\034\035\036\037"
101                 "'`";
102
103                 const char *cx;
104
105                 for (cx = illegal_dbpath_chars; *cx; cx++)
106                         if (*cp == *cx)
107                                 return NULL;
108                 /* don't allow access to parent dirs */
109                 if (strncmp(cp, "/../", 4) == 0)
110                         return NULL;
111         }
112
113         return pstrdup(buf);
114 }       /* ExpandDatabasePath() */
115
116
117
118 /* --------------------------------
119  *      GetRawDatabaseInfo() -- Find the OID and path of the database.
120  *
121  *              The database's oid forms half of the unique key for the system
122  *              caches and lock tables.  We therefore want it initialized before
123  *              we open any relations, since opening relations puts things in the
124  *              cache.  To get around this problem, this code opens and scans the
125  *              pg_database relation by hand.
126  *
127  *              This code knows way more than it should about the layout of
128  *              tuples on disk, but there seems to be no help for that.
129  *              We're pulling ourselves up by the bootstraps here...
130  * --------------------------------
131  */
132 void
133 GetRawDatabaseInfo(const char *name, Oid *db_id, char *path)
134 {
135         int                     dbfd;
136         int                     nbytes;
137         int                     pathlen;
138         HeapTupleData tup;
139         Page            pg;
140         char       *dbfname;
141         Form_pg_database tup_db;
142         RelFileNode rnode;
143
144         rnode.tblNode = 0;
145         rnode.relNode = RelOid_pg_database;
146         dbfname = relpath(rnode);
147
148         if ((dbfd = open(dbfname, O_RDONLY | PG_BINARY, 0)) < 0)
149                 elog(FATAL, "cannot open %s: %m", dbfname);
150
151         pfree(dbfname);
152
153         /*
154          * read and examine every page in pg_database
155          *
156          * Raw I/O! Read those tuples the hard way! Yow!
157          *
158          * Why don't we use the access methods or move this code someplace else?
159          * This is really pg_database schema dependent code.  Perhaps it
160          * should go in lib/catalog/pg_database? -cim 10/3/90
161          *
162          * mao replies 4 apr 91:  yeah, maybe this should be moved to
163          * lib/catalog.  however, we CANNOT use the access methods since those
164          * use the buffer cache, which uses the relation cache, which requires
165          * that the dbid be set, which is what we're trying to do here.
166          *
167          */
168         pg = (Page) palloc(BLCKSZ);
169
170         while ((nbytes = read(dbfd, pg, BLCKSZ)) == BLCKSZ)
171         {
172                 OffsetNumber max = PageGetMaxOffsetNumber(pg);
173                 OffsetNumber lineoff;
174
175                 /* look at each tuple on the page */
176                 for (lineoff = FirstOffsetNumber; lineoff <= max; lineoff++)
177                 {
178                         ItemId          lpp = PageGetItemId(pg, lineoff);
179
180                         /* if it's a freed tuple, ignore it */
181                         if (!ItemIdIsUsed(lpp))
182                                 continue;
183
184                         /* get a pointer to the tuple itself */
185                         tup.t_datamcxt = NULL;
186                         tup.t_data = (HeapTupleHeader) PageGetItem(pg, lpp);
187
188                         /*
189                          * Check to see if tuple is valid (committed).
190                          *
191                          * XXX warning, will robinson: violation of transaction semantics
192                          * happens right here.  We cannot really determine if the
193                          * tuple is valid without checking transaction commit status,
194                          * and the only way to do that at init time is to paw over
195                          * pg_clog by hand, too.  Instead of checking, we assume that
196                          * the inserting transaction committed, and that any deleting
197                          * transaction did also, unless shown otherwise by on-row
198                          * commit status bits.
199                          *
200                          * All in all, this code is pretty shaky.  We will cross-check
201                          * our result in ReverifyMyDatabase() in postinit.c.
202                          *
203                          * NOTE: if a bogus tuple in pg_database prevents connection to a
204                          * valid database, a fix is to connect to another database and
205                          * do "select * from pg_database".      That should cause
206                          * committed and dead tuples to be marked with correct states.
207                          *
208                          * XXX wouldn't it be better to let new backends read the
209                          * database OID from a flat file, handled the same way we
210                          * handle the password relation?
211                          */
212                         if (!PhonyHeapTupleSatisfiesNow(tup.t_data))
213                                 continue;
214
215                         /*
216                          * Okay, see if this is the one we want.
217                          */
218                         tup_db = (Form_pg_database) GETSTRUCT(&tup);
219
220                         if (strcmp(name, NameStr(tup_db->datname)) == 0)
221                         {
222                                 /* Found it; extract the OID and the database path. */
223                                 *db_id = HeapTupleGetOid(&tup);
224                                 pathlen = VARSIZE(&(tup_db->datpath)) - VARHDRSZ;
225                                 if (pathlen < 0)
226                                         pathlen = 0;    /* pure paranoia */
227                                 if (pathlen >= MAXPGPATH)
228                                         pathlen = MAXPGPATH - 1;        /* more paranoia */
229                                 strncpy(path, VARDATA(&(tup_db->datpath)), pathlen);
230                                 path[pathlen] = '\0';
231                                 goto done;
232                         }
233                 }
234         }
235
236         /* failed to find it... */
237         *db_id = InvalidOid;
238         *path = '\0';
239
240 done:
241         close(dbfd);
242         pfree(pg);
243 }
244
245 /*
246  * PhonyHeapTupleSatisfiesNow --- cut-down tuple time qual test
247  *
248  * This is a simplified version of HeapTupleSatisfiesNow() that does not
249  * depend on having transaction commit info available.  Any transaction
250  * that touched the tuple is assumed committed unless later marked invalid.
251  * (While we could think about more complex rules, this seems appropriate
252  * for examining pg_database, since both CREATE DATABASE and DROP DATABASE
253  * are non-roll-back-able.)
254  */
255 static bool
256 PhonyHeapTupleSatisfiesNow(HeapTupleHeader tuple)
257 {
258         if (!(tuple->t_infomask & HEAP_XMIN_COMMITTED))
259         {
260                 if (tuple->t_infomask & HEAP_XMIN_INVALID)
261                         return false;
262
263                 if (tuple->t_infomask & HEAP_MOVED_OFF)
264                         return false;
265                 /* else assume committed */
266         }
267
268         if (tuple->t_infomask & HEAP_XMAX_INVALID)      /* xid invalid or aborted */
269                 return true;
270
271         /* assume xmax transaction committed */
272         if (tuple->t_infomask & HEAP_MARKED_FOR_UPDATE)
273                 return true;
274
275         return false;
276 }