fastpath.c 10.5 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.60 2003/05/02 20:54:35 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 32 33 34
 *
 *-------------------------------------------------------------------------
 */
#include "postgres.h"

35 36 37
#include <netinet/in.h>
#include <arpa/inet.h>

B
Bruce Momjian 已提交
38
#include "access/xact.h"
39
#include "catalog/pg_proc.h"
B
Bruce Momjian 已提交
40 41
#include "libpq/libpq.h"
#include "libpq/pqformat.h"
42
#include "miscadmin.h"
B
Bruce Momjian 已提交
43
#include "tcop/fastpath.h"
44
#include "utils/acl.h"
45
#include "utils/lsyscache.h"
B
Bruce Momjian 已提交
46
#include "utils/syscache.h"
47
#include "utils/tqual.h"
48 49


50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
/* ----------------
 *		GetOldFunctionMessage
 *
 * In pre-3.0 protocol, there is no length word on the message, so we have
 * to have code that understands the message layout to absorb the message
 * into a buffer.  We want to do this before we start execution, so that
 * we do not lose sync with the frontend if there's an error.
 *
 * The caller should already have initialized buf to empty.
 * ----------------
 */
static int
GetOldFunctionMessage(StringInfo buf)
{
	int32		ibuf;
	int			nargs;

	/* Dummy string argument */
	if (pq_getstring(buf))
		return EOF;
	/* Function OID */
	if (pq_getbytes((char *) &ibuf, 4))
		return EOF;
	appendBinaryStringInfo(buf, (char *) &ibuf, 4);
	/* Number of arguments */
	if (pq_getbytes((char *) &ibuf, 4))
		return EOF;
	appendBinaryStringInfo(buf, (char *) &ibuf, 4);
	nargs = ntohl(ibuf);
	/* For each argument ... */
	while (nargs-- > 0)
	{
		int			argsize;

		/* argsize */
		if (pq_getbytes((char *) &ibuf, 4))
			return EOF;
		appendBinaryStringInfo(buf, (char *) &ibuf, 4);
		argsize = ntohl(ibuf);
		if (argsize < 0)
		{
			/* FATAL here since no hope of regaining message sync */
			elog(FATAL, "HandleFunctionRequest: bogus argsize %d",
				 argsize);
		}
		/* and arg contents */
		if (argsize > 0)
		{
			/* Allocate space for arg */
			enlargeStringInfo(buf, argsize);
			/* And grab it */
			if (pq_getbytes(buf->data + buf->len, argsize))
				return EOF;
			buf->len += argsize;
			/* Place a trailing null per StringInfo convention */
			buf->data[buf->len] = '\0';
		}
	}
	return 0;
}

111
/* ----------------
112
 *		SendFunctionResult
113 114
 *
 * retlen is 0 if returning NULL, else the typlen according to the catalogs
115 116 117
 * ----------------
 */
static void
118
SendFunctionResult(Datum retval, bool retbyval, int retlen)
119
{
120 121
	StringInfoData buf;

122
	pq_beginmessage(&buf, 'V');
123 124 125

	if (retlen != 0)
	{
126
		pq_sendbyte(&buf, 'G');
127 128
		if (retbyval)
		{						/* by-value */
129
			pq_sendint(&buf, retlen, 4);
130
			pq_sendint(&buf, DatumGetInt32(retval), retlen);
131 132 133
		}
		else
		{						/* by-reference ... */
134
			if (retlen == -1)
135
			{					/* ... varlena */
136
				struct varlena *v = PG_DETOAST_DATUM(retval);
137 138 139

				pq_sendint(&buf, VARSIZE(v) - VARHDRSZ, VARHDRSZ);
				pq_sendbytes(&buf, VARDATA(v), VARSIZE(v) - VARHDRSZ);
140 141 142
			}
			else
			{					/* ... fixed */
143
				pq_sendint(&buf, retlen, 4);
144
				pq_sendbytes(&buf, DatumGetPointer(retval), retlen);
145 146
			}
		}
147 148
	}

149 150
	pq_sendbyte(&buf, '0');
	pq_endmessage(&buf);
151 152 153
}

