Async 1.8.0
Async::HttpServerConnection Class Reference

A class representing a HTTP server side connection. More...

#include <AsyncHttpServerConnection.h>

Inheritance diagram for Async::HttpServerConnection:
Async::TcpConnection

Classes

struct  Request
 
class  Response
 

Public Types

typedef std::map< std::string, std::string > Headers
 
- Public Types inherited from Async::TcpConnection
enum  DisconnectReason {
  DR_HOST_NOT_FOUND , DR_REMOTE_DISCONNECTED , DR_SYSTEM_ERROR , DR_ORDERED_DISCONNECT ,
  DR_PROTOCOL_ERROR , DR_SWITCH_PEER , DR_BAD_STATE
}
 Reason code for disconnects. More...
 

Public Member Functions

 HttpServerConnection (size_t recv_buf_len=DEFAULT_RECV_BUF_LEN)
 Constructor.
 
 HttpServerConnection (int sock, const IpAddress &remote_addr, uint16_t remote_port, size_t recv_buf_len=DEFAULT_RECV_BUF_LEN)
 Constructor.
 
virtual ~HttpServerConnection (void)
 Destructor.
 
virtual TcpConnectionoperator= (TcpConnection &&other_base) override
 Move assignmnt operator.
 
void setChunked (void)
 Send data with chunked transfer encoding.
 
virtual bool write (const Response &res)
 Send a HTTP response.
 
virtual bool write (const char *buf, int len)
 Write data to the socket.
 
- Public Member Functions inherited from Async::TcpConnection
 TcpConnection (size_t recv_buf_len=DEFAULT_RECV_BUF_LEN)
 Constructor.
 
 TcpConnection (int sock, const IpAddress &remote_addr, uint16_t remote_port, size_t recv_buf_len=DEFAULT_RECV_BUF_LEN)
 Constructor.
 
virtual ~TcpConnection (void)
 Destructor.
 
void setRecvBufLen (size_t recv_buf_len)
 Set a new receive buffer size.
 
size_t recvBufLen (void) const
 
virtual void disconnect (void)
 Disconnect from the remote host.
 
IpAddress localHost (void) const
 Get the local IP address associated with this connection.
 
uint16_t localPort (void) const
 Get the local TCP port associated with this connection.
 
const IpAddressremoteHost (void) const
 Return the IP-address of the remote host.
 
uint16_t remotePort (void) const
 Return the remote port used.
 
bool isConnected (void) const
 Check if the connection is established or not.
 
bool isIdle (void) const
 Check if the connection is idle.
 
void enableSsl (bool enable)
 Enable or disable TLS for this connection.
 
SslX509 sslPeerCertificate (void)
 Get the peer certificate associated with this connection.
 
Async::SslX509 sslCertificate (void) const
 
long sslVerifyResult (void) const
 Get the result of the certificate verification process.
 
void setSslContext (SslContext &ctx, bool is_server)
 Set the OpenSSL context to use when setting up the connection.
 
SslContextsslContext (void)
 
bool isServer (void) const
 
void freeze (void)
 Stop all communication.
 
void unfreeze (void)
 Reenable all communication.
 

Public Attributes

sigc::signal< void, HttpServerConnection *, DisconnectReasondisconnected
 A signal that is emitted when a connection has been terminated.
 
sigc::signal< void, HttpServerConnection *, Request & > requestReceived
 A signal that is emitted when a HTTP request has been received on the connection.
 
- Public Attributes inherited from Async::TcpConnection
sigc::signal< void, TcpConnection *, DisconnectReasondisconnected
 Get common name for the SSL connection.
 
sigc::signal< int, TcpConnection *, void *, int > dataReceived
 A signal that is emitted when data has been received on the connection.
 
sigc::signal< if_all_true_acc::result_type, TcpConnection *, int, X509_STORE_CTX * >::accumulated< if_all_true_accverifyPeer
 A signal that is emitted on SSL/TLS certificate verification.
 
