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

📄 tcpipsck.cpp

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

 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/IO/TCPIPSck.cpp,v $
 * $Date: 2004/05/29 16:42:12 $
 *
 Description:
	Implements a TCP/IP socket class

	TODO:
		- lookup service by name and add documentation.
		- make error messages give the name of the IO object.

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

/* --- ANSI --- */
#include <iostream.h>
#include <fstream.h>
#include <string.h>
#include <stdio.h>
#include <assert.h>
#include <ctype.h>
#include <stdlib.h>
#include <errno.h>

/* --- system includes --- */
#if POSIX
#	define USE_FLOCK		/* what OS's need this? */
#	define _BSD_COMPAT		/* this is for IRIX 5.3 */
#	include <sys/types.h>
#	include <sys/socket.h>
#	include <sys/file.h>
#	include <fcntl.h>
#	include <netinet/in.h>
#	include <netinet/tcp.h>
#	include <netdb.h>
#	include <arpa/inet.h>
#	include <unistd.h>
#	define closesocket(x)	close(x)
#	define SOCKET_ERROR		(-1)

/*
 * Prototype gethostname
 */
int gethostname( char *, int );
#elif WIN32
#	include <winsock.h>
#	define uint int
#else
#	error Unsupported Operating system
#endif

#include "Pi2API.h"

/*
** Macros
*/
#define LISTEN_QUEUE_SIZE				20
#define DEFAULT_TIMEOUT					360

/* --- Values from configuration file --- */
#define KEY_CONF_BINDPORT				"BindPort"
#define KEY_CONF_BINDHOST				"BindHost"
#define KEY_CONF_ACCEPTTIMEOUT			"AcceptTimeout"
#define KEY_CONF_RECVTIMEOUT			"RecvTimeout"
#define KEY_CONF_SENDTIMEOUT			"SendTimeout"
#define KEY_CONF_PEERADDRESSVARIABLE	"PeerIPVariable"
#define KEY_CONF_PEERHOSTNAMEVARIABLE	"PeerHostNameVariable"
#define KEY_CONF_LOCALADDRESSVARIABLE	"LocalAddressVariable"
#define KEY_CONF_SERVERPORTVARIABLE		"ServerPortVariable"
#define KEY_CONF_ACCEPTLOCKFILE			"AcceptLockFile"
#define KEY_CONF_FLAGS					"Flags"

/* --- Values from configuration tree --- */
#define KEY_CONF_TYPE					"Type"
#define VALUE_PASSIVE					"Passive"
#define VALUE_ACTIVE					"Active"
#define VALUE_INADDR_ANY				"INADDR_ANY"
#define VALUE_INADDR_ZERO				"0.0.0.0"

/*
** #define D	{ cerr << __FILE__ << ", " << __LINE__ << endl; };
*/
#define D  

#define STDERR (cerr << "TCPIPIO: ")

/*____________________________________________________________________________*\
 *
 Description:
	Messages
\*____________________________________________________________________________*/
const char szLockFileMsg[]="\n\
** ---\n\
**\n\
** The lockfile is used for synchronization amoungst multiple processes \n\
** using the same TCP/IP socket.\n\
**\n\
** Either remove the 'AcceptLockFile' directive and the named lockfile\n\
** or change the configuration to ensure that the lockfile is created.\n\
**\n\
** ---\
";
#if POSIX
const char szBindFailedAccess[]="\n\
** ---\n\
**\n\
** Failed to bind to the specified TCP/IP port because of insufficient \n\
** privileges. \n\
** \n\
** Note that use of TCP/IP ports 0-1023 is restricted on UNIX systems \n\
** (server must run initially as root).\n\
** \n\
** ---\
";
#else
const char szBindFailedAccess[]="\n\
** ---\n\
**\n\
** Failed to bind to the specified TCP/IP port because of insufficient \n\
** privilages. \n\
** \n\
** ---\
";
#endif
const char szBindFailedInUse[]="\n\
** ---\n\
**\n\
** Failed to bind to the specified TCP/IP port because the port \n\
** is already in use. \n\
** \n\
** Another process may be currently using the specified port.\n\
** \n\
** ---\
";

/*____________________________________________________________________________*\
 *
 Description:
	Functions used internally.
\*____________________________________________________________________________*/
class MainSocketData;
class TCPIPSocketData;
static int Internal_initActiveSocket( PIObject *pObject );
static int Internal_initPassiveSocket( PIObject *pObject,
		TCPIPSocketData *pProtoType );