/*
154 155 156 157 158 159 160
 * 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
161 162
 * in the FmgrInfo struct.	So, forget about caching and just repeat the
 * syscache fetches on each usage.	They're not *that* expensive.
163
 */
164 165
struct fp_info
{
166
	Oid			funcid;
167
	FmgrInfo	flinfo;			/* function lookup info for funcid */
168
	int16		arglen[FUNC_MAX_ARGS];
169
	bool		argbyval[FUNC_MAX_ARGS];
170
	int16		retlen;
171
	bool		retbyval;
172 173 174
};

/*
175
 * fetch_fp_info
176 177 178 179 180
 *
 * Performs catalog lookups to load a struct fp_info 'fip' for the
 * function 'func_id'.
 */
static void
181
fetch_fp_info(Oid func_id, struct fp_info * fip)
182
{
183
	Oid		   *argtypes;		/* an oidvector */
184
	Oid			rettype;
185
	HeapTuple	func_htp;
186 187
	Form_pg_proc pp;
	int			i;
188 189 190 191 192 193 194 195

	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
196
	 * fp_info, since we can be interrupted (i.e., with an elog(ERROR,
197
	 * ...)) at any time.  [No longer really an issue since we don't save
198 199
	 * the struct fp_info across transactions anymore, but keep it
	 * anyway.]
200
	 */
201
	MemSet((char *) fip, 0, sizeof(struct fp_info));
202 203
	fip->funcid = InvalidOid;

204 205
	fmgr_info(func_id, &fip->flinfo);

206 207 208
	func_htp = SearchSysCache(PROCOID,
							  ObjectIdGetDatum(func_id),
							  0, 0, 0);
209
	if (!HeapTupleIsValid(func_htp))
210
		elog(ERROR, "fetch_fp_info: cache lookup for function %u failed",
211 212 213 214 215
			 func_id);
	pp = (Form_pg_proc) GETSTRUCT(func_htp);
	rettype = pp->prorettype;
	argtypes = pp->proargtypes;

216
	for (i = 0; i < pp->pronargs; ++i)
217
	{
218 219 220 221
		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");
222 223
	}

224 225 226
	get_typlenbyval(rettype, &fip->retlen, &fip->retbyval);
	if (fip->retlen == -2)
		elog(ERROR, "CSTRING not supported in fastpath protocol");
227

228 229
	ReleaseSysCache(func_htp);

230 231 232 233
	/*
	 * This must be last!
	 */
	fip->funcid = func_id;
234
}
235

236 237 238 239 240 241 242

/*
 * HandleFunctionRequest
 *
 * Server side of PQfn (fastpath function calls from the frontend).
 * This corresponds to the libpq protocol symbol "F".
 *
243 244 245 246 247 248
 * INPUT:
 *		In protocol version 3, postgres.c has already read the message body
 *		and will pass it in msgBuf.
 *		In old protocol, the passed msgBuf is empty and we must read the
 *		message here.
 * 
249
 * RETURNS:
250 251 252 253 254
 *		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...
255 256 257
 *
 * 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
258
 * MessageContext memory context, which will be automatically reset when
259
 * control returns to PostgresMain.
260 261
 */
