base64.c

来自「mini http server,可以集成嵌入到程序中,实现简单的web功能」· C语言 代码 · 共 459 行

C
459
字号
/*____________________________________________________________________________*\
 *

 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/Examples/Base64.c,v $
 * $Date: 2003/05/13 18:41:59 $
 *
 Description:
	Get CGI Post method.
	
	Speaks HTTP/1.0
\*____________________________________________________________________________*/
/* $SourceTop:$ */

#include <stdlib.h>
#include <stdio.h>
#include <time.h>

/*____________________________________________________________________________*\
 *
 Description:
\*____________________________________________________________________________*/
#if WIN32
extern char **_environ;
#else
extern char **environ;
#define _environ environ
#endif
#define assert(x)
#define MIN(a,b)    (((a)<(b))?(a):(b))

/*____________________________________________________________________________*\
 *
 Function:
 Synopsis:
 Description:
    Base64 encode
\*____________________________________________________________________________*/
const char __pBase64[65]="\
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
static void Internal_base64Encode( const char *pPlain, char *pBuffer,
    int iBufferLen )
{
    int iPos;
	int iLen;
	int i;
	enum { START, TWO, FOUR, SIX } eState;

    pBuffer[iBufferLen-1] = '\0';
    iBufferLen -= 2;
    iPos = 0;

#define CONCATENATE(c) \
    { \
    if ( iPos < iBufferLen ) \
        { pBuffer[iPos++] = (c); }; \
    }

	assert( pPlain );
	iLen = strlen( pPlain );
	eState = START;
	i=0;
	for( ;; )
		{
		int iPlain;
		int iBase64;
		char c = (i<iLen) ? pPlain[i] : 0 ;
		switch( eState )
			{
			case START:
				if ( i>=iLen )
                    {
                    CONCATENATE('\0');
                    return;
                    };
				iBase64 = (c >> 2);
				iPlain = (c << 4 ) & 0x30;
				i++;
				eState = TWO;
				break;

			case TWO:
				iBase64 = iPlain | ( c >> 4 );
				iPlain = (c << 2 ) & 0x3C;
				i++;
				eState = FOUR;
				break;
				
			case FOUR:
				iBase64 = iPlain | ( c >> 6 );
				iPlain = c & 0x3F;
				i++;
				eState = SIX;
				break;
				
			case SIX:
				iBase64 = iPlain;
				eState = START; 
				break;

			default:;
			};
		
		CONCATENATE( __pBase64[iBase64 & 0x3F] ); 

		if ( i>iLen )
			{
			switch( eState )
				{
				case START:
				case TWO:
					CONCATENATE( '=' );
				case FOUR:
					CONCATENATE( '=' );
				case SIX:
					CONCATENATE( '=' );
					CONCATENATE( '\0' );
					return;
				default:;
					assert( 0 );
				};
			};
		};
}

/*____________________________________________________________________________*\
 *
 Function:
 Synopsis:
 Description:
    Base64 Decode
\*____________________________________________________________________________*/
const char __pPlain[128]={
/*   0.. 15 */ -1, -1, -1, -1, -1, -1, -1 ,-1, -1, -1, -1, -1, -1, -1, -1, -1,
/*  16.. 31 */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
/*  32.. 47 */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63,
/*  48.. 63 */ 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1,  0, -1, -1,
/*  64.. 79 */ -1,  0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14,
/*  80.. 95 */ 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1,
/*  96..111 */ -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
/* 112..127 */ 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1
};
static void Internal_base64Decode( const char *pBase64, char *pBuffer,
    int iBufferLen )
{
    int iPos;
	int iLen;
	enum { START, TWO, FOUR, SIX } eState;
	int iDone;
	int i;

    iPos = 0;
    pBuffer[iBufferLen-1] = '\0';
    iBufferLen--;
#define CONCATENATE(c) \
    { \
    if ( iPos < iBufferLen ) \
        { pBuffer[iPos++] = (c); }; \
    }

	assert( pBase64 );
	iLen = strlen( pBase64 );
	eState = START;
	iDone = 0;
	for( i=0; i<iLen; i++)
		{
		char c = pBase64[i];
		int iLast;
		int iPlain;
		if ( !isalnum(c) && (c!='+') && (c!='/') ) { break; };
		iPlain = __pPlain[c];
		assert( iPlain!= -1 );
		switch( eState )
			{
			case START:
				iLast = ( iPlain << 2 ) & 0xFC;
				eState = TWO;
				break;

			case TWO:
				CONCATENATE( iLast | ( (iPlain >> 4 ) & 0x03) );
				iLast = ( iPlain << 4 ) & 0xF0;
				eState = FOUR;
				break;
				
			case FOUR:
				CONCATENATE( iLast | ( (iPlain >> 2 ) & 0x0F) );
				iLast = ( iPlain << 6 ) & 0xC0;
				eState = SIX;
				break;
				
			case SIX:
				CONCATENATE( iLast | ( iPlain & 0x3F) );
				eState = START; 
				break;

			default:;
			};

		if ( c=='=')
			{ break; };
		};
}

/*____________________________________________________________________________*\
 *
 Function:
 Synopsis:
 Description:
\*____________________________________________________________________________*/
int SendHeaders()
{
	printf("Content-Type: text/html\n");
	printf("\n" );
	printf("<HTML>\n");
	printf("<TITLE>Base64</TITLE>\n");
	printf("<BODY>\n");
	printf("<H2>Base64</H2>\n");

    return 1;
}