/*____________________________________________________________________________*\
 *
 Description:
	Fast keys for faster access to variables
\*____________________________________________________________________________*/
static const char *pFKSendTimeout = 0;
static const char *pFKRecvTimeout = 0;

/*____________________________________________________________________________*\
 *
 Description:
		Configuration flags
\*____________________________________________________________________________*/
#define VALUE_FLAG_OWNDB				"OwnDB"
#define VALUE_FLAG_SETREMOTEADDRESS		"SetPeerAddress"
#define VALUE_FLAG_DNSREVERSELOOKUP		"DNSReverseLookup"
#define VALUE_FLAG_SETLOCALADDRESS		"SetLocalAddress"

#define FLG_OWNDB						0x0001
#define FLG_SETREMOTEADDRESS			0x0002
#define FLG_DNSREVERSELOOKUP			0x0004
#define FLG_SETLOCALADDRESS				0x0008
#define FLG_ERROR						0x8000

/*____________________________________________________________________________*\
** Class for PIDBTYPE, Variable name and PIDBFLAG
\*____________________________________________________________________________*/
class DBInfo
{
public:
	int iType;
	const char *pFKVariableName;
	int iFlags;

	DBInfo( const char *pDefinition )
	:	iType( -1 ), pFKVariableName( 0 ), iFlags( 0 )
		{
		if ( !pDefinition )
				{ return; };
		/* ---

		Decode something like the following:-

				STRING:PeerIP:0

		--- */
		enum { BUF_SIZE=2047 };
		char szBuf[BUF_SIZE+1];
		int i=0;
		const char *pS = pDefinition;
		for(; i<BUF_SIZE && pS[i] && pS[i]!=':'; i++) { szBuf[i]=pS[i]; };
		szBuf[i] = '\0';

		iType = PIDB_pidbtypeNameToNumber( szBuf );

		if ( i<BUF_SIZE && pS[i] ) { i++; };
		pS = &(pS[i]); i=0;
		for(; i<BUF_SIZE && pS[i] && pS[i]!=':'; i++) { szBuf[i]=pS[i]; };
		szBuf[i] = '\0';

		pFKVariableName = PIDB_getFastKey( pS, iType );

		if ( i<BUF_SIZE && pS[i] ) { i++; };
		pS = &(pS[i]); i=0;
		for(; i<BUF_SIZE && pS[i] && pS[i]!=':'; i++) { szBuf[i]=pS[i]; };
		szBuf[i] = '\0';

		if ( *szBuf )
				{ iFlags = PIDB_pidbflagsNameToNumber( szBuf ); };
		};

	~DBInfo()
		{
		};

	inline int IsOK()			   { return pFKVariableName && iType>=0; };
};

/*____________________________________________________________________________*\
 *
 Description:
	Documentation for this IO object.
\*____________________________________________________________________________*/

#if 0
/*___+++HTMLDOC_BEGIN+++___*/
Name:
	TCPIPIO

Description:
	This object encapsulates TCP/IP based IO communication.

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

<TR>
<TD>Type
<TD>Passive
<TD>"Passive", "Active"
<TD>A Pi3 object
<TD>Type "Passive"

<TR>
<TD>BindPort
<TD>+ (passive only)
<TD>1..n
<TD>local port
<TD>BindPort 8080

<TR>
<TD>BindHost
<TD>+ (passive only)
<TD>nnn.nnn.nnn.nnn or host.org.dom or INADDR_ANY
<TD>local host
<TD>BindHost "localhost"

<TR>
<TD>AcceptTimeout
<TD>360
<TD>n seconds or -1 (infinite)
<TD>Timeout on accept
<TD>AcceptTimeout -1

<TR>
<TD>RecvTimeout
<TD>-
<TD>n seconds or -1 (infinite)
<TD>Timeout on receive
<TD>RecvTimeout 45

<TR>
<TD>SendTimeout
<TD>-
<TD>n seconds or -1 (infinite)
<TD>Timeout on send
<TD>SendTimeout 30

<TR>
<TD>PeerAddressVariable
<TD>-
<TD>&lt;db type&gt;:&lt;name&gt;
<TD>Variable to hold Peer IP address
<TD>PeerAddressVariable "STRING:RemoteAddr"