sigc::signal< void, TcpConnection * > sslConnectionReady
 A signal that is emitted when the SSL connection is ready.
 

Protected Member Functions

virtual void closeConnection (void) override
 Disconnect from the remote peer.
 
virtual void onDisconnected (DisconnectReason reason) override
 Called when a connection has been terminated.
 
virtual int onDataReceived (void *buf, int count) override
 Called when data has been received on the connection.
 
virtual void emitDisconnected (DisconnectReason reason) override
 Emit the disconnected signal.
 
- Protected Member Functions inherited from Async::TcpConnection
void setSocket (int sock)
 Setup information about the connection.
 
void setRemoteAddr (const IpAddress &remote_addr)
 Setup information about the connection.
 
void setRemotePort (uint16_t remote_port)
 Setup information about the connection.
 
int socket (void) const
 Return the socket file descriptor.
 
virtual int emitVerifyPeer (int preverify_ok, X509_STORE_CTX *store_ctx)
 Emit the verifyPeer signal.
 

Protected Attributes

sigc::signal< void, bool > sendBufferFull
 

Additional Inherited Members

- Static Public Member Functions inherited from Async::TcpConnection
static const char * disconnectReasonStr (DisconnectReason reason)
 Translate disconnect reason to a string.
 
- Static Public Attributes inherited from Async::TcpConnection
static const int DEFAULT_RECV_BUF_LEN = 1024
 The default size of the reception buffer.
 

Detailed Description

A class representing a HTTP server side connection.

Author
Tobias Blomberg / SM0SVX
Date
2019-08-26

This class implement a VERY simple HTTP server side connection. It can be used together with the Async::TcpServer class to build a HTTP server.

WARNING: This implementation is not suitable to be exposed to the public Internet. It contains a number of security flaws and probably also incompatibilities. Only use this class with known clients.