/*____________________________________________________________________________*\
 *
 Function:
 Synopsis:
 Description:
\*____________________________________________________________________________*/
int SendForm( const char *pName, const char *pPassword )
{
	printf("<FORM ACTION=\"/cgi-bin/Base64.exe?encode\" \
Method=\"POST\" WIDTH=40>\n");
	printf("<TABLE>\n");
	printf("<TR>\n");

	printf("<TH>\n");
	printf("Username\n");
	printf("</TH>\n");

	printf("<TH>\n");
	printf("Password\n");
	printf("</TH>\n");

	printf("<TR>\n");

	printf("<TD>\n");
	printf("<INPUT TYPE=\"text\" NAME=\"username\" WIDTH=40\n");
    if ( pName )
		printf("VALUE=\"%s\">\n", pName);
    else
		printf(">\n");
	printf("</TD>\n");

	printf("<TD>\n");
	printf("<INPUT TYPE=\"text\" NAME=\"password\" WIDTH=40\n");
    if ( pPassword )
		printf("VALUE=\"%s\">\n", pPassword);
    else
		printf(">\n");
	printf("</TD>\n");

	printf("</TR>\n");
	printf("</TABLE>\n");
	printf("<INPUT TYPE=\"submit\" VALUE=\"Encode\" WIDTH=40>\n");
	printf("<INPUT TYPE=\"reset\" VALUE=\"Clear\" WIDTH=40>\n");
	printf("</FORM>\n");
	printf("<HR>\n" );

    return 1;
}

/*____________________________________________________________________________*\
 *
 Function:
 Synopsis:
 Description:
\*____________________________________________________________________________*/
int SendEncoded( const char *pName, const char *pPassword )
{
    enum { BUF_SIZE=511 };
    char szBuf[BUF_SIZE+1];
    char szEncoded[BUF_SIZE+1];

    sprintf( szBuf, "%s:%s", pName, pPassword );
    Internal_base64Encode( szBuf, szEncoded, BUF_SIZE );

	printf("<TABLE>\n");
	printf("<TH>\n");
	printf("Username\n");
	printf("</TH>\n");

	printf("<TH>\n");
	printf("Password\n");
	printf("</TH>\n");

	printf("<TR>\n");
	printf("<TR>\n");

	printf("<TD>\n");
	printf("%s\n", pName );
	printf("</TD>\n");

	printf("<TD>\n");
	printf("%s\n", pPassword );
	printf("</TD>\n");

	printf("</TR>\n");
	printf("</TABLE>\n");
	printf("<BR><B>Base64(username:password)</B>: %s\n", szEncoded );

	printf("<HR>\n" );

    return 1;
}

/*____________________________________________________________________________*\
 *
 Function:
 Synopsis:
 Description:
\*____________________________________________________________________________*/
int Internal_getData( const char *pData, int iDataLen,
    char *pName, int iNameLen,
    char *pPassword, int iPasswordLen )
{
    pName[iNameLen-1] = '\0';    
    pPassword[iPasswordLen-1] = '\0';    
    for(;;)
        {
        /* --- scan to next '&' --- */
        int i;
        for( i=0; i<iDataLen && pData[i]!='&'; i++ );
        if ( i<9 ) { return 0; };
        if ( !strncmp( pData, "username=", 9 ) )
            {
            strncpy( pName, &(pData[9]), MIN( iNameLen, (i-9) ) );
            pName[i-9] = '\0';
            }
        else if ( !strncmp( pData, "password=", 9 ) )
            {
            strncpy( pPassword, &(pData[9]), MIN( iPasswordLen, (i-9) ) );
            pPassword[i-9] = '\0';
            };
        if ( pData[i]=='&' ) { i++; };
        iDataLen -= i;
        pData = &( pData[i] );
        };

    return 0;
}

/*____________________________________________________________________________*\
 *
 Function:
 Synopsis:
 Description:
\*____________________________________________________________________________*/
int main( int iArgc, const char *ppArgv[] )
{
	const char *pContentLength;
	const char *pContentType;
	int iInLen;
	char *pInputData;
	int iRLen;
    enum { BUF_SIZE=511 };
    char szName[BUF_SIZE+1];
    char szPassword[BUF_SIZE+1];
    char *pQuery;

    *szName = '\0';
    *szPassword = '\0';

	pContentLength = getenv( "CONTENT_LENGTH" );
	pContentType = getenv( "CONTENT_TYPE" );
    pQuery = getenv( "QUERY_STRING" );
	iInLen = pContentLength ? atoi( pContentLength ) : -1;

    if ( iInLen )
        {
		/*
		** Allocate buffer for data
		*/
		pInputData = (char *)malloc( iInLen+1 ); 

		/*
		** Read data
		*/
		iRLen = fread( pInputData, sizeof( char ), iInLen, stdin );
		if ( iRLen!=iInLen )
			{
            printf("Content-Type: text/html\n");
			printf("\n" );
			printf("<HTML>\n");
			printf("Error reading input.\n");
            return -1;
			};

		pInputData[iInLen] = '\0';

        Internal_getData( pInputData, iInLen, szName, BUF_SIZE, szPassword,
            BUF_SIZE );
        };

    if ( pQuery && !strcmp( pQuery, "encode" ) )
        {
        SendHeaders();
        SendForm( szName, szPassword );
        SendEncoded( szName, szPassword ); 
        }
    else if ( pQuery && !strcmp( pQuery, "decode" ) )
        {
        SendHeaders();
        SendForm( szName, szPassword );
        SendEncoded( szName, szPassword );
        }
    else
        {
        SendHeaders();
        SendForm( 0, 0 );
        }

	return 0;
}

⌨️ 快捷键说明

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