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

📄 bscauth.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/BscAuth.cpp,v $
 * $Date: 2003/05/13 18:42:01 $
 *
 Description:
	Basic authentication module.

\*____________________________________________________________________________*/
/* $SourceTop:$ */

#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <iostream.h>

#include "Pi3API.h"
#include "Base64.h"

/*____________________________________________________________________________*\
 *
 Description:
\*____________________________________________________________________________*/
/*
#define D { cerr << __FILE__ << ", " << __LINE__ << endl; }
*/
#define D

/*____________________________________________________________________________*\
 *
 Description:
\*____________________________________________________________________________*/
#define KEY_CONF_REALM		"Realm"
#define KEY_CONF_BASE64		"Base64"
#define BASIC_AUTH_TYPE		"Basic"

/*____________________________________________________________________________*\
 *
 Description:
	Documentation
\*____________________________________________________________________________*/
#if 0
	/*
	** HTML documentation for this handler
	*/
/*___+++HTMLDOC_BEGIN+++___*/
Name:
	BasicAuth

Description:
    Provide basic authentication.

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

<TR>
<TD>Realm
<TD>+
<TD>A string
<TD>Realm to authenticate
<TD>Realm="Admin"

<TR>
<TD>Base64
<TD>+
<TD>A base64 encoded string
<TD>Encoding of username and password
<TD>Base64="anJveTpoZWxsbw=="

</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>
	Base64
</H5>
Specify a base64 encoded pattern of username and password to be matched
against browser username and passwords. This directive can be repeated
multiple times to specify multiple valid username and passwords.

<H5>
	Realm
</H5>
Realm to be authenticated by this handler.

Phase:
	CHECKAUTH

Returns:
	PIAPI_COMPLETED if authentication passed. INT_REDIRECT if the
	status was set to 401 to challenge, PIAPI_CONTINUE if this 
	handler choose to take no action and PIAPI_ERROR if this handler
	was invoked for a phase other than CHECKAUTH.

Note:
Example:
	<PRE>
	&lt;Object&gt;
		Name BasicAuth
		Class BasicAuthClass
	&lt;/Object&gt;

	&lt;Object&gt;
		...
		Handle BasicAuth 
		...
	&lt;/Object&gt;
	</PRE>
/*___+++HTMLDOC_END+++___*/
#endif

/*____________________________________________________________________________*\
 *
 Description:
\*____________________________________________________________________________*/
struct _BasicAuth
{
	char *pRealm;
	PIDB *pBase64DB;
};
typedef struct _BasicAuth BasicAuth;

/*____________________________________________________________________________*\
 *
 Function:
 Synopsis:
 Description:
\*____________________________________________________________________________*/
int BasicAuth_fnParameter( void *pData, const char *pVar, const char *pVal,
	const char *pWhere )
{
	PIObject *pObject = (PIObject *)pData;
	BasicAuth *pBasicAuth = (BasicAuth *)PIObject_getUserData( pObject );
	(void)pBasicAuth;
	assert( pVar );
	assert( pVal );

	if ( !PIUtil_stricmp( pVar, KEY_CONF_REALM ) )
		{
		pBasicAuth->pRealm = PIUtil_strdup( pVal );
		}
	else if ( !PIUtil_stricmp( pVar, KEY_CONF_BASE64 ) )
		{
		assert( pBasicAuth->pBase64DB );
		PIDB_add( pBasicAuth->pBase64DB, PIDBTYPE_OPAQUE, pVal, (void *)1, 0 );
		}
	else
		{
		/* ---
		Configuration error
		--- */
		PILog_addMessage(
			PIObject_getDB( pObject ),
			PIObject_getConfigurationDB( pObject ),
			PILOG_ERROR, "BasicAuth: %sUnknown directive '%s'.", pWhere, pVar );
		return 0;
		};
	return 1;
}

/*____________________________________________________________________________*\
 *
 Function:
 Synopsis:
 Description:
\*____________________________________________________________________________*/
int BasicAuth_init( BasicAuth *pBasicAuth, PIObject *pObject, int iArgc,
	const char *ppArgv[] )
{
	int iRet = PIObject_readParameters( pObject, iArgc, ppArgv,
		BasicAuth_fnParameter, pObject );

	/* --- set defaults --- */
	if ( iRet )
		{
		if ( !pBasicAuth->pRealm )
			{ pBasicAuth->pRealm = PIUtil_strdup( "" ); };
		};

	return iRet;
}

/*____________________________________________________________________________*\
 *
 Function:
 Synopsis:
 Description:
\*____________________________________________________________________________*/
PUBLIC_PIAPI int BasicAuth_onClassLoad( PIClass_LoadAction, PIDB * )
{
	return PIAPI_COMPLETED;
}

/*____________________________________________________________________________*\
 *
 Function:
 Synopsis:
 Description:
\*____________________________________________________________________________*/
PUBLIC_PIAPI int BasicAuth_constructor( PIObject *pObj,
	int iArgc, const char *ppArgv[] )
{
	BasicAuth *pBasicAuth = (BasicAuth *)
		PIUtil_malloc( sizeof( BasicAuth ) );
	pBasicAuth->pBase64DB = PIDB_new( 0, "Base64" );
	PIObject_setUserData( pObj, pBasicAuth );
	if ( !BasicAuth_init( pBasicAuth, pObj, iArgc, ppArgv ) )
		{
		return PIAPI_ERROR;
		};
	return PIAPI_COMPLETED;
}

