src.dualinventive.com/dinet/sec-multi-proxy/include/server/TCPConnection.h

130 lines
2.9 KiB
C++

/**
* @file include/server/TCPConnection.h
* @brief The TCP connection class
* @copyright 2015 Dual Inventive Technology Centre B.V.
*
* TCP Connection wrapper around POSIX client sockets
*/
#ifndef INCLUDE_SERVER_TCPCONNECTION_H_
#define INCLUDE_SERVER_TCPCONNECTION_H_
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <string>
#include <map>
#include <memory>
#include <mutex>
#include <vector>
#include <di/Timer.h>
#include <di/Buffer.h>
#include <di/Mailbox.h>
#include <di/encryption.h>
class QueuedMessage;
class TCPConnection {
public:
enum SelectResult {
SELECT_TIMEOUT,
SELECT_READ,
SELECT_ERROR
};
enum ReadResult {
READ_NONE,
READ_DATA,
READ_EOF,
READ_ERROR
};
const size_t kReadSize = 1024;
const int kTimeoutMs = 10000;
bool closing; /**< bool to initiate closing a connection*/
/**
* constructor for TCP connection
* @param sock socket number
* @param info info on socket address
*/
TCPConnection(int sock, const struct sockaddr_in &info);
/**
* Destuctor for TCP connection, closes connection
*/
~TCPConnection();
/**
* Returns the connection information in the format:
* `"<remote addr>:<remote port>"`
*/
std::string getPeer();
/**
* select connection
* @param timeoutMs miliseconds till timeout should be triggered
* @return Result of the select
*/
enum SelectResult select(size_t timeoutMs);
/**
* read from the connection
* @return returns result of the read
*/
enum ReadResult read(void);
/**
* write to the connection, sets __errno on failure
* @return true if succes, false if failed
*/
bool write(const std::shared_ptr<Di::Buffer> &buf);
/**
* Returns the POSIX error code which (can) be happened to the
* connection.
*/
int getErrno(void);
/**
* get the buffer
* @return retuns buffer pointer
*/
std::shared_ptr<Di::Buffer> getBuffer(void);
void queueRequest(const std::shared_ptr<struct Message> &msg);
std::shared_ptr<struct Message> getRequest(void);
/**
* DI-Net timestamp when the last incoming data was seen.
*/
uint64_t lastReadTime(void);
void addDeviceUid(const std::string &deviceUid);
void removeDeviceUid(const std::string &deviceUid);
std::vector<std::string> getDeviceUids(void);
bool isAuthenticated(void);
private:
int __sockFd; /**< socked number*/
std::string __peerIp; /**< peer IP address*/
unsigned int __peerPort; /**< peer port number*/
std::shared_ptr<Di::Buffer> __rxBuffer; /**< pointer to read buffer*/
int __errno; /**< error number*/
Di::Mailbox<struct Message> __requestQueue; /**< mailbox for requests*/
uint64_t __lastReadTime; /**< time of the last read*/
std::vector<std::string> __deviceUids; /**< device unique Identifiers */
/**
* set the socket to have no delay
*/
int __setNoDelay();
/**
* set the timeout of the socket
*/
int __setTimeout();
};
#endif // INCLUDE_SERVER_TCPCONNECTION_H_