int
262
HandleFunctionRequest(StringInfo msgBuf)
263
{
264 265
	Oid			fid;
	int			nargs;
266
	AclResult	aclresult;
267 268
	FunctionCallInfoData fcinfo;
	Datum		retval;
269
	int			i;
270
	struct fp_info my_fp;
271 272
	struct fp_info *fip;

273
	/*
274
	 * Read message contents if not already done.
275
	 */
276 277 278 279 280 281 282 283
	if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
	{
		if (GetOldFunctionMessage(msgBuf))
		{
			elog(COMMERROR, "unexpected EOF on client connection");
			return EOF;
		}
	}
284

285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
	/*
	 * Now that we've eaten the input message, check to see if we actually
	 * want to do the function call or not.  It's now safe to elog(); we won't
	 * lose sync with the frontend.
	 */
	if (IsAbortedTransactionBlockState())
		elog(ERROR, "current transaction is aborted, "
			 "queries ignored until end of transaction block");

	/*
	 * Parse the buffer contents.
	 */
	(void) pq_getmsgstring(msgBuf);	/* dummy string */
	fid = (Oid) pq_getmsgint(msgBuf, 4); /* function oid */
	nargs = pq_getmsgint(msgBuf, 4);	/* # of arguments */
300 301

	/*
302 303
	 * There used to be a lame attempt at caching lookup info here. Now we
	 * just do the lookups on every call.
304
	 */
305 306
	fip = &my_fp;
	fetch_fp_info(fid, fip);
307

308 309 310 311 312
	/* Check permission to call function */
	aclresult = pg_proc_aclcheck(fid, GetUserId(), ACL_EXECUTE);
	if (aclresult != ACLCHECK_OK)
		aclcheck_error(aclresult, get_func_name(fid));

313
	if (fip->flinfo.fn_nargs != nargs || nargs > FUNC_MAX_ARGS)
314
		elog(ERROR, "HandleFunctionRequest: actual arguments (%d) != registered arguments (%d)",
315
			 nargs, fip->flinfo.fn_nargs);
316

317 318 319 320
	MemSet(&fcinfo, 0, sizeof(fcinfo));
	fcinfo.flinfo = &fip->flinfo;
	fcinfo.nargs = nargs;

321
	/*
322
	 * Copy supplied arguments into arg vector.  Note there is no way for
323
	 * frontend to specify a NULL argument --- this protocol is misdesigned.
324
	 */
325
	for (i = 0; i < nargs; ++i)
326
	{
327 328 329 330
		int			argsize;
		char	   *p;

		argsize = pq_getmsgint(msgBuf, 4);
331 332 333 334 335 336
		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] ? */
337
			fcinfo.arg[i] = (Datum) pq_getmsgint(msgBuf, argsize);
338 339 340
		}
		else
		{						/* by-reference ... */
341
			if (fip->arglen[i] == -1)
342 343 344 345
			{					/* ... varlena */
				if (argsize < 0)
					elog(ERROR, "HandleFunctionRequest: bogus argsize %d",
						 argsize);
346
				p = palloc(argsize + VARHDRSZ);
J
TOAST  
Jan Wieck 已提交
347
				VARATT_SIZEP(p) = argsize + VARHDRSZ;
348
				pq_copymsgbytes(msgBuf, VARDATA(p), argsize);
349
			}
350
			else
351 352 353 354
			{					/* ... fixed */
				if (argsize != fip->arglen[i])
					elog(ERROR, "HandleFunctionRequest: bogus argsize %d, should be %d",
						 argsize, fip->arglen[i]);
B
Bruce Momjian 已提交
355
				p = palloc(argsize + 1);		/* +1 in case argsize is 0 */
356
				pq_copymsgbytes(msgBuf, p, argsize);
357
			}
358
			fcinfo.arg[i] = PointerGetDatum(p);
359
		}
360 361
	}

362 363 364 365 366 367 368
	/*
	 * 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();

369 370 371 372
#ifdef NO_FASTPATH
	/* force a NULL return */
	retval = (Datum) 0;
	fcinfo.isnull = true;
373
#else
374
	retval = FunctionCallInvoke(&fcinfo);
375
#endif   /* NO_FASTPATH */
376

377 378 379 380
	if (fcinfo.isnull)
		SendFunctionResult(retval, fip->retbyval, 0);
	else
		SendFunctionResult(retval, fip->retbyval, fip->retlen);
381

382
	return 0;
383
}