Bredbandskollen CLI  1.2
Asynchronous network task engine
Public Types | Public Member Functions | List of all members
HttpServerConnection Class Reference

HTTP/1.1 server protocol. More...

#include <httpserverconnection.h>

Inheritance diagram for HttpServerConnection:
Inheritance graph
[legend]
Collaboration diagram for HttpServerConnection:
Collaboration graph
[legend]

Public Types

typedef std::multimap< std::string, std::string >::const_iterator Hit
 

Public Member Functions

 HttpServerConnection (const std::string &label, WebServerTask *task, int fd, const char *ip, uint16_t port)
 
PollState connected () final
 Will be called when the connection is established. More...
 
PollState readData (char *buf, size_t len) final
 Callback, called when data has arrived; len > 0. More...
 
PollState writeData () override
 Callback, called when socket is writable. More...
 
bool hasQueryPar (const std::string &name) const
 Return true if query string in current request has parameter name:
 
void eraseQueryPar (const std::string &name)
 
std::string getQueryVal (const std::string &name) const
 
const std::multimap< std::string, std::string > & currentQueryPars () const
 
std::map< std::string, std::string > currentRequestCookies () const
 
std::string cookieVal (const std::string &name) const
 Return value of cookie if it exists, otherwise empty string.
 
std::string getHeaderVal (const std::string &name) const
 
std::pair< Hit, Hit > getHeaderVals (const std::string &name) const
 
size_t sendHttpResponse (const std::string &headers, const std::string &mime, const std::string &contents)
 Async send response. Return length of what's to be sent.
 
size_t sendHttpResponseHeader (const std::string &headers, const std::string &mime, size_t content_length)
 Async send response headers. Return length of what's to be sent:
 
size_t sendChunkedResponseHeader (const std::string &headers, const std::string &mime)
 
size_t sendChunk (const std::string &content)
 Send chunk. May only be used if we sent chunked headers.
 
size_t chunkedResponseComplete ()
 To notify that all chunks have been sent.
 
bool sendingChunkedResponse () const
 
const std::string & currentUri () const
 
const std::string currentFullUrl () const
 
const std::string & currentQueryString () const
 
size_t remainingPostData () const
 Number of bytes left of the current HTTP POST.
 
void bufferPostData ()
 
void notifyWsHandshake ()
 Call this if the owner is to be notified after handshake:
 
void setOwner (Task *new_owner) override
 
std::string currentRequest () const
 Current request (first line and headers) in raw form.
 
- Public Member Functions inherited from HttpConnection
unsigned int httpVersion ()
 
void sendWsMessage (const std::string &msg)
 
void sendWsBinary (const char *buf, size_t len)
 
void startWsBinStream (size_t len)
 
void startWsTxtStream (size_t len)
 
void abortWsStream ()
 
void sendWsClose (uint16_t code, std::string msg)
 
void streamWsResponse ()
 
const unsigned char * responseMask () const
 
size_t wsIncomingBytesLeft () const
 
size_t wsBytesReceived () const
 
size_t wsOutgoingBytesLeft () const
 
size_t wsBytesSent () const
 
bool isWebsocket () const
 
- Public Member Functions inherited from SocketConnection
 SocketConnection (const std::string &label, Task *owner, const std::string &hostname, uint16_t port, uint16_t iptype=0, struct addrinfo *local_addr=nullptr)
 
void enableTLS ()
 Notify that the connection will be encrypted (SSL).
 
bool is_tls () const
 Return true if the connection will be encrypted (SSL).
 
gnutls_session_t cache_session ()
 Store SSL session in cache.
 
void insert_cached_session (gnutls_session_t &old_session)
 Reuse cached SSL session.
 
virtual void connectionFailed (const std::string &err_msg)
 Will be called if the connection couldn't be established.
 
virtual void closedByPeer ()
 
virtual PollState unexpectedData (char *buf, size_t len)
 Peer has sent data when it wasn't supposed to. More...
 
size_t sendData (const char *buf, size_t len)
 Try to send len bytes from the given buffer. Return the amount sent. More...
 
void asyncSendData (const char *buf, size_t len)
 Send data to peer as soon as possible. More...
 
void asyncSendData (const std::string data)
 Send data to peer as soon as possible. More...
 
size_t asyncBufferSize () const
 Return number of bytes left to send after calling SocketConnection::asyncSendData.
 
const std::string & peerIp () const
 Return peer's IP address.
 
uint16_t peerPort () const
 Return peer's port number.
 
void dbgOn (bool b=true)
 Enable debug output of data sent and received.
 
