fastpath.c 11.4 KB
Newer Older
1 2
/*-------------------------------------------------------------------------
 *
3
 * fastpath.c
4
 *	  routines to handle function requests from the frontend
5
 *
B
Bruce Momjian 已提交
6
 * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group
B
Add:  
Bruce Momjian 已提交
7
 * Portions Copyright (c) 1994, Regents of the University of California
8 9 10
 *
 *
 * IDENTIFICATION
11
 *	  $Header: /cvsroot/pgsql/src/backend/tcop/fastpath.c,v 1.57 2003/01/09 18:00:23 tgl Exp $
12 13
 *
 * NOTES
14
 *	  This cruft is the server side of PQfn.
15
 *
16
 *	  - jolly 07/11/95:
17
 *
18 19 20
 *	  no longer rely on return sizes provided by the frontend.	Always
 *	  use the true lengths for the catalogs.  Assume that the frontend
 *	  has allocated enough space to handle the result value returned.
21
 *
22 23 24 25
 *	  trust that the user knows what he is doing with the args.  If the
 *	  sys catalog says it is a varlena, assume that the user is only sending
 *	  down VARDATA and that the argsize is the VARSIZE.  If the arg is
 *	  fixed len, assume that the argsize given by the user is correct.
26
 *
27 28 29
 *	  if the function returns by value, then only send 4 bytes value
 *	  back to the frontend.  If the return returns by reference,
 *	  send down only the data portion and set the return size appropriately.
30
 *
31
 *	 OLD COMMENTS FOLLOW
32
 *
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
 *	  The VAR_LENGTH_{ARGS,RESULT} stuff is limited to MAX_STRING_LENGTH
 *	  (see src/backend/tmp/fastpath.h) for no obvious reason.  Since its
 *	  primary use (for us) is for Inversion path names, it should probably
 *	  be increased to 256 (MAXPATHLEN for Inversion, hidden in pg_type
 *	  as well as utils/adt/filename.c).
 *
 *	  Quoth PMA on 08/15/93:
 *
 *	  This code has been almost completely rewritten with an eye to
 *	  keeping it as compatible as possible with the previous (broken)
 *	  implementation.
 *
 *	  The previous implementation would assume (1) that any value of
 *	  length <= 4 bytes was passed-by-value, and that any other value
 *	  was a struct varlena (by-reference).	There was NO way to pass a
48
 *	  fixed-length by-reference argument (like name) or a struct
49 50 51 52 53 54 55 56 57
 *	  varlena of size <= 4 bytes.
 *
 *	  The new implementation checks the catalogs to determine whether
 *	  a value is by-value (type "0" is null-delimited character string,
 *	  as it is for, e.g., the parser).	The only other item obtained
 *	  from the catalogs is whether or not the value should be placed in
 *	  a struct varlena or not.	Otherwise, the size given by the
 *	  frontend is assumed to be correct (probably a bad decision, but
 *	  we do strange things in the name of compatibility).
58 59 60 61 62
 *
 *-------------------------------------------------------------------------
 */
#include "postgres.h"

B
Bruce Momjian 已提交
63
#include "access/xact.h"
64
#include "catalog/pg_proc.h"
B
Bruce Momjian 已提交
65 66
#include "libpq/libpq.h"
#include "libpq/pqformat.h"
67
#include "miscadmin.h"
B
Bruce Momjian 已提交
68
#include "tcop/fastpath.h"
69
#include "utils/acl.h"
70
#include "utils/lsyscache.h"
B
Bruce Momjian 已提交
71
#include "utils/syscache.h"
72
#include "utils/tqual.h"
73 74 75


/* ----------------
76
 *		SendFunctionResult
77 78
 *
 * retlen is 0 if returning NULL, else the typlen according to the catalogs
79 80 81
 * ----------------
 */