// A demo http/https server.
// Run AsyncSslX509_demo first to generate CA, key and certificate
// Use a web browser or curl to access:
//
// curl http://localhost:8080
// curl --cacert demo_ca.crt https://localhost:8443
//
#include <sstream>
#include <AsyncTcpServer.h>
void requestReceived(Async::HttpServerConnection *con,
{
std::cout << "--- " << req.method << " " << req.target << std::endl;
if ((req.method != "GET") && (req.method != "HEAD"))
{
res.setCode(501);
res.setContent("text/plain", req.method + ": Method not implemented");
con->write(res);
return;
}
std::ostringstream os;
os << "{"
<< "\"method\":\"" << req.method << "\","
<< "\"target\":\"" << req.target << "\","
<< "\"client-proto-major\":" << req.ver_major << ","
<< "\"client-proto-minor\":" << req.ver_minor << ","
<< "\"headers\":{";
Async::HttpServerConnection::Headers::const_iterator it;
for (it=req.headers.begin(); it!=req.headers.end(); ++it)
{
std::cout << (*it).first << ": " << (*it).second << std::endl;
if (it != req.headers.begin())
{
os << ",";
}
os << "\"" << (*it).first << "\":\"" << (*it).second << "\"";
}
os << "}}";
res.setContent("application/json", os.str());
if (req.method == "HEAD")
{
res.setSendContent(false);
}
res.setCode(200);
con->write(res);
} /* requestReceived */
void clientConnected(Async::HttpServerConnection *con)
{
std::cout << "/// Client connected: "
<< con->remoteHost() << ":" << con->remotePort() << std::endl;
con->requestReceived.connect(sigc::ptr_fun(&requestReceived));
} /* clientConnected */
void clientDisconnected(Async::HttpServerConnection *con,
{
std::cout << "\\\\\\ Client disconnected: "
<< con->remoteHost() << ":" << con->remotePort()
<< std::endl;
} /* clientConnected */
void sslClientConnected(Async::HttpServerConnection *con)
{
std::cout << "/// SSL Client connected: "
<< con->remoteHost() << ":" << con->remotePort() << std::endl;
con->requestReceived.connect(sigc::ptr_fun(&requestReceived));
con->enableSsl(true);
} /* sslClientConnected */
void sslClientDisconnected(Async::HttpServerConnection *con,
{
std::cout << "\\\\\\ SSL Client disconnected: "
<< con->remoteHost() << ":" << con->remotePort()
<< std::endl;
} /* sslClientConnected */
int main(void)
{
app.catchUnixSignal(SIGINT);
app.catchUnixSignal(SIGTERM);
app.unixSignalCaught.connect(
sigc::hide(sigc::mem_fun(app, &Async::CppApplication::quit)));
// Listen for http connections on TCP port 8080
server.clientConnected.connect(sigc::ptr_fun(&clientConnected));
server.clientDisconnected.connect(sigc::ptr_fun(&clientDisconnected));
// Listen for https connections on TCP port 8443
ctx.setCertificateFiles("demo.key", "demo.crt");
ssl_server.setSslContext(ctx);
ssl_server.clientConnected.connect(sigc::ptr_fun(&sslClientConnected));
ssl_server.clientDisconnected.connect(sigc::ptr_fun(&sslClientDisconnected));
app.exec();
}
The core class for writing asyncronous cpp applications.
A simple HTTP Server connection class.
A class for creating a TCP server.
An application class for writing non GUI applications.
void quit(void)
Exit the application main loop.
void catchUnixSignal(int signum)
Catch the specified UNIX signal.
void exec(void)
Execute the application main loop.
sigc::signal< void, int > unixSignalCaught
A signal that is emitted when a monitored UNIX signal is caught.
void setContent(const std::string &content_type, const std::string &content)
A class representing a HTTP server side connection.
sigc::signal< void, HttpServerConnection *, Request & > requestReceived
A signal that is emitted when a HTTP request has been received on the connection.
virtual bool write(const Response &res)
Send a HTTP response.
SSL context meant to be used with TcpConnection and friends.
bool setCertificateFiles(const std::string &keyfile, const std::string &crtfile)
Set which key and certificate file to use for connections.
static const char * disconnectReasonStr(DisconnectReason reason)
Translate disconnect reason to a string.
const IpAddress & remoteHost(void) const
Return the IP-address of the remote host.
uint16_t remotePort(void) const
Return the remote port used.
DisconnectReason
Reason code for disconnects.
void enableSsl(bool enable)
Enable or disable TLS for this connection.
A class for creating a TCP server.
Examples
AsyncHttpServer_demo.cpp.

Definition at line 129 of file AsyncHttpServerConnection.h.

Member Typedef Documentation

◆ Headers

std::map<std::string, std::string> Async::HttpServerConnection::Headers

Definition at line 132 of file AsyncHttpServerConnection.h.

Constructor & Destructor Documentation

◆ HttpServerConnection() [1/2]

Async::HttpServerConnection::HttpServerConnection ( size_t recv_buf_len = DEFAULT_RECV_BUF_LEN)
explicit

Constructor.

Parameters
recv_buf_lenThe length of the receiver buffer to use

◆ HttpServerConnection() [2/2]

Async::HttpServerConnection::HttpServerConnection ( int sock,
const IpAddress & remote_addr,
uint16_t remote_port,
size_t recv_buf_len = DEFAULT_RECV_BUF_LEN )

Constructor.

Parameters
sockThe socket for the connection to handle
remote_addrThe remote IP-address of the connection
remote_portThe remote TCP-port of the connection
recv_buf_lenThe length of the receiver buffer to use

◆ ~HttpServerConnection()

virtual Async::HttpServerConnection::~HttpServerConnection ( void )
virtual

Destructor.

Member Function Documentation

◆ closeConnection()

virtual void Async::HttpServerConnection::closeConnection ( void )
overrideprotectedvirtual

Disconnect from the remote peer.

This function is used internally to close the connection to the remote peer.

Reimplemented from Async::TcpConnection.

◆ emitDisconnected()

virtual void Async::HttpServerConnection::emitDisconnected ( DisconnectReason reason)
inlineoverrideprotectedvirtual

Emit the disconnected signal.

Parameters
reasonThe reason for the disconnection

Reimplemented from Async::TcpConnection.

Definition at line 330 of file AsyncHttpServerConnection.h.

References disconnected, and Async::TcpConnection::emitDisconnected().

◆ onDataReceived()

virtual int Async::HttpServerConnection::onDataReceived ( void * buf,
int count )
overrideprotectedvirtual

Called when data has been received on the connection.

Parameters
bufA buffer containg the read data
countThe number of bytes in the buffer
Returns
Return the number of processed bytes

This function is called when data has been received on this connection. The buffer will contain the bytes read from the operating system. The function will return the number of bytes that has been processed. The bytes not processed will be stored in the receive buffer for this class and presented again to the slot when more data arrives. The new data will be appended to the old data.

Reimplemented from Async::TcpConnection.

◆ onDisconnected()

virtual void Async::HttpServerConnection::onDisconnected ( DisconnectReason reason)
overrideprotectedvirtual

Called when a connection has been terminated.

Parameters
reasonThe reason for the disconnect

This function will be called when the connection has been terminated.

Reimplemented from Async::TcpConnection.

◆ operator=()

virtual TcpConnection & Async::HttpServerConnection::operator= ( TcpConnection && other_base)
overridevirtual

Move assignmnt operator.

Parameters
other_baseThe object to move from
Returns
Returns this object

The move operator move the state of a specified TcpFramedConnection object into this object. After the move, the state of the other object will be the same as if it had just been default constructed.

Reimplemented from Async::TcpConnection.

◆ setChunked()

void Async::HttpServerConnection::setChunked ( void )
inline

Send data with chunked transfer encoding.

Calling this function will enable data to be sent in chunks. The "Transfer-encoding: chunked" will be set in the header and each call to write() will send a chunk.

Definition at line 254 of file AsyncHttpServerConnection.h.

◆ write() [1/2]

virtual bool Async::HttpServerConnection::write ( const char * buf,
int len )
virtual

Write data to the socket.

Parameters
bufThe buffer containing the data to write
lenThen length of the data in the buffer
Returns
Return true on success or else false

If chunked mode has been set a chunked header and trailer will be added to the data. If not in chunked mode, the raw buffer will be sent without modification.

◆ write() [2/2]

virtual bool Async::HttpServerConnection::write ( const Response & res)
virtual

Send a HTTP response.

Parameters
resThe response (
See also
Response)
Returns
Return true on success or else false
Examples
AsyncHttpServer_demo.cpp.

Member Data Documentation

◆ disconnected

sigc::signal<void, HttpServerConnection *, DisconnectReason> Async::HttpServerConnection::disconnected

A signal that is emitted when a connection has been terminated.

Parameters
conThe connection object
reasonThe reason for the disconnect

Definition at line 280 of file AsyncHttpServerConnection.h.

Referenced by emitDisconnected().

◆ requestReceived

sigc::signal<void, HttpServerConnection *, Request&> Async::HttpServerConnection::requestReceived

A signal that is emitted when a HTTP request has been received on the connection.

Parameters
reqThe request object (
See also
Request)

This signal is emitted when a HTTP request has been received on this connection.

Examples
AsyncHttpServer_demo.cpp.

Definition at line 290 of file AsyncHttpServerConnection.h.

◆ sendBufferFull

sigc::signal<void, bool> Async::HttpServerConnection::sendBufferFull
protected

Definition at line 293 of file AsyncHttpServerConnection.h.


The documentation for this class was generated from the following file: