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

📄 sendpi3x.cpp

📁 mini http server,可以集成嵌入到程序中,实现简单的web功能
💻 CPP
字号:
/*____________________________________________________________________________*\
 *

 Copyright (c) 1997-2003 John Roy, Holger Zimmermann. All rights reserved.

 These sources, libraries and applications are
 FREE FOR COMMERCIAL AND NON-COMMERCIAL USE
 as long as the following conditions are adhered to.

 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions
 are met:

 1. Redistributions of source code must retain the above copyright
    notice, this list of conditions and the following disclaimer. 

 2. Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in
    the documentation and/or other materials provided with the
    distribution.

 3. The name of the author may not be used to endorse or promote products
    derived from this software without specific prior written permission.

 THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 IN NO EVENT SHALL THE AUTHORS OR ITS CONTRIBUTORS BE LIABLE FOR ANY
 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 OF THE POSSIBILITY OF SUCH DAMAGE.

 *____________________________________________________________________________*|
 *
 * $Source: /cvsroot/pi3web/Pi3Web_200/Source/HTTP/SendPi3X.cpp,v $
 * $Date: 2003/05/13 18:42:04 $
 *
 Description:
	Evaluate and send Pi3 expression to a remote client.

\*____________________________________________________________________________*/
//$SourceTop:$

#include <ctype.h>
#include <stdio.h>

#include "HandBase.h"
#include "HTTPUtil.h"
#include "HTTPCore.h"
#include "PIStrStr.h"
#include "DblList.h"
#include "StrToken.h"
#include "Pi3Expr.h"

/*____________________________________________________________________________*\
 *
 Description:
\*____________________________________________________________________________*/
#define CONFIG_ERROR(this, msg)	\
	{ PILog_addMessage( PIObject_getDB(this), \
	PIObject_getConfigurationDB(this), PILOG_ERROR, (msg) ); }

/*____________________________________________________________________________*\
 *
 Class:
 Description:
	Parse, store and add RFC822 headers to  response DB's.
\*____________________________________________________________________________*/
class RFC822Header
{
private:
	const char *pFKVariable;
	PIString sValue;
	int iOK;

public:
	RFC822Header( const char *pLine )
	:	pFKVariable( 0 ),
		iOK( 0 )
		{
		if ( !pLine )
			{ return; };
		int iLen = strlen( pLine );
		int i;
		for( i=0; i<iLen && pLine[i]!=':' && !(isspace(pLine[i])); i++);
		if ( !i || pLine[i]!=':' )
			{ return; };
		PIString sVariable( pLine, i );
		for( i++; i<iLen && (isspace(pLine[i])); i++);	/* scan past ws */
		pFKVariable = PIDB_getFastKey( sVariable, PIDBTYPE_RFC822 );
		sValue = &( pLine[i] );
		iOK = 1;
		};

	/* --- Replace this header in DB --- */
	void ReplaceHeader( PIDB *pDB )
		{
		assert( pDB );
		assert( pFKVariable );
		assert( iOK );
		PIDB_replace( pDB, PIDBTYPE_RFC822, pFKVariable,
			(void *)(const char *)sValue, PIDBFLAG_FASTKEY );
		};

	inline int IsOK()
		{ return iOK; };
};

/*____________________________________________________________________________*\
 *
 Description:
\*____________________________________________________________________________*/
#define KEY_CONF_PI3EXPRESSION			"Pi3Expression"
#define KEY_CONF_INMULTIPARTRESPONSE	"InMultipartResponse"
#define KEY_CONF_BUFFERSIZE				"BufferSize"
#define KEY_CONF_HTTPEQUIV				"HTTPEquiv"
#define VALUE_YES						"Yes"

#define INITIAL_BUFFER_SIZE				2048

#if 0
	/*
	** HTML documentation for this handler
	*/
/*___+++HTMLDOC_BEGIN+++___*/
Name:
	SendPi3Expression

Description:
	This handler object evalulates and sends a Pi3Expression to a the
	client.
	By default this handler will send the result in the context of a 
	single-bodied response to the client. This default can be overriden
	so this handler sends one content-body of a mulipart response.

Options:
<H5>Overview</H5>
<TABLE BORDER=1>
<TH>Option
<TH>Default
<TH>Values
<TH>Short Description
<TH>Example(s)

<TR>
<TD>Pi3Expression
<TD>+
<TD>A Pi3Expression
<TD>Pi3Expression to be sent
<TD>"Process [$P], Thread [$k]"

<TR>
<TD>InMultipartResponse
<TD>No
<TD>Yes, No
<TD>Multipart response indicator
<TD>InMultipartResponse=Yes

<TR>
<TD>BufferSize
<TD>-1
<TD>A decimal number
<TD>Maximum message length 
<TD>BufferSize=4096

<TR>
<TD>HTTPEquiv
<TD>-
<TD>"&lt;rfc822_variable&gt;: &lt;content&gt;"
<TD>HTTP Entity header
<TD>"Content-Type: text/html"

