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

📄 flexhand.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/FlexHand.cpp,v $
 * $Date: 2003/05/13 18:42:03 $
 *
 Description:
	Flexible handler.

\*____________________________________________________________________________*/
//$SourceTop:$

#include <ctype.h>

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

/*____________________________________________________________________________*\
 *
 Description:
	Configuration and documentation source.
\*____________________________________________________________________________*/
#if 0
	/*
	** HTML documentation for this handler
	*/
/*___+++HTMLDOC_BEGIN+++___*/
Name:
	FlexibleHandler

Description:
	Dispatches requests to multiple handlers depending on the request
	phase.

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

<TR>
<TD>Condition
<TD>-
<TD>A Pi3Expression
<TD>Makes handler conditional
<TD>Condition="&cmp(dblookup(response,string,ObjectMap),Scripts)"

<TR>
<TD>Handlers
<TD>-
<TD>An optional condition followed by a list of handler names
<TD>Handles invoked for all phases
<TD>Handlers "yes" "Errors Scripts Default"

<TR>
<TD>&lt;phase&gt;
<TD>-
<TD>A phase name followed by an optional condition and a handler
<TD>Define a handler for a phase
<TD>Destroy "&not($d)" DeleteTemporaryFiles

</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>
	Condition
</H5>
A Pi3Expression which must evaluate to true before any of the specified 
handlers are invoked to handle the request.
This directive can be repeat multiple times to specify multiple conditions
which must all evaluate to true before the any handlers are invoked.

<H5>
	Handlers
</H5>
An optional statement of the form 'Condition=&lt;Pi3Expression&gt;' followed by a list of handler
objects. The list of handler objects may be optionally quoted.
These handlers are 
invoked for all phases of request processing.

<H5>
	&lt;phase&gt;
</H5>
An optional statement of the form 'Condition=&lt;Pi3Expression&gt;' followed
by a handler name and parameters.

Phase:
	All

Returns:
	PIAPI_COMPLETED if the request from processed, PIAPI_CONTINUE otherwise.
	PIAPI_ERROR or PIAPI_ABORT if any sub-handler returned these error
	codes.

Example:
	<PRE>
	&lt;Object&gt;
		Name FlexibleHandler
		Class FlexibleHandlerClass
		Condition "&cmp(dblookup(response,string,ObjectMap),Scripts)"
		Handlers Condition="&lt;expr&gt;" "Errors Scripts Default"
		Init ...
		Headers ...
		HostMap ...
		Mapping ...
		CheckPath ...
		CheckAccess ...
		CheckType ...
		Handle ...
		Handle Condition="&lt;expr&gt;" ...
		Handle ...
		Log Condition="&lt;expr&gt;" ...
		Destroy Condition="&lt;expr&gt;" ...
	&lt;/Object&gt;

	&lt;Object&gt;
		...
		Handle FlexibleHandler 
		...
	&lt;/Object&gt;

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

/*____________________________________________________________________________*\
 *
 Description:
\*____________________________________________________________________________*/
#define KEY_CONF_CONDITION		"Condition"
#define KEY_CONF_HANDLERS		"Handlers"

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

	/* ---
	Configuration data
	--- */
	DblList lConditions;			/* condition list */
	DblList lToDelete;				/* handlers to delete */
	DblList lHandlers[PH_NUMBER];	/* phase specific handlers */

	/* --- class to wrap handler with condition --- */
	class Handler
	{
	public:
		PIObject *pHandler;			/* handler object to execute */
		Pi3Expression *pCondition;	/* must be satisfied */

		Handler( PIObject *pTheHandler, Pi3Expression *pTheCondition )
		:	pHandler( pTheHandler ), pCondition( pTheCondition )
			{};

		~Handler()
			{
			Pi3Expression_delete( pCondition );
			PIObject_delete( pHandler, 0, 0 );
			};
	};