<TR>
<TD>PeerHostNameVariable
<TD>-
<TD>&lt;db type&gt;:&lt;name&gt;
<TD>Variable to hold Peer hostname
<TD>PeerHostNameVariable "STRING:RemoteHost"

<TR>
<TD>LocalAddressVariable
<TD>-
<TD>&lt;db type&gt;:&lt;name&gt;
<TD>Variable to hold local IP address
<TD>LocalAddressVariable "STRING:LocalAddr"

<TR>
<TD>ServerPortVariable
<TD>-
<TD>&lt;db type&gt;:&lt;name&gt;
<TD>Variable to hold server IP port
<TD>ServerPortVariable "RFC822:ServerPort"

<TR>
<TD>AcceptLockFile
<TD>-
<TD>&lt;filename&gt;
<TD>File containing lock filename
<TD>AcceptLockFile "Logs/lockfile.txt"

<TR>
<TD>Flags
<TD>0 (no flags set)
<TD>"OwnDB" | "SetPeerAddress" | "DNSReverseLookup"
<TD>Flags which effect operation
<TD>Flags "OwnDB | SetPeerAddress | DNSReverseLookup"

</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> Type </H5>
Specify whether child objects the prototype IO object will be an active (client)
or passive (server) socket.

<H5> BindPort </H5>
The local port to listen on for passive sockets.

<H5> BindHost </H5>
The local IP address or hostname of the network interface to listen on
passive sockets. A value of INADDR_ANY let the server listen on any interface.

<H5> AcceptTimeout </H5>
Accept timeout for passive sockets, a value of -1 specifies
no timeout.

<H5> RecvTimeout </H5>
Timeout on receiving data for active and passive sockets. A value
of -1 specifies no timeout.

<H5> SendTimeout </H5>
Timeout on sending data for active and passive sockets. A value
of -1 specifies no timeout.

<H5> PeerAddressVariable </H5>
The variable name with which to set the ip address of the remote
peer if the 'SetPeerAddress' flag is set.

<H5> PeerHostNameVariable </H5>
The variable name with which to set the hostname of the remote
peer if the 'SetPeerAddress' and 'DNSReverseLookup' flags are set.

<H5> LocalAddressVariable </H5>
The variable name with which to set the local IP address of the socket if
the 'SetLocalAddress' flag is set.

<H5> ServerPortVariable </H5>
The variable name with which to set the IP port of the server socket if
the 'SetLocalAddress' flag is set for server or 'SetPeerAddress' flag is
set for client connections.

<H5> AcceptLockFile </H5>
The path to a file containing the lockfile for this server. The
lockfile is used to synchronization accepting of new connection
amoungst a group of processes listening for connections on the
same file descriptor. Note this is only applicable to POSIX operating
systems where the <CODE>fork()</CODE> system call may have been invoked
to spawn a single process with a single listening file descriptor into
multiple processes with multiple copies of the same file descriptor.

<H5> Flags </H5>
This options allows various options to be enabled and disabled. The
value of the option takes the form of a sequence of value seperated
by the '|' character. The values have the following significance.
"OwnDB" | "SetPeerAddress" | "DNSReverseLookup"
<CENTER>
<STRONG>Flags</STRONG>
<TABLE BORDER=1>
<TH>Value
<TH>Meaning

<TR>
<TD>OwnDB
<TD>Each child object will create its own DB

<TR>
<TD>SetPeerAddress
<TD>On creation, each child socket will get the IP address of its remote
peer and place it in the DB with the variable name specified with the
'PeerAddressVariable' and 'ServerPortVariable' (client connection only)
options.

<TR>
<TD>DNSReverseLookup
<TD>When the IP address of the remote peer is retrieved the hostname of
the peer will be found and placed in the DB with the variable name
specified by the 'PeerHostNameVariable' option.

<TR>
<TD>SetLocalAddress
<TD>On creation, each child socket will store its local IP address in
the variable specified by the 'LocalAddressVariable' and 'ServerPortVariable'
(server connection only) parameters.

</TABLE>
</CENTER>

Returns:
	PIAPI_COMPLETED on success.
	PIAPI_CONTINUE if no action taken.
	PIAPI_ERROR and PIAPI_ABORT respectively for generic and severe
	error conditions.

⌨️ 快捷键说明

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