</TABLE>
<STRONG>-</STRONG> in the <IT>default</IT> indicates no default<BR>
<STRONG>+</STRONG> in the <IT>default</IT> indicates the field is mandatory<BR>

<H4>Description of Options</H4>
<H5>
	Pi3Expression
</H5>
A full Pi3Expression to be evaluated and sent to the remote client. 
<H5>
	InMultipartResponse
</H5>
Specify whether or not the response is part of a multipart response. This
handler object specifies a multipart response differently from a single 
response in the following way:-
<LIST>
<ITEM>The handler will not return PIAPI_COMPLETED, but PIAPI_CONTINUE, to
allow multiple responses to be listed in order for the HANDLE phase.
<ITEM>Only the entity headers will be send to the client (Content-Type,
Content-Length, etc.) not the general headers (Server, Connection etc.).
<ITEM>The seperator header willl be sent as appropriate.
</LIST>
The values 'Yes' or 'No' (not case sensitive) may be used.
<H5>
	BufferSize
</H5>
Specify the maximum message length that may be sent to the client. Expressions
which evaluate to greater than this length will be truncated. A value
of -1 specifies no limit.
<H5>
	HTTPEquiv
</H5>
Specify additional rfc822 headers to send to the client. Any headers
given override default headers set by this handler, i.e. 'Content-Length' and
'Content-Type'. Care must be taken so that addition of headers would 
cause the HTTP protocol as specified to be violated. In particular,
the 'Content-Length' header should not be specified.

Phase:
	HANDLE

Returns:
	PIAPI_COMPLETED on success if InMultiPartResponse is 'No'.
	PIAPI_CONTINUE if no action taken or on success and InMultiPartResponse is
		'Yes'.
	PIAPI_ERROR and PIAPI_ABORT respectively for generic and severe
	error conditions.

Example:
	<PRE>
	&lt;Object&gt;
		Name SendPi3Expression
		Class SendPi3ExpressionClass
		BufferSize 128
		HTTPEquiv "Content-Type: text/plain"
	&lt;/Object&gt;

	&lt;Object&gt;
		...
		Handle SendPi3Expression \
			Pi3Expression="Hello, your computer's hostname is $h."
		...
	&lt;/Object&gt;

	</PRE>
/*___+++HTMLDOC_END+++___*/
#endif

/*____________________________________________________________________________*\
 *
 Class:
 Description:
\*____________________________________________________________________________*/
class SendPi3Expression : public HandlerBaseHTTP
{
private:
	/* --- forbid copy constructor --- */
	SendPi3Expression( const SendPi3Expression &t )
	: HandlerBaseHTTP( t )
		{ assert( 0 ); };

	/* ---
	Configuration data
	--- */
	Pi3Expression *pExpr;
	int iBufferSize;
	DblList lHTTPEquivalents;
	int iMultipart;

protected:
	int Parameter( const char *pVariable, const char *pValue,
		const char *pWhere )
		{
		assert( pVariable );
		assert( pValue );

		PIOStrStream os;
		os << pWhere << "SendPi3Expression: ";

		if ( !PIUtil_stricmp( KEY_CONF_PI3EXPRESSION, pVariable ) )
			{
			if ( pExpr )
				{
				os << "Pi3Expession already defined." << ends;
				CONFIG_ERROR( Object(), os.str() );
				return 0;
				};
			Pi3String *pError = Pi3String_new( 0 );
			pExpr = Pi3Expression_new( pValue, 0, pError );
			if ( !pExpr )
				{
				os << Pi3String_getPtr( pError ) << ends;
				Pi3String_delete( pError );
				CONFIG_ERROR( Object(), os.str() );
				pExpr = 0;
				return 0;
				};
			Pi3String_delete( pError );
			}
		else if ( !PIUtil_stricmp( KEY_CONF_BUFFERSIZE, pVariable ) )
			{
			int iTmp = atoi( pValue );
			iBufferSize = iTmp;
			}
		else if ( !PIUtil_stricmp( KEY_CONF_HTTPEQUIV, pVariable ) )
			{
			RFC822Header *pHeader = new RFC822Header( pValue );
			if ( !pHeader || !pHeader->IsOK() )
				{
				os << "Bad HTTPEquiv expression, '" << pValue << "'" << ends;
				CONFIG_ERROR( Object(), os.str() );
				delete pHeader;
				return 0;
				}
			else
				{
				lHTTPEquivalents.Append( (DblList::type)pHeader );
				};
			}
		else if ( !PIUtil_stricmp( KEY_CONF_INMULTIPARTRESPONSE, pVariable ) )
			{
			if ( !PIUtil_stricmp( pValue, VALUE_YES ) )
				{ iMultipart = 1; };	
			}
		else
			{
			os << "Unknown directive '" << pVariable <<
				"'" << ends;
			CONFIG_ERROR( Object(), os.str() );
			return 0;
			};

		return 1;
		};

public:
	SendPi3Expression( PIObject *pObject, int iArgc, const char *ppArgv[] )
	:	HandlerBaseHTTP( pObject ),
		pExpr( 0 ),
		iBufferSize( -1 ),
		iMultipart( 0 )
		{
		ReadParameters( iArgc, ppArgv );

		/* --- 
		check values are valid
		--- */
		if ( !pExpr )
			{
			CONFIG_ERROR( Object(), "SendPi3Expression: 'Pi3Expression' \
not defined or error in definition." );
			SetOK( 0 );
			return;
			};

		};