protected:
	int Parameter( const char *pVariable, const char *pValue,
		const char *pWhere )
		{
		assert( pVariable && pValue );
		PIOStrStream os;
		os << pWhere << "FlexibleHandler: ";

		Pi3Expression *pCondition = 0;

		/* ---
		See if the value starts with a quote to make it conditional
		--- */
		if ( !PIUtil_strncmpi( pValue, "Condition=", 10 ) ) // =='"' )
			{
			/* --- skip Condition=... --- */
			pValue = &( pValue[10] );

			/* --- scan to first space, ignoring spaces in '"' --- */
			int i;
			int iQuoted = 0;
			for(i=0; pValue[i] && ( !(isspace(pValue[i])) || iQuoted ) ; i++)
				{
				if ( pValue[i]=='"' )
					{ iQuoted = ( iQuoted ? 0 : 1 ); };
				};

			/* --- i now points at first space after condition --- */
			PIString sExpression( pValue, i );
			DeQuote tExpression( sExpression );
			Pi3String *pError = Pi3String_new( 0 );
			Pi3Expression *pTmp = Pi3Expression_new( tExpression, 0, pError );
			PIString sError( Pi3String_getPtr( pError ) );
			Pi3String_delete( pError );
			if ( !pTmp )
				{
				os << "Error parsing expression: " << sError << ends;
				CONFIG_ERR( Object(), os.str() );
				PI_DELETE( pTmp );
				return 0;
				};
			pCondition = pTmp;

			/* --- skip leading spaces --- */
			for( ; pValue[i] && (isspace(pValue[i])); i++ );
			pValue = &( pValue[i] );
			};

		if ( !PIUtil_stricmp( KEY_CONF_CONDITION, pVariable ) )
			{
			Pi3String *pError = Pi3String_new( 0 );
			Pi3Expression *pCond = Pi3Expression_new( pValue, 0, pError );
			PIString sError( Pi3String_getPtr( pError ) );
			Pi3String_delete( pError );
			if ( !pCond )
				{
				os << "Syntax error in condition: " << sError << ends;
				CONFIG_ERR( Object(), os.str() );
				Pi3Expression_delete( pCondition );
				return 0;
				};
			lConditions.Append( (DblList::type)pCond );
			}
		else if ( !PIUtil_stricmp( KEY_CONF_HANDLERS, pVariable ) )
			{
			StringTokenizer tTokens( pValue, " " );
			for( int i=0; i<tTokens.NumTokens(); i++)
				{
				const char *pToken = tTokens.GetToken( i );
				int j;
				/* --- skip leading space --- */
				for( j=0; pToken[j] && (isspace(pToken[j])); j++ );
				pToken = &( pToken[j] );

				/* --- skip trailing spaces --- */
				for( j=0; pToken[j] && !(isspace(pToken[j])); j++ );
				PIString sHandlerName( pToken, j );

				PIObject *pHandler = PIObject_load(
					PIObject_getDB( Object() ), 0, sHandlerName, 0, 0 );
				if ( !pHandler )
					{
					/* --- message already set by 'PIObject_load()' --- */
					Pi3Expression_delete( pCondition );
					return 0;
					};

				Handler *pNewHandler = PI_NEW( Handler( pHandler, pCondition )
					);

				/* --- add to all phases --- */
				for( int k=0; k<PH_NUMBER; k++)
					{
					lHandlers[k].Append( (DblList::type)pNewHandler );
					};
				lToDelete.Append( (DblList::type)pNewHandler );
				};
			}
		else
			{
			/* ---
			See if this is a valid phase name
			--- */
			int iPhase = HTTPUtil_phaseNameToNumber( pVariable );
			if ( iPhase==PH_INVALID )
				{
				os << "Unknown phase '" << pVariable << "'" << ends;
				CONFIG_ERR( Object(), os.str() );
				Pi3Expression_delete( pCondition );
				return 0;
				};

			/* --- iPhase is a valid phase, try to load it --- */
			PIObject *pHandler = PIObject_loadFromLine( 
				PIObject_getDB( Object() ),
				PIObject_getConfigurationDB( Object() ),
				pValue );
			if ( !pHandler )
				{
				Pi3Expression_delete( pCondition );
				return 0;
				};

			Handler *pNewHandler = PI_NEW( Handler( pHandler, pCondition ) );

			/* --- append to the list of handlers for this phase --- */
			lHandlers[iPhase].Append( (DblList::type)pNewHandler );
			lToDelete.Append( (DblList::type)pNewHandler );
			};

		return 1;
		};

public:
	FlexibleHandler( PIObject *pObject, int iArgc, const char *ppArgv[] )
	:	HandlerBaseHTTP( pObject )
		{
		ReadParameters( iArgc, ppArgv );
		};

	~FlexibleHandler()
		{
		for( DblListIterator k( lToDelete ); !k.BadIndex(); k++ )
			{ PI_DELETE( (Handler *)k.Current() ); };
		for( DblListIterator j( lConditions ); !j.BadIndex(); j++ )
			{ Pi3Expression_delete( (Pi3Expression *)j.Current() ); };
		};

	/* ---
	Little class for passing arguments
	--- */
	class HandlerArgs
	{
	public:
		DblListIterator *pIter;
		PIHTTP *pPIHTTP;

		HandlerArgs( DblListIterator *pTheIterator, PIHTTP *pThePIHTTP )
		:	pIter( pTheIterator ), pPIHTTP( pThePIHTTP )
			{};
	};
	static PIObject *GetNextHandler( void *pArg )
		{
		HandlerArgs *pArgs = (HandlerArgs *)pArg;
		DblListIterator *pIter = pArgs->pIter;
		assert( pIter );
		if ( pIter->BadIndex() )
			{ return 0; };
		Handler *pHandler = (Handler *)pIter->Current();
		assert( pHandler );
		(*pIter)++;

		/* ---
		if a condition exists and its false, recurse to skip this
		handler
		--- */
		if ( pHandler->pCondition &&
			!Pi3Expression_write( pHandler->pCondition, pArgs->pPIHTTP, 0, 0,
				0 ) )
			{ return GetNextHandler( pArg ); };

		PIObject *pObject = pHandler->pHandler;
		return pObject;
		};


	int Handle( int iPhase, PIHTTP &tPIHTTP, PIIOBuffer & )
		{
		/* ---
		See can all conditions be satisfied 
		--- */
		for( DblListIterator i( lConditions ); !i.BadIndex(); i++ )
			{ 
			Pi3Expression *pCond = (Pi3Expression *)i.Current();
			assert( pCond );		/* --- sanity only --- */
			if ( !Pi3Expression_write( pCond, &tPIHTTP, 0, 0, 0 ) )
				{
				return PIAPI_CONTINUE;
				};
			};

		/* ---
		Conditions satisfied, execute handlers
		--- */
		DblListIterator j( lHandlers[iPhase] );
		HandlerArgs tArgs( &j, &tPIHTTP );
		return HTTPCore_executePhase( &tPIHTTP, GetNextHandler, &tArgs );
		};
};

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

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

	<Object>
		Name FlexibleHandler
		Class FlexibleHandlerClass
	</Object>

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

⌨️ 快捷键说明

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