/*____________________________________________________________________________*\
 *
 Function:
 Synopsis:
 Description:
\*____________________________________________________________________________*/
PUBLIC_PIAPI int BasicAuth_copyConstructor( PIObject *, int,
	const char *[] )
{
	return PIAPI_ERROR;
}

/*____________________________________________________________________________*\
 *
 Function:
 Synopsis:
 Description:
\*____________________________________________________________________________*/
PUBLIC_PIAPI int BasicAuth_execute( PIObject *pObj, int iArgc,
		const char *ppArgv[] )
{
	PIHTTP *pPIHTTP;
	BasicAuth *pBasicAuth;
	const char *pRealm;
	char *pAuth;

	if ( iArgc<1 )
		{ return PIAPI_ERROR; };

	pPIHTTP = (PIHTTP *)*ppArgv;

	if ( pPIHTTP->ciPhase!=PH_CHECKAUTH )
		{ return PIAPI_ERROR; };

	pBasicAuth = (BasicAuth *)PIObject_getUserData( pObj );

	/* ---
	Get the realm
	--- */
	pRealm = (const char *)PIDB_lookup( pPIHTTP->pResponseDB, PIDBTYPE_STRING,
		KEY_INT_AUTHENTICATIONREALM, 0 );

	if ( !pRealm || strcmp( pRealm, pBasicAuth->pRealm ) )
		{
		/* ---
		Not for this handler to authenticate
		--- */
		return PIAPI_CONTINUE;
		};

	/*
	** This realm applies. Set the authentication type to 'Basic'
	*/
	PIDB_replace( pPIHTTP->pResponseDB, PIDBTYPE_STRING, KEY_INT_AUTHTYPE,
		(void *)BASIC_AUTH_TYPE, 0 );

	/*
	** Get browser authentication string
	*/
	const char *pAuthenticate = (const char *)PIDB_lookup(
		pPIHTTP->pRequestDB, PIDBTYPE_RFC822, KEY_HTTP_AUTHORIZATION, 0 );
	if ( pAuthenticate )
		{
		/*
		** Check authentication string
		*/
		if ( !strncmp( pAuthenticate, "Basic ", 6 ) )
			{
			/*
			** Check to see if this is an acceptable base64 encoding
			*/
			const char *pBase64 = &( pAuthenticate[6] );
			if ( PIDB_lookup( pBasicAuth->pBase64DB, PIDBTYPE_OPAQUE,
				pBase64, 0 ) )
				{
					/*
					** Authenticated
					*/
					char auth[256];
					Base64Decode( pBase64, auth, sizeof( auth ));
					char *tok = strtok( auth, ":" );
					if ( tok != NULL )
						{
						PIDB_replace( pPIHTTP->pResponseDB, PIDBTYPE_STRING,
							KEY_INT_REMOTEUSER, tok, 0 );
						tok = strtok( NULL, ":" );
						if ( tok != NULL )
							{
								PIDB_replace( pPIHTTP->pResponseDB, PIDBTYPE_STRING,
									KEY_INT_AUTHPASS, tok, 0 );
							};
						};
						
					return PIAPI_COMPLETED;
				};
			};
		};

	/* ---
	Challenge
	--- */
	pAuth = (char *)PIHTTP_allocMem( pPIHTTP, sizeof( "Basic realm=\"\"" )
			+ strlen( pBasicAuth->pRealm ) + 1 );
	sprintf( pAuth, "Basic realm=\"%s\"", pBasicAuth->pRealm );
	PIDB_replace( pPIHTTP->pResponseDB, PIDBTYPE_RFC822,
		KEY_HTTP_WWW_AUTHENTICATE, pAuth, 0 );

	/* ---
	Read the rest of the request
	--- */
	if ( void *pLength = PIDB_lookup( pPIHTTP->pRequestDB, PIDBTYPE_RFC822,
		KEY_HTTP_CONTENTLENGTH, 0 ))
		{
		int iLen;
		const char *pBuf = PIIOBuffer_read( pPIHTTP->pBuffer, &iLen );
		int toRead = atoi((const char *)pLength) - iLen;
		while( toRead )
			{
			pBuf = PIIOBuffer_read( pPIHTTP->pBuffer, &iLen );
			toRead -= iLen;
			};
		}

	/* ---
	Redirect because of authentication failure
	--- */
	return HTTPUtil_doHTTPError( pPIHTTP, ST_UNAUTHORIZED );
}

/*____________________________________________________________________________*\
 *
 Function:
 Synopsis:
 Description:
\*____________________________________________________________________________*/
PUBLIC_PIAPI int BasicAuth_destructor( PIObject *pObj, int, const char *[] )
{
	BasicAuth *pAuth = (BasicAuth *)PIObject_getUserData( pObj );
	if ( pAuth->pRealm )
		{ PIUtil_free( pAuth->pRealm ); };
	PIDB_delete( pAuth->pBase64DB );
	PIUtil_free( pAuth );
	return PIAPI_COMPLETED;
}

#if 0
/*___+++CNF_BEGIN+++___*/
	<Class>
		Name BasicAuthClass
		Type LogicExtension
		Library HTTP
		OnClassLoad BasicAuth_onClassLoad
		Constructor BasicAuth_constructor
		CopyConstructor BasicAuth_copyConstructor
		Destructor BasicAuth_destructor
		Execute BasicAuth_execute
	</Class>

	<Object>
		Name BasicAuth
		Class BasicAuthClass
	</Object>

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

⌨️ 快捷键说明

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