	virtual ~SendPi3Expression()
		{
		for( DblListIterator j( lHTTPEquivalents ); !j.BadIndex(); j++)
			{ delete (RFC822Header *)j.Current(); };
		Pi3Expression_delete( pExpr );
		};

	/* --- handle a request --- */
	int Handle( int iPhase, PIHTTP &tPIHTTP, PIIOBuffer &tB )
		{
		assert( pExpr );

		if ( iPhase!=PH_HANDLE )
			{
			HTTPCore_logError( &tPIHTTP, "MapToErrorDocument: \
Configuration error, \
'MapToErrorDocument' handler may only be used for 'MAPPING' phase, not '%s' \
phase.",
			HTTPUtil_phaseNumberToName( iPhase ) );
			return PIAPI_ERROR;
			};

		/* --- sanity --- */
		if ( !pExpr )
			{ return PIAPI_ERROR; };

		PIDB *pR = tPIHTTP.pResponseDB;

		/* --- evaluate expression --- */
		char *pBuffer = (char *)PIHTTP_allocMem( &tPIHTTP, INITIAL_BUFFER_SIZE);
		int iLen = Pi3Expression_write( pExpr, &tPIHTTP, 0, pBuffer,
			INITIAL_BUFFER_SIZE );
		if ( iLen==-1 )
			{
			/* --- error --- */
			HTTPCore_logError( &tPIHTTP, "SendPi3Expression: Failed \
to write expression into buffer." );
			return HTTPUtil_doHTTPError( &tPIHTTP, ST_INTERNALERROR );
			};

		int iSizeToSend = iLen;
		if ( iBufferSize!=-1 && iSizeToSend>iBufferSize )
			{ iSizeToSend = iBufferSize; };
		if ( iSizeToSend>INITIAL_BUFFER_SIZE )
			{
			/* --- get a bigger buffer and try again --- */
			pBuffer = (char *)PIHTTP_allocMem( &tPIHTTP, iSizeToSend );
			int iTmp = Pi3Expression_write( pExpr, &tPIHTTP, 0, pBuffer,
				iSizeToSend );
			assert( iTmp==iLen );
			};

		/* --- set headers --- */
		enum { BUF_SIZE=63 };
		char szBuf[BUF_SIZE+1];
		sprintf( szBuf, "%d", iSizeToSend );
		PIDB_replace( pR, PIDBTYPE_RFC822, KEY_HTTP_CONTENTLENGTH,
			(void *)szBuf, 0 );
		PIDB_replace( pR, PIDBTYPE_RFC822, KEY_HTTP_CONTENTTYPE,
			(void *)"text/plain", 0 );
		for( DblListIterator i( lHTTPEquivalents ); !i.BadIndex(); i++)
			{
			((RFC822Header *)i.Current())->ReplaceHeader( pR );
			};

		/* --- Send headers --- */
		if ( !iMultipart )
			{
			tPIHTTP.iStatus = ST_OK;
			if ( HTTPCore_sendGeneralHeaders( &tPIHTTP ) )
				{ goto send_error; };
			};
		if ( HTTPCore_sendEntityHeaders( &tPIHTTP, pR ) )
			{ goto send_error; };

		/* --- send response --- */
		PIIOBuffer_write( &tB, pBuffer, iSizeToSend, PIIOBUF_NONE );

		return iMultipart ? PIAPI_CONTINUE : PIAPI_COMPLETED;

send_error:

		/* --- assume connectivity gone, no HTTP status, return ERROR --- */
		HTTPCore_logError( &tPIHTTP, "SendPi3Expression: Error \
sending response to client." );
		return PIAPI_ERROR;
		};
};

/*____________________________________________________________________________*\
 *
 Function:
 Synopsis:
 Description:
\*____________________________________________________________________________*/
PUBLIC_PIAPI int SendPi3Expression_constructor( PIObject *pObj,
	int iArgc, const char *ppArgv[] )
{
	return HandlerBaseHTTP_constructor( pObj, PI_NEW( SendPi3Expression( pObj,
		iArgc, ppArgv ) ) );
}

#if 0
/*___+++CNF_BEGIN+++___*/
	<Class>
		Name SendPi3ExpressionClass
		Type LogicExtension
		Library HTTP
		OnClassLoad HandlerBaseHTTP_onClassLoad
		Constructor SendPi3Expression_constructor
		CopyConstructor HandlerBaseHTTP_copyConstructor
		Destructor HandlerBaseHTTP_destructor
		Execute HandlerBaseHTTP_execute
	</Class>

	<Object>
		Name SendPi3Expression
		Class SendPi3ExpressionClass
	</Object>

/*___+++CNF_END+++___*/
#endif

⌨️ 快捷键说明

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