Bredbandskollen CLI
1.2
Asynchronous network task engine
|
This class implements low-level socket connection operations. Inherit from it to implement protocols like HTTP. More...
#include <socketconnection.h>
Public Member Functions | |
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 PollState | connected () |
Will be called when the connection is established. More... | |
virtual void | connectionFailed (const std::string &err_msg) |
Will be called if the connection couldn't be established. | |
virtual void | closedByPeer () |
virtual PollState | readData (char *, size_t) |
Callback, called when data has arrived; len > 0. More... | |
virtual PollState | unexpectedData (char *buf, size_t len) |
Peer has sent data when it wasn't supposed to. More... | |
virtual PollState | writeData () |
Callback, called when socket is writable. 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) | |
Task * | owner () 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... | |
virtual void | setOwner (Task *t) |
Set the given task as owner of the socket. | |
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. | |
Static Public Member Functions | |
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 | |
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... | |
Friends | |
class | Engine |
Additional Inherited Members | |
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. | |
This class implements low-level socket connection operations. Inherit from it to implement protocols like HTTP.
A SocketConnection object represents a socket connection. Inherit from this class to implement a "protocol" for the connection, i.e. when/what to read/write through the connection.
Each SocketConnection is owned by a Task object. SocketConnection objects will be added to the network Engine (a part of the EventLoop) through the task's addConnection method.
The subclass will be notified through callback functions when anything happens on the socket, i.e. if the socket has been closed, if data has arrived, or if the socket is writable. You define the callback functions by overloading the below virtual functions. All operations will be performed asynchronously (non-blocking) except for dns lookups, which are performed synchronously (blocking).
Note! You must create the SocketConnection objects with new. The ownership will then be passed to the network engine. You are not allowed to delete a SocketConnection object. We will delete it when the connection has been closed, which will be
1) If you order us to close it by returning CLOSE, KEEPALIVE or KILL from a callback, or
2) After the closedByPeer callback, if the connection has been closed by peer.
3) After the connectionFailed callback, if the connection couldn't be established in the first place.
The owner task will be notified before the object is deleted.
SocketConnection::SocketConnection | ( | const std::string & | label, |
Task * | owner, | ||
const std::string & | hostname, | ||
uint16_t | port, | ||
uint16_t | iptype = 0 , |
||
struct addrinfo * | local_addr = nullptr |
||
) |
Create a SocketConnection owned by the given Task. The network Engine will connect to the given hostname/port, and notify through the below method when the connection is ready. If iptype is 4, prefer ipv4. If iptype is 6, prefer ipv6.
|
protected |
If fd is the socket descriptor of an already established connection, you may let us manage the connection by calling this constructor. fd will probably be a client socket connected through a ServerSocket.
void SocketConnection::asyncSendData | ( | const char * | buf, |
size_t | len | ||
) |
Send data to peer as soon as possible.
Helper function which you may call only during the execution of the callbacks SocketConnection::connected, SocketConnection::readData, and SocketConnection::writeData.
Send len bytes from the given buffer. The callback SocketConnection::closedByPeer might be executed before all data was sent.
If you need to send "unlimited" amounts of data, you cant use this method; instead you must use SocketConnection::sendData.
|
inline |
Send data to peer as soon as possible.
Helper function which you may call only during the execution of the callbacks SocketConnection::connected, SocketConnection::readData, and SocketConnection::writeData.
Send len bytes from the given buffer. The callback SocketConnection::closedByPeer might be executed before all data was sent.
If you need to send "unlimited" amounts of data, you cant use this method; instead you must use SocketConnection::sendData.
|
virtual |
Called when the socket has been closed by peer: May be called in states READ, WRITE, READ_WRITE
|
inlinevirtual |
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 in ShortMessageConnection, HttpServerConnection, and HttpClientConnection.
|
inlinevirtual |
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 in ShortMessageConnection, HttpServerConnection, and HttpClientConnection.
size_t SocketConnection::sendData | ( | const char * | buf, |
size_t | len | ||
) |
Try to send len bytes from the given buffer. Return the amount sent.
More accurately, this method will return the number of bytes that could be copied into the socket's send buffer.
Please understand that the return value might be < len. To safely get all data sent, you should use the SocketConnection::asyncSendData function instead. However, if you need to send large amounts of data ("large" as in "no upper limit") as fast as possible, this is the function to use.
|
protected |
Send a "message" to owner task. It will be executed as Task::msgFromConnection(this, msg) in the owner task. This is useful if you want to create SocketConnection subclasseses that work with any Task.
|
virtual |
Peer has sent data when it wasn't supposed to.
If peer sends data when we're not in state READ/READ_WRITE, this function will be called. Default is for the socket to be closed. If you return READ, any remaining async_send data will be discarded.
|
inlinevirtual |
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 in HttpServerConnection, and HttpClientConnection.