static void
82
SendFunctionResult(Datum retval, bool retbyval, int retlen)
83
{
84 85 86 87
	StringInfoData buf;

	pq_beginmessage(&buf);
	pq_sendbyte(&buf, 'V');
88 89 90

	if (retlen != 0)
	{
91
		pq_sendbyte(&buf, 'G');
92 93
		if (retbyval)
		{						/* by-value */
94
			pq_sendint(&buf, retlen, 4);
95
			pq_sendint(&buf, DatumGetInt32(retval), retlen);
96 97 98
		}
		else
		{						/* by-reference ... */
99
			if (retlen == -1)
100
			{					/* ... varlena */
101
				struct varlena *v = PG_DETOAST_DATUM(retval);
102 103 104

				pq_sendint(&buf, VARSIZE(v) - VARHDRSZ, VARHDRSZ);
				pq_sendbytes(&buf, VARDATA(v), VARSIZE(v) - VARHDRSZ);
105 106 107
			}
			else
			{					/* ... fixed */
108
				pq_sendint(&buf, retlen, 4);
109
				pq_sendbytes(&buf, DatumGetPointer(retval), retlen);
110 111
			}
		}
112 113
	}

114 115
	pq_sendbyte(&buf, '0');
	pq_endmessage(&buf);
116 117 118
}

/*
119 120 121 122 123 124 125
 * Formerly, this code attempted to cache the function and type info
 * looked up by fetch_fp_info, but only for the duration of a single
 * transaction command (since in theory the info could change between
 * commands).  This was utterly useless, because postgres.c executes
 * each fastpath call as a separate transaction command, and so the
 * cached data could never actually have been reused.  If it had worked
 * as intended, it would have had problems anyway with dangling references
126 127
 * in the FmgrInfo struct.	So, forget about caching and just repeat the
 * syscache fetches on each usage.	They're not *that* expensive.
128
 */
129 130
struct fp_info
{
131
	Oid			funcid;
132
	FmgrInfo	flinfo;			/* function lookup info for funcid */
133
	int16		arglen[FUNC_MAX_ARGS];
134
	bool		argbyval[FUNC_MAX_ARGS];
135
	int16		retlen;
136
	bool		retbyval;
137 138 139
};

/*
140
 * fetch_fp_info
141 142 143 144 145
 *
 * Performs catalog lookups to load a struct fp_info 'fip' for the
 * function 'func_id'.
 */
static void
146
fetch_fp_info(Oid func_id, struct fp_info * fip)
147
{
148
	Oid		   *argtypes;		/* an oidvector */
149
	Oid			rettype;
150
	HeapTuple	func_htp;
151 152
	Form_pg_proc pp;
	int			i;
153 154 155 156 157 158 159 160

	Assert(OidIsValid(func_id));
	Assert(fip != (struct fp_info *) NULL);

	/*
	 * Since the validity of this structure is determined by whether the
	 * funcid is OK, we clear the funcid here.	It must not be set to the
	 * correct value until we are about to return with a good struct
161
	 * fp_info, since we can be interrupted (i.e., with an elog(ERROR,
162
	 * ...)) at any time.  [No longer really an issue since we don't save
163 164
	 * the struct fp_info across transactions anymore, but keep it
	 * anyway.]
165
	 */
166
	MemSet((char *) fip, 0, sizeof(struct fp_info));
167 168
	fip->funcid = InvalidOid;

169 170
	fmgr_info(func_id, &fip->flinfo);

171 172 173
	func_htp = SearchSysCache(PROCOID,
							  ObjectIdGetDatum(func_id),
							  0, 0, 0);
174
	if (!HeapTupleIsValid(func_htp))
175
		elog(ERROR, "fetch_fp_info: cache lookup for function %u failed",
176 177 178 179 180
			 func_id);
	pp = (Form_pg_proc) GETSTRUCT(func_htp);
	rettype = pp->prorettype;
	argtypes = pp->proargtypes;

181
	for (i = 0; i < pp->pronargs; ++i)
182
	{
183 184 185 186
		get_typlenbyval(argtypes[i], &fip->arglen[i], &fip->argbyval[i]);
		/* We don't support cstring in fastpath protocol */
		if (fip->arglen[i] == -2)
			elog(ERROR, "CSTRING not supported in fastpath protocol");
187 188
	}

189 190 191
	get_typlenbyval(rettype, &fip->retlen, &fip->retbyval);
	if (fip->retlen == -2)
		elog(ERROR, "CSTRING not supported in fastpath protocol");
192

193 194
	ReleaseSysCache(func_htp);

195 196 197 198
	/*
	 * This must be last!
	 */
	fip->funcid = func_id;
199
}
200