bool dbgIsOn ()
 Return true if socket debugging is enabled.
 
- Public Member Functions inherited from Socket
 Socket (const std::string &label, Task *owner, const std::string &hostname, uint16_t port)
 
 Socket (const std::string &label, Task *owner, int fd)
 
Taskowner () const
 Return task owning the socket.
 
std::string hostname () const
 Return name of the host to which the socket is supposed to connect.
 
uint16_t port () const
 Return port number to which the socket is supposed to connect.
 
PollState state () const
 Return current socket state.
 
int getUnixDomainPeer () const
 Return the peer socket descriptor. More...
 
virtual std::string cacheLabel ()
 Return the socket's cache group, or an empty string. More...
 
int id () const
 Return unique connection ID if connected. More...
 
void setExpiry (double s)
 Set a time to live for the socket. More...
 
bool hasExpired (const TimePoint &when) const
 Return true if the given TimePoint is after the socket's expiry.
 
const char * localIp () const
 Return local IP address in static buffer.
 
struct addrinfo * getAddressInfo (uint16_t iptype=0)
 Perform DNS lookup of remote host.
 
- Public Member Functions inherited from Logger
 Logger (std::string label)
 
std::string label () const
 Return the object's log label.
 
void resetLabel (const std::string &new_label)
 Modify the object's log label.
 

Additional Inherited Members

- Static Public Member Functions inherited from SocketConnection
static uint64_t totBytesSent ()
 Number of bytes sent by current thread.
 
static uint64_t totBytesReceived ()
 Number of bytes recieved by current thread.
 
static void resetByteCounter ()
 Reset counter for SocketConnection::totBytesSent and SocketConnection::totBytesReceived.
 
- Static Public Member Functions inherited from Socket
static const char * getIp (int fd, uint16_t *port=nullptr, bool peer=true)
 Return IP address of connected socket in static buffer. More...
 
static const char * getIp (struct sockaddr *address, uint16_t *port=nullptr)
 Return IP address in static buffer.
 
static const char * getIp (struct addrinfo *address, uint16_t *port=nullptr)
 Return IP address in static buffer.
 
- Static Public Member Functions inherited from Logger
static void setLogFile (std::ostream &stream)
 Set global log destination. More...
 
static void reopenLogFile (const std::string &filename)
 If current log is a file (ofstream), reopen it with new filename:
 
static void setLogLimit (unsigned int loglines=0, unsigned int warnlines=0, unsigned int errlines=0)
 Set max number of lines of info/warn/err log. More...
 
static void sayTime (std::ostream &stream)
 Write current local time to the given stream.
 
static bool inError ()
 Return true if any error has been logged (globally since start)
 
static std::ostream & err_log (const std::string &label)
 Write a line of error log. More...
 
static std::ostream & warn_log (const std::string &label)
 Write a line of warning log. More...
 
static std::ostream & log (const std::string &label)
 Write a line of info log. More...
 
static void flushLogFile ()
 
static void pauseLogging ()
 Disable all log output until next call to Logger::setLogFile.
 
static double secondsSince (const TimePoint &t)
 
static double secondsTo (const TimePoint &t)
 
static int64_t msSince (const TimePoint &t)
 
static int64_t msTo (const TimePoint &t)
 
static bool hasExpired (const TimePoint &t)
 Return true if current time is after the given TimePoint.
 
static TimePoint timeNow ()
 Return current time.
 
static TimePoint timeAfter (double s)
 Return current time plus s seconds.
 
static TimePoint timeMax ()
 Return a very distant time.
 
static std::chrono::microseconds toUs (double t)
 Convert s (seconds) to std::chrono::microseconds.
 
static std::string dateString (time_t t=0)
 Return local time, formatted as 2023-10-14T09:38:47+0200.
 
static std::string dateString2 (time_t t=0)
 Return local time, formatted as Sat, 14 Oct 2023 09:38:47.
 
static std::string createHashKey (unsigned int length=20)
 Return a random string. More...
 
- Protected Member Functions inherited from HttpConnection
 HttpConnection (const std::string &label, Task *owner, const std::string &hostname, uint16_t port, uint16_t iptype=0, struct addrinfo *local_addr=nullptr)
 
 HttpConnection (const std::string &label, Task *owner, int fd, const char *ip, uint16_t port)
 
void set_http_version (unsigned int major, unsigned int minor)
 
void send_ws_handshake (const std::string &key)
 
void send_ws_bin_header (size_t len)
 
void send_ws_txt_header (size_t len)
 
void send_ws_pong ()
 
PollState incoming_ws_data (const char *buf, size_t len)
 
