⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 fe-misc.c

📁 PostgreSQL 8.1.4的源码 适用于Linux下的开源数据库系统
💻 C
📖 第 1 页 / 共 2 页
字号:
/*------------------------------------------------------------------------- * *	 FILE *		fe-misc.c * *	 DESCRIPTION *		 miscellaneous useful functions * * The communication routines here are analogous to the ones in * backend/libpq/pqcomm.c and backend/libpq/pqcomprim.c, but operate * in the considerably different environment of the frontend libpq. * In particular, we work with a bare nonblock-mode socket, rather than * a stdio stream, so that we can avoid unwanted blocking of the application. * * XXX: MOVE DEBUG PRINTOUT TO HIGHER LEVEL.  As is, block and restart * will cause repeat printouts. * * We must speak the same transmitted data representations as the backend * routines. * * * Portions Copyright (c) 1996-2005, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * * IDENTIFICATION *	  $PostgreSQL: pgsql/src/interfaces/libpq/fe-misc.c,v 1.122.2.1 2005/11/22 18:23:30 momjian Exp $ * *------------------------------------------------------------------------- */#include "postgres_fe.h"#include <errno.h>#include <signal.h>#include <time.h>#ifndef WIN32_CLIENT_ONLY#include <netinet/in.h>#include <arpa/inet.h>#endif#ifdef WIN32#include "win32.h"#else#include <unistd.h>#include <sys/time.h>#endif#ifdef HAVE_POLL_H#include <poll.h>#endif#ifdef HAVE_SYS_POLL_H#include <sys/poll.h>#endif#ifdef HAVE_SYS_SELECT_H#include <sys/select.h>#endif#include "libpq-fe.h"#include "libpq-int.h"#include "pqsignal.h"#include "mb/pg_wchar.h"static int	pqPutMsgBytes(const void *buf, size_t len, PGconn *conn);static int	pqSendSome(PGconn *conn, int len);static int pqSocketCheck(PGconn *conn, int forRead, int forWrite,			  time_t end_time);static int	pqSocketPoll(int sock, int forRead, int forWrite, time_t end_time);/* * pqGetc: get 1 character from the connection * *	All these routines return 0 on success, EOF on error. *	Note that for the Get routines, EOF only means there is not enough *	data in the buffer, not that there is necessarily a hard error. */intpqGetc(char *result, PGconn *conn){	if (conn->inCursor >= conn->inEnd)		return EOF;	*result = conn->inBuffer[conn->inCursor++];	if (conn->Pfdebug)		fprintf(conn->Pfdebug, "From backend> %c\n", *result);	return 0;}/* * pqPutc: write 1 char to the current message */intpqPutc(char c, PGconn *conn){	if (pqPutMsgBytes(&c, 1, conn))		return EOF;	if (conn->Pfdebug)		fprintf(conn->Pfdebug, "To backend> %c\n", c);	return 0;}/* * pqGets: * get a null-terminated string from the connection, * and store it in an expansible PQExpBuffer. * If we run out of memory, all of the string is still read, * but the excess characters are silently discarded. */intpqGets(PQExpBuffer buf, PGconn *conn){	/* Copy conn data to locals for faster search loop */	char	   *inBuffer = conn->inBuffer;	int			inCursor = conn->inCursor;	int			inEnd = conn->inEnd;	int			slen;	while (inCursor < inEnd && inBuffer[inCursor])		inCursor++;	if (inCursor >= inEnd)		return EOF;	slen = inCursor - conn->inCursor;	resetPQExpBuffer(buf);	appendBinaryPQExpBuffer(buf, inBuffer + conn->inCursor, slen);	conn->inCursor = ++inCursor;	if (conn->Pfdebug)		fprintf(conn->Pfdebug, "From backend> \"%s\"\n",				buf->data);	return 0;}/* * pqPuts: write a null-terminated string to the current message */intpqPuts(const char *s, PGconn *conn){	if (pqPutMsgBytes(s, strlen(s) + 1, conn))		return EOF;	if (conn->Pfdebug)		fprintf(conn->Pfdebug, "To backend> \"%s\"\n", s);	return 0;}/* * pqGetnchar: *	get a string of exactly len bytes in buffer s, no null termination */intpqGetnchar(char *s, size_t len, PGconn *conn){	if (len < 0 || len > (size_t) (conn->inEnd - conn->inCursor))		return EOF;	memcpy(s, conn->inBuffer + conn->inCursor, len);	/* no terminating null */	conn->inCursor += len;	if (conn->Pfdebug)		fprintf(conn->Pfdebug, "From backend (%lu)> %.*s\n",				(unsigned long) len, (int) len, s);	return 0;}/* * pqPutnchar: *	write exactly len bytes to the current message */intpqPutnchar(const char *s, size_t len, PGconn *conn){	if (pqPutMsgBytes(s, len, conn))		return EOF;	if (conn->Pfdebug)		fprintf(conn->Pfdebug, "To backend> %.*s\n", (int) len, s);	return 0;}/* * pqGetInt *	read a 2 or 4 byte integer and convert from network byte order *	to local byte order */intpqGetInt(int *result, size_t bytes, PGconn *conn){	uint16		tmp2;	uint32		tmp4;	switch (bytes)	{		case 2:			if (conn->inCursor + 2 > conn->inEnd)				return EOF;			memcpy(&tmp2, conn->inBuffer + conn->inCursor, 2);			conn->inCursor += 2;			*result = (int) ntohs(tmp2);			break;		case 4:			if (conn->inCursor + 4 > conn->inEnd)				return EOF;			memcpy(&tmp4, conn->inBuffer + conn->inCursor, 4);			conn->inCursor += 4;			*result = (int) ntohl(tmp4);			break;		default:			pqInternalNotice(&conn->noticeHooks,							 "integer of size %lu not supported by pqGetInt",							 (unsigned long) bytes);			return EOF;	}	if (conn->Pfdebug)		fprintf(conn->Pfdebug, "From backend (#%lu)> %d\n", (unsigned long) bytes, *result);	return 0;}/* * pqPutInt * write an integer of 2 or 4 bytes, converting from host byte order * to network byte order. */intpqPutInt(int value, size_t bytes, PGconn *conn){	uint16		tmp2;	uint32		tmp4;	switch (bytes)	{		case 2:			tmp2 = htons((uint16) value);			if (pqPutMsgBytes((const char *) &tmp2, 2, conn))				return EOF;			break;		case 4:			tmp4 = htonl((uint32) value);			if (pqPutMsgBytes((const char *) &tmp4, 4, conn))				return EOF;			break;		default:			pqInternalNotice(&conn->noticeHooks,							 "integer of size %lu not supported by pqPutInt",							 (unsigned long) bytes);			return EOF;	}	if (conn->Pfdebug)		fprintf(conn->Pfdebug, "To backend (%lu#)> %d\n", (unsigned long) bytes, value);	return 0;}/* * Make sure conn's output buffer can hold bytes_needed bytes (caller must * include already-stored data into the value!) * * Returns 0 on success, EOF if failed to enlarge buffer */intpqCheckOutBufferSpace(int bytes_needed, PGconn *conn){	int			newsize = conn->outBufSize;	char	   *newbuf;	if (bytes_needed <= newsize)		return 0;	/*	 * If we need to enlarge the buffer, we first try to double it in size; if	 * that doesn't work, enlarge in multiples of 8K.  This avoids thrashing	 * the malloc pool by repeated small enlargements.	 *	 * Note: tests for newsize > 0 are to catch integer overflow.	 */	do	{		newsize *= 2;	} while (bytes_needed > newsize && newsize > 0);	if (bytes_needed <= newsize)	{		newbuf = realloc(conn->outBuffer, newsize);		if (newbuf)		{			/* realloc succeeded */			conn->outBuffer = newbuf;			conn->outBufSize = newsize;			return 0;		}	}	newsize = conn->outBufSize;	do	{		newsize += 8192;	} while (bytes_needed > newsize && newsize > 0);	if (bytes_needed <= newsize)	{		newbuf = realloc(conn->outBuffer, newsize);		if (newbuf)		{			/* realloc succeeded */			conn->outBuffer = newbuf;			conn->outBufSize = newsize;			return 0;		}	}	/* realloc failed. Probably out of memory */	printfPQExpBuffer(&conn->errorMessage,					  "cannot allocate memory for output buffer\n");	return EOF;}/* * Make sure conn's input buffer can hold bytes_needed bytes (caller must * include already-stored data into the value!) * * Returns 0 on success, EOF if failed to enlarge buffer */intpqCheckInBufferSpace(int bytes_needed, PGconn *conn){	int			newsize = conn->inBufSize;	char	   *newbuf;	if (bytes_needed <= newsize)		return 0;	/*	 * If we need to enlarge the buffer, we first try to double it in size; if	 * that doesn't work, enlarge in multiples of 8K.  This avoids thrashing	 * the malloc pool by repeated small enlargements.	 *	 * Note: tests for newsize > 0 are to catch integer overflow.	 */	do	{		newsize *= 2;	} while (bytes_needed > newsize && newsize > 0);	if (bytes_needed <= newsize)	{		newbuf = realloc(conn->inBuffer, newsize);		if (newbuf)		{			/* realloc succeeded */			conn->inBuffer = newbuf;			conn->inBufSize = newsize;			return 0;		}	}	newsize = conn->inBufSize;	do	{		newsize += 8192;	} while (bytes_needed > newsize && newsize > 0);	if (bytes_needed <= newsize)	{		newbuf = realloc(conn->inBuffer, newsize);		if (newbuf)		{			/* realloc succeeded */			conn->inBuffer = newbuf;			conn->inBufSize = newsize;			return 0;		}	}	/* realloc failed. Probably out of memory */	printfPQExpBuffer(&conn->errorMessage,					  "cannot allocate memory for input buffer\n");	return EOF;}/* * pqPutMsgStart: begin construction of a message to the server * * msg_type is the message type byte, or 0 for a message without type byte * (only startup messages have no type byte) * * force_len forces the message to have a length word; otherwise, we add * a length word if protocol 3. * * Returns 0 on success, EOF on error * * The idea here is that we construct the message in conn->outBuffer, * beginning just past any data already in outBuffer (ie, at * outBuffer+outCount).  We enlarge the buffer as needed to hold the message. * When the message is complete, we fill in the length word (if needed) and * then advance outCount past the message, making it eligible to send. * * The state variable conn->outMsgStart points to the incomplete message's * length word: it is either outCount or outCount+1 depending on whether * there is a type byte.  If we are sending a message without length word * (pre protocol 3.0 only), then outMsgStart is -1.  The state variable * conn->outMsgEnd is the end of the data collected so far. */intpqPutMsgStart(char msg_type, bool force_len, PGconn *conn){	int			lenPos;	int			endPos;	/* allow room for message type byte */	if (msg_type)		endPos = conn->outCount + 1;	else		endPos = conn->outCount;	/* do we want a length word? */	if (force_len || PG_PROTOCOL_MAJOR(conn->pversion) >= 3)	{		lenPos = endPos;		/* allow room for message length */		endPos += 4;	}	else		lenPos = -1;	/* make sure there is room for message header */	if (pqCheckOutBufferSpace(endPos, conn))		return EOF;	/* okay, save the message type byte if any */	if (msg_type)		conn->outBuffer[conn->outCount] = msg_type;	/* set up the message pointers */	conn->outMsgStart = lenPos;	conn->outMsgEnd = endPos;	/* length word, if needed, will be filled in by pqPutMsgEnd */	if (conn->Pfdebug)		fprintf(conn->Pfdebug, "To backend> Msg %c\n",				msg_type ? msg_type : ' ');	return 0;}/* * pqPutMsgBytes: add bytes to a partially-constructed message * * Returns 0 on success, EOF on error */static intpqPutMsgBytes(const void *buf, size_t len, PGconn *conn){	/* make sure there is room for it */	if (pqCheckOutBufferSpace(conn->outMsgEnd + len, conn))		return EOF;	/* okay, save the data */	memcpy(conn->outBuffer + conn->outMsgEnd, buf, len);	conn->outMsgEnd += len;	/* no Pfdebug call here, caller should do it */	return 0;}/* * pqPutMsgEnd: finish constructing a message and possibly send it * * Returns 0 on success, EOF on error * * We don't actually send anything here unless we've accumulated at least * 8K worth of data (the typical size of a pipe buffer on Unix systems). * This avoids sending small partial packets.  The caller must use pqFlush * when it's important to flush all the data out to the server. */intpqPutMsgEnd(PGconn *conn){	if (conn->Pfdebug)		fprintf(conn->Pfdebug, "To backend> Msg complete, length %u\n",				conn->outMsgEnd - conn->outCount);	/* Fill in length word if needed */	if (conn->outMsgStart >= 0)	{		uint32		msgLen = conn->outMsgEnd - conn->outMsgStart;		msgLen = htonl(msgLen);		memcpy(conn->outBuffer + conn->outMsgStart, &msgLen, 4);	}	/* Make message eligible to send */	conn->outCount = conn->outMsgEnd;	if (conn->outCount >= 8192)	{		int			toSend = conn->outCount - (conn->outCount % 8192);		if (pqSendSome(conn, toSend) < 0)			return EOF;		/* in nonblock mode, don't complain if unable to send it all */	}	return 0;}/* ---------- * pqReadData: read more data, if any is available * Possible return values: *	 1: successfully loaded at least one more byte *	 0: no data is presently available, but no error detected *	-1: error detected (including EOF = connection closure); *		conn->errorMessage set * NOTE: callers must not assume that pointers or indexes into conn->inBuffer * remain valid across this call! * ---------- */intpqReadData(PGconn *conn){	int			someread = 0;	int			nread;	char		sebuf[256];	if (conn->sock < 0)	{		printfPQExpBuffer(&conn->errorMessage,						  libpq_gettext("connection not open\n"));		return -1;	}	/* Left-justify any data in the buffer to make room */	if (conn->inStart < conn->inEnd)	{		if (conn->inStart > 0)		{			memmove(conn->inBuffer, conn->inBuffer + conn->inStart,					conn->inEnd - conn->inStart);			conn->inEnd -= conn->inStart;			conn->inCursor -= conn->inStart;			conn->inStart = 0;		}	}	else	{		/* buffer is logically empty, reset it */		conn->inStart = conn->inCursor = conn->inEnd = 0;	}	/*	 * If the buffer is fairly full, enlarge it. We need to be able to enlarge	 * the buffer in case a single message exceeds the initial buffer size. We	 * enlarge before filling the buffer entirely so as to avoid asking the	 * kernel for a partial packet. The magic constant here should be large	 * enough for a TCP packet or Unix pipe bufferload.  8K is the usual pipe	 * buffer size, so...	 */	if (conn->inBufSize - conn->inEnd < 8192)	{		if (pqCheckInBufferSpace(conn->inEnd + 8192, conn))		{

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -