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

📄 pi3app.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/EnhPi3/Pi3App.cpp,v $
 * $Date: 2003/05/13 18:41:58 $
 *
 Description:
\*____________________________________________________________________________*/
//$SourceTop:$

#include <assert.h>
#include <iostream.h>
#include <fstream.h>
#include <stdlib.h>
#include <signal.h>
#include <stdio.h>

#include <windowsx.h>
#include "Common.h"

#include "Pi2API.h"
#include "PIStrStr.h"
#include "StrToken.h"
#include "MiscUtil.h"
#include "resrc1.h"

/*____________________________________________________________________________*\
 *
 Description:
	All globals are global to this file only.
\*____________________________________________________________________________*/
static int iRet;						/* global application return code */
static int __iArgc;					/* global argument count */
static const char **__ppArgv;			/* global arguments */
static PIObject *___pGlobalObject = 0;	/* Pi3 object 'main' */
static HANDLE ___hSema;					/* termination semaphore */					
static HINSTANCE __hInstance = 0;		/* global hInstance */

/* ---
Output a diagnostic message
--- */
#define ERROR_TITLE "Pi3"
#define MSG_OUT(msg) MessageBox( NULL, (msg), ERROR_TITLE, MB_OK ); 
#define DIAG_OUT(msg,db,type)								\
	{														\
	PIOStrStream __os;										\
	if ( *(msg) ) { __os << (msg) << endl; }				\
	const char *__pTmpFile = tmpnam( NULL );				\
	PILog_writeDiagnostics( (db), (type), __pTmpFile );		\
	ifstream __ifs( __pTmpFile );							\
	enum { __BUF_SIZE=4095 };								\
	char __szBuf[__BUF_SIZE+1];								\
	while( __ifs.good() && !__ifs.eof() )					\
		{													\
		__ifs.getline( __szBuf, __BUF_SIZE );				\
		__os << __szBuf << endl;							\
		};													\
	__ifs.close();											\
	__os << ends;											\
	MSG_OUT( __os.str() );									\
	remove( __pTmpFile );									\
	};

/* #define D { cerr << PIPlatform_getProcessId() << ": " << __FILE__ << ", " \
**	<< __LINE__ << endl; };
*/
#define D

/*____________________________________________________________________________*\
 *
 Function:
 Synopsis:
 Description:
	The function that is called when the windowing terminates.
	(User selects shutdown server...).
\*____________________________________________________________________________*/
void fnOnWindowingTermination( void *pData )
{
	HANDLE hSema = (HANDLE)pData;
	if ( hSema )
		{
		/* --- unlock the mutex to allow termination --- */
		::ReleaseSemaphore( hSema, 1, NULL );
		};
}

/*____________________________________________________________________________*\
 *
 Function:
 Synopsis:
 Description:
\*____________________________________________________________________________*/
void Usage()
{
	const char *pProgram = ( __ppArgv && __ppArgv[0] ) ? __ppArgv[0] : "";
	PIOStrStream os;
	os << "Usage: " << pProgram << " <configuration file>" << ends;
	MSG_OUT( os.str() );
}

/*____________________________________________________________________________*\
 *
 Function:
 Synopsis:
 Description:
\*____________________________________________________________________________*/
void DoApp( PIDB *pDB )
{
	if ( __iArgc < 2 )
		{
		Usage();
		return;
		};

	/*
	** Load configuration file
	*/
	PIConfig *pConfigDB = 0;
	const char *pFile = __ppArgv[1];
	if ( PIConfig_loadConfigurationFile( pDB, pFile, &pConfigDB ) )
		{
		PIOStrStream os;
		os << "Unable to load configuration file: '"
			<< ( pFile ? pFile : "" )
			<< "'" << ends;
		DIAG_OUT( os.str(), pDB, PILOG_ALL );
		return;
		};

	/*
	** Load object 'main' and nested objects
	*/
	PIObject *pObject = PIObject_load( pDB, pConfigDB, "Main", 0, 0 );
	if ( !pObject )
		{
		DIAG_OUT( "", pDB, PILOG_ALL );
		return;
		};

	___pGlobalObject = pObject;

#if 0
	/* ---
 	Delete the configuration DB
	--- */
/*	PIDB_delete( (PIDB *)pConfigDB );
**	PIDBIterator *pIter = PIDB_getIterator( (PIDB *)pConfigDB, PIDBTYPE_TREE,
*/		PIDBKEY_CONFIGURATION, 0 );
	PIDBIterator *pIter = PIDB_getIterator( pDB, PIDBTYPE_TREE,
		0, 0 );
	if ( pIter )
		{
		for( ;	PIDBIterator_atValidElement( pIter ); 
				PIDBIterator_next( pIter ) )
			{
			PIDBIterator_removeCurrent( pIter );
			};
		PIDBIterator_delete( pIter );
		};
#endif

#if POSIX
	PILog_writeDiagnostics( pDB, PILOG_WARNING, 0 );
#else
	/* --- nothing else gets the warnings --- */
#endif

	/* --- send subsequent messages to error stream --- */
	PILog_newSink( PILOG_STDERR, 0 );

	/*
	** Create the windowing thread
	*/
	if ( !Pi3_startWindowing( __hInstance, __ppArgv, 
		fnOnWindowingTermination, ___hSema ) )
		{
		/* --- failed --- */
		MSG_OUT( "Internal error: failed to create windowing thread" );
		return;
		}

	/*
	** Unload any of that configuration file stuff
	*/
	if ( __pConfig )	
		{
		AD_destroyConfig( __pConfig );
		__pConfig = 0;
		};

	/*
	** Run object 'main' to run the server
	*/
	if ( PILogic_execute( pObject, __iArgc, __ppArgv ) )
		{
		DIAG_OUT( "", pDB, PILOG_ALL );
		return;
		};

	iRet = 0;
}

/*____________________________________________________________________________*\
 *
 Function:
 Synopsis:
 Description:
	Main function of execution thread. 
\*____________________________________________________________________________*/
void App( PIDB *pDB )
{
	DoApp( pDB );

	if ( ___hSema )
		{ ::ReleaseSemaphore( ___hSema, 1, NULL ); };
}

/*____________________________________________________________________________*\
 *
 Function:
 Synopsis:
 Description:
\*____________________________________________________________________________*/
void ThreadFn( PIDB *pDB )
{
	iRet = -1;

	/*
	** Semaphore name for application is the full
	** path to the configuration file in upper case
	*/
	PIString sSemaphoreName;
	CTRL_semaphoreNameFromConfigPath( __ppArgv[1], sSemaphoreName );
	const char *pSemaphoreName = sSemaphoreName;

	/*
	** Check can the semaphore be opened, meaning
	** that the server is already running
	*/
	if ( CTRL_isPi3Running( pSemaphoreName ) )
		{
		/*
		** Server is running, quit this server
		*/
		iRet = 0;
		return;
		};

	/*
	** Create execution thread object
	*/
	PIThread *pThread = PIThread_new( 0, 0 );
	if ( !pThread )
		{
		PIOStrStream os;
		os << "Internal error: could not allocate thread object" << ends;
		MSG_OUT( os.str() );
		return;
		};

	/*
	** Create termination semaphore
	*/
	___hSema = ::CreateSemaphore( NULL, 0, 1, pSemaphoreName );

	if ( !___hSema )
		{
		PIOStrStream os;
		DWORD dwLastError = ::GetLastError();
		os << "Internal error: could not allocate mutex - Win32 error " <<
			dwLastError << ends;
		MSG_OUT( os.str() );
		return;
		};

	/*
	** Begin the thread to run the server
	*/
	if ( PIThread_begin( pThread,
			(unsigned long (*)(unsigned long))App,
			(unsigned long)pDB,
			PITHREAD_PRIORITY_MED, 0 ) )
		{
		PIOStrStream os;
		os << "Internal error: could not begin thread" << ends;
		MSG_OUT( os.str() );
		return;
		};

	/* --- block on the semaphore --- */
	if ( ::WaitForSingleObject( ___hSema, INFINITE )==WAIT_FAILED )
		{
		/* --- failed to lock --- */
		PIOStrStream os;
		os << "Internal error: failed to lock mutex" << ends;
		MSG_OUT( os.str() );
		return;
		};

	/* --- lock has been released --- */
	iRet = 0;

	/* --- kill main thread --- */
	PIThread_delete( pThread );	

	/* ---
	Terminate windowing if necessary
	--- */
	Pi3_endWindowing();

	CloseHandle( ___hSema );

	if ( ___pGlobalObject )
		{
		PIObject_delete( ___pGlobalObject, 0, 0 );
		___pGlobalObject = 0;
		};
}