PollState incoming_ws_header (const char *buf, size_t len)
 
PollState wsReadData (const char *buf, size_t len)
 
PollState wsWriteData ()
 
- Protected Member Functions inherited from SocketConnection
 SocketConnection (const std::string &label, Task *owner, int fd, const char *ip, uint16_t port)
 
PollState tellOwner (const std::string &msg)
 
- Protected Member Functions inherited from Socket
virtual PollState checkReadBlock ()
 This will be called regularly on READ_BLOCKED sockets to check if the block can be lifted. More...
 
void setWantToSend ()
 Notify intention of sending large amounts of data. More...
 
int socket () const
 Return file descriptor.
 
void closeMe ()
 Tell the network engine that the connection should be closed.
 
void createNonBlockingSocket (struct addrinfo *addressEntry, struct addrinfo *localAddr=nullptr)
 Create socket and initiate the connection. More...
 
bool setNonBlocking (int fd)
 Set socket as non-blocking.
 
bool inError () const
 Return true if the socket has encountered a fatal error.
 
- Protected Member Functions inherited from Logger
std::ostream & errno_log () const
 Write a line of error log after a failed system call has set the global errno to a non-zero value. More...
 
std::ostream & err_log () const
 Write a line of error log. More...
 
std::ostream & warn_log () const
 Write a line of warning log. More...
 
std::ostream & log () const
 Write a line of info log. More...
 
std::ostream & dbg_log () const
 Write a line of debug log. More...
 
- Static Protected Member Functions inherited from Socket
static bool isTempError ()
 Return true unless last syscall encountered a fatal error.
 
static int closeSocket (int fd)
 Close a file descriptor.
 
static bool socketInError (int fd)
 Return true if the file descriptor has encountered a fatal error.
 
- Protected Attributes inherited from HttpConnection
std::string buffer
 
bool is_websocket = false
 

Detailed Description

HTTP/1.1 server protocol.

This class implements a small subset of the HTTP/1.1 server protocol. When a new HTTP GET or POST request is made, the owner task's method newGetRequest or newPostRequest will be called. If a websocket connection is made, the owner task's method newWsRequest will be called.

To use this class, you must derive from WebServerTask and implement at least one of newGetRequest, newPostRequest, or newWsRequest.

Member Function Documentation

◆ bufferPostData()

void HttpServerConnection::bufferPostData ( )
inline

The owner task may call this in the newPostRequest handler and return HttpState::READING_POST_DATA. In that case, the owner task will not get partialPostData calls, but only a lastPostData call when the user has posted all data.

Hint: Check first that remainingPostData() isn't too large.

◆ connected()

PollState HttpServerConnection::connected ( )
inlinefinalvirtual

Will be called when the connection is established.

Override it to start sending data when the connection is ready.

If a connection couldn't be established, SocketConnection::connectionFailed will be called instead. You must not return PollState::CONNECTING.

Reimplemented from SocketConnection.

◆ getHeaderVal()

std::string HttpServerConnection::getHeaderVal ( const std::string &  name) const

If HTTP headers in current request has attribute "name", return the value of its first occurrence. Otherwise return empty string. Note: use only lower-case letters in "name", e.g. "content-length".

◆ getQueryVal()

std::string HttpServerConnection::getQueryVal ( const std::string &  name) const

If query string in current request has parameter "name", return the value of its first occurrence. Otherwise return empty string.

◆ readData()

PollState HttpServerConnection::readData ( char *  ,
size_t   
)
finalvirtual

Callback, called when data has arrived; len > 0.

May be called in states READ, READ_WRITE. Override this method to handle the data. Return value should be the new state.

The buffer is owned by the implementation. However, you are allowed to modify the contents of the buffer and you may also use it in the asyncSendData call.

Reimplemented from SocketConnection.

◆ sendChunkedResponseHeader()

size_t HttpServerConnection::sendChunkedResponseHeader ( const std::string &  headers,
const std::string &  mime 
)

Async send response headers with the "chunked" encoding. Return length of what's to be sent.

◆ setOwner()

void HttpServerConnection::setOwner ( Task new_owner)
overridevirtual

Override this to make sure we're not transfered to an owner Task that is not a WebServerTask (or subclass).

Reimplemented from HttpConnection.

◆ writeData()

PollState HttpServerConnection::writeData ( )
overridevirtual

Callback, called when socket is writable.

May be called in states PollState::WRITE and PollState::READ_WRITE. Override it to write data. Return value should be the new state. Do not return PollState::WRITE or PollState::READ_WRITE except after a write operation where all data couldn't be sent immediately.

Reimplemented from SocketConnection.


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