201 202 203 204 205 206 207 208

/*
 * HandleFunctionRequest
 *
 * Server side of PQfn (fastpath function calls from the frontend).
 * This corresponds to the libpq protocol symbol "F".
 *
 * RETURNS:
209 210 211 212 213
 *		0 if successful completion, EOF if frontend connection lost.
 *
 * Note: All ordinary errors result in elog(ERROR,...).  However,
 * if we lose the frontend connection there is no one to elog to,
 * and no use in proceeding...
214 215 216 217 218
 *
 * Note: palloc()s done here and in the called function do not need to be
 * cleaned up explicitly.  We are called from PostgresMain() in the
 * QueryContext memory context, which will be automatically reset when
 * control returns to PostgresMain.
219 220
 */
int
221
HandleFunctionRequest(void)
222
{
223 224 225
	Oid			fid;
	int			argsize;
	int			nargs;
226
	int			tmp;
227
	AclResult	aclresult;
228 229
	FunctionCallInfoData fcinfo;
	Datum		retval;
230 231
	int			i;
	char	   *p;
232
	struct fp_info my_fp;
233 234
	struct fp_info *fip;

235 236 237 238
	/*
	 * XXX FIXME: This protocol is misdesigned.
	 *
	 * We really do not want to elog() before having swallowed all of the
B
Bruce Momjian 已提交
239 240 241 242 243 244
	 * frontend's fastpath message; otherwise we will lose sync with the
	 * input datastream.  What should happen is we absorb all of the input
	 * message per protocol syntax, and *then* do error checking
	 * (including lookup of the given function ID) and elog if
	 * appropriate.  Unfortunately, because we cannot even read the
	 * message properly without knowing whether the data types are
245 246 247
	 * pass-by-ref or pass-by-value, it's not all that easy to do :-(. The
	 * protocol should require the client to supply what it thinks is the
	 * typbyval and typlen value for each arg, so that we can read the
B
Bruce Momjian 已提交
248 249 250 251
	 * data without having to do any lookups.  Then after we've read the
	 * message, we should do the lookups, verify agreement of the actual
	 * function arg types with what we received, and finally call the
	 * function.
252 253
	 *
	 * As things stand, not only will we lose sync for an invalid message
B
Bruce Momjian 已提交
254 255 256 257
	 * (such as requested function OID doesn't exist), but we may lose
	 * sync for a perfectly valid message if we are in transaction-aborted
	 * state! This can happen because our database lookup attempts may
	 * fail entirely in abort state.
258 259
	 *
	 * Unfortunately I see no way to fix this without breaking a lot of
B
Bruce Momjian 已提交
260 261
	 * existing clients.  Maybe do it as part of next protocol version
	 * change.
262 263
	 */

264 265
	if (pq_getint(&tmp, 4))		/* function oid */
		return EOF;
266
	fid = (Oid) tmp;
267 268
	if (pq_getint(&nargs, 4))	/* # of arguments */
		return EOF;
269 270

	/*
271 272
	 * There used to be a lame attempt at caching lookup info here. Now we
	 * just do the lookups on every call.
273
	 */
274 275
	fip = &my_fp;
	fetch_fp_info(fid, fip);
276

277
	if (fip->flinfo.fn_nargs != nargs || nargs > FUNC_MAX_ARGS)
278
	{
279
		elog(ERROR, "HandleFunctionRequest: actual arguments (%d) != registered arguments (%d)",
280
			 nargs, fip->flinfo.fn_nargs);
281 282
	}

283 284 285 286
	MemSet(&fcinfo, 0, sizeof(fcinfo));
	fcinfo.flinfo = &fip->flinfo;
	fcinfo.nargs = nargs;

287
	/*
288 289
	 * Copy supplied arguments into arg vector.  Note there is no way for
	 * frontend to specify a NULL argument --- more misdesign.
290
	 */
291
	for (i = 0; i < nargs; ++i)
292
	{
293 294 295 296 297 298 299 300 301
		if (pq_getint(&argsize, 4))
			return EOF;
		if (fip->argbyval[i])
		{						/* by-value */
			if (argsize < 1 || argsize > 4)
				elog(ERROR, "HandleFunctionRequest: bogus argsize %d",
					 argsize);
			/* XXX should we demand argsize == fip->arglen[i] ? */
			if (pq_getint(&tmp, argsize))
302
				return EOF;
303 304 305 306
			fcinfo.arg[i] = (Datum) tmp;
		}
		else
		{						/* by-reference ... */
307
			if (fip->arglen[i] == -1)
308 309 310 311 312
			{					/* ... varlena */
				if (argsize < 0)
					elog(ERROR, "HandleFunctionRequest: bogus argsize %d",
						 argsize);
				/* I suspect this +1 isn't really needed - tgl 5/2000 */
B
Bruce Momjian 已提交
313 314 315
				p = palloc(argsize + VARHDRSZ + 1);		/* Added +1 to solve
														 * memory leak - Peter
														 * 98 Jan 6 */
J
TOAST  
Jan Wieck 已提交
316
				VARATT_SIZEP(p) = argsize + VARHDRSZ;
317
				if (pq_getbytes(VARDATA(p), argsize))
318
					return EOF;
319
			}
320
			else
321 322 323 324
			{					/* ... fixed */
				if (argsize != fip->arglen[i])
					elog(ERROR, "HandleFunctionRequest: bogus argsize %d, should be %d",
						 argsize, fip->arglen[i]);
B
Bruce Momjian 已提交
325
				p = palloc(argsize + 1);		/* +1 in case argsize is 0 */
326 327
				if (pq_getbytes(p, argsize))
					return EOF;
328
			}
329
			fcinfo.arg[i] = PointerGetDatum(p);
330
		}
331 332
	}

333 334 335 336 337 338 339 340 341 342 343
	/*
	 * Now that we've eaten the input message, check to see if we actually
	 * want to do the function call or not.
	 *
	 * Currently, we report an error if in ABORT state, or return a dummy
	 * NULL response if fastpath support has been compiled out.
	 */
	if (IsAbortedTransactionBlockState())
		elog(ERROR, "current transaction is aborted, "
			 "queries ignored until end of transaction block");

344 345 346 347 348 349 350 351 352 353 354 355
	/* Check permission to call function */
	aclresult = pg_proc_aclcheck(fid, GetUserId(), ACL_EXECUTE);
	if (aclresult != ACLCHECK_OK)
		aclcheck_error(aclresult, get_func_name(fid));

	/*
	 * Set up a query snapshot in case function needs one.  (It is not safe
	 * to do this if we are in transaction-abort state, so we have to postpone
	 * it till now.  Ugh.)
	 */
	SetQuerySnapshot();

356 357 358 359
#ifdef NO_FASTPATH
	/* force a NULL return */
	retval = (Datum) 0;
	fcinfo.isnull = true;
360
#else
361
	retval = FunctionCallInvoke(&fcinfo);
362
#endif   /* NO_FASTPATH */
363

364 365 366 367
	if (fcinfo.isnull)
		SendFunctionResult(retval, fip->retbyval, 0);
	else
		SendFunctionResult(retval, fip->retbyval, fip->retlen);
368

369
	return 0;
370
}