/*____________________________________________________________________________*\
 *
 Function:
 Synopsis:
 Description:
\*____________________________________________________________________________*/
static HWND __hWndDlgOK = 0;
static HWND __hWndDlgPasswd = 0;
struct passphrase {
	char **buf;
	int bufsize;
} * __passphrase;

static BOOL CALLBACK fnPassDialogProc(HWND hDlg, UINT uMsg, WPARAM wParam,
	LPARAM lParam)
{
	switch (uMsg)
		{
		case WM_INITDIALOG:
			__hWndDlgOK = GetDlgItem( hDlg, IDOK );
			__hWndDlgPasswd = GetDlgItem( hDlg, IDC_PASSWORD );
			__passphrase = (passphrase *)lParam;
			assert( __hWndDlgOK && __hWndDlgPasswd );
			SendMessage( __hWndDlgPasswd, EM_SETLIMITTEXT, __passphrase->bufsize, 0 );
			EnableWindow( __hWndDlgOK, FALSE );
			break;

		case WM_COMMAND:
			switch (GET_WM_COMMAND_ID(wParam, lParam))
				{
				case IDOK:
					{
					/*
					** Get content of edit field
					*/
					SendMessage( __hWndDlgPasswd, WM_GETTEXT, __passphrase->bufsize,
						(LPARAM)*(__passphrase->buf) );
					EndDialog( hDlg, 1 );
					break;
					}

				case IDCANCEL:
					EndDialog( hDlg, 0 );
					break;

				case IDC_PASSWORD:
					if ( GET_WM_COMMAND_CMD(wParam, lParam)==EN_CHANGE )
						{
						if ( SendMessage( GET_WM_COMMAND_HWND(wParam, lParam ), EM_LINELENGTH,
							0, 0 )>0 )
							{ EnableWindow( __hWndDlgOK, TRUE ); }
						else
							{ EnableWindow( __hWndDlgOK, FALSE ); }
						}
					else
						return (FALSE);
					break;

				default:;
				};

		default:
			return (FALSE);
		};

	return (TRUE);
}

int fnPassPhraseDlg(char *buf, int bufsize)
{
	passphrase pphrase;
	pphrase.buf = &buf;
	pphrase.bufsize = bufsize;
	if (DialogBoxParam(
		__hInstance,
		MAKEINTRESOURCE(IDD_PASSPHRASE),
		NULL,
		(DLGPROC)fnPassDialogProc,
		(LPARAM)&pphrase
	) != -1 )
		{
		return strlen(buf);
		}
	else
		return -1;
}

typedef void REGPWDDLG(void *pPasswdDlg);

/*____________________________________________________________________________*\
 *
 Function:
 Synopsis:
 Description:
\*____________________________________________________________________________*/
void RegisterPassPhraseDialog()
{
	HINSTANCE hSSL = LoadLibrary("SSL.dll");
	if (hSSL)
	{
	REGPWDDLG *regPwdDlg = (REGPWDDLG *)GetProcAddress(hSSL, "SSL_register_PassphraseDlg");
	if (regPwdDlg!=NULL) regPwdDlg(&fnPassPhraseDlg);
	}

}

/*____________________________________________________________________________*\
 *
 Function:
 Synopsis:
 Description:
\*____________________________________________________________________________*/
int Pi3_main( HINSTANCE hInstance, int iArgc, 
	const char *ppArgv[] )
{
	__hInstance = hInstance;

	__iArgc = iArgc;
	__ppArgv = ppArgv;

	/*
	** register ssl private key passphrase dialog 
	*/
	RegisterPassPhraseDialog();

	/*
	** Load configuration 
	*/
	AD_hourglassInit();
	__pConfig = AD_loadConfig( __ppArgv[1] );

	if ( PIProgram_enter( ppArgv[0], PIPROGRAM_VERSION_1_0, ThreadFn ) )
		{
		PIOStrStream os;
		os << "Program_enter() failed." << ends;
		MessageBox( NULL, os.str(), ERROR_TITLE, MB_OK );
		iRet = 1;
		};

	if ( __pConfig )	
		{ AD_destroyConfig( __pConfig ); };

	AD_hourglassDestroy();

	return iRet;
}

⌨️ 快捷键说明

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