Classified ads
Classes | Public Types | Public Slots | Signals | Public Member Functions | Static Public Member Functions | Public Attributes | Static Public Attributes | Protected Member Functions | Protected Attributes | List of all members
Connection Class Reference

Class that represents a network connection. More...

#include <connection.h>

Inheritance diagram for Connection:
Inheritance graph
Collaboration diagram for Connection:
Collaboration graph


class  ConnectionObserver
 Interface for receiving network traffic. More...

Public Types

enum  ConnectionState { Initial, Open, Closing, Error }

Public Slots

void socketReady ()
void run ()
void encryptedBytesWritten (qint64 written)
void sslErrors (const QList< QSslError > &errors)
void socketError (QAbstractSocket::SocketError socketError)
void disconnected ()
void readyRead ()


void error (QTcpSocket::SocketError socketError)
void finished ()
void blackListNetworkAddr (QHostAddress aAddr)
void connectionAttemptFailed (const Hash &aNodeHash)

Public Member Functions

 Connection (int aSocketDescriptor, ConnectionObserver &aObserver, Model &aModel, MController &aController)
 Connection (const QHostAddress &aAddr, const int aPort, ConnectionObserver &aObserver, Model &aModel, MController &aController, const Hash &aFpOfNodeToTry)
 ~Connection ()
Nodenode () const
void setNode (Node *aNode)
QHostAddress peerAddress () const
const HashfingerPrintOfNodeAttempted ()
ConnectionState connectionState () const
ProtocolItemType stageOfBucketFill () const
void setStageOfBucketFill (ProtocolItemType aStage)
bool isInbound () const
time_t getOpenTime () const
Hash getPeerHash () const
unsigned long bytesIn () const
unsigned long bytesOut () const
bool forciblyCloseSocket ()
bool isInPrivateAddrSpace () const

Static Public Member Functions

static bool Ipv6AddressesEqual (const Q_IPV6ADDR &aAddr1, const Q_IPV6ADDR &aAddr2)

Public Attributes

QList< SendQueueItemiSendQueue
QList< QByteArray * > iNextProtocolItemToSend
bool iNeedsToRun
time_t iTimeOfLastActivity
unsigned iNumberOfPacketsReceived

Static Public Attributes

static const unsigned iMinutesBetweenBucketFill = 30

Protected Member Functions

void performRead ()
void readLoop ()
void runForIncomingConnections ()
void runForOutgoingConnections ()
void checkForBucketFill ()
void flushSocket ()
void setupSocketSignals ()
void msleep (int aMilliSeconds)

Protected Attributes

ConnectionState iConnectionState
QSslSocket * iSocket
quint32 iBytesExpectedInPacketBeingRead
QByteArray * iBytesRead
int iInvocationsSinceLastByteReceived
QHostAddress iAddrToConnect
const int iPortToConnect
const int iSocketDescriptor
const bool iSocketIsIncoming
Hash iFpOfNodeWeTrying
ProtocolItemType iStageOfBucketFill
quint32 iTimeOfBucketFill
Hash iEndOfBucket
const time_t iSocketOpenTime
unsigned long iBytesIn
unsigned long iBytesOut
QHostAddress iPeerAddress
int iBytesPendingWrite
int iSleepBetweenSendOperations
Hash iPeerHash

Detailed Description

Class that represents a network connection.

At runtime we'll have 1-n of these. This is a base-class that allows us to do some operations like "send", "receive" without needing to know if we're having a socket conn or some other kind.

Member Enumeration Documentation

Enumeration of the connection states


SYN packet sent


SSL handshake was success, peerCert is avail


Disconnection has been asked


Connection itself reports an error

Constructor & Destructor Documentation

Connection::Connection ( int  aSocketDescriptor,
ConnectionObserver aObserver,
Model aModel,
MController aController 

Constructor to use when incoming connection

Connection::Connection ( const QHostAddress &  aAddr,
const int  aPort,
ConnectionObserver aObserver,
Model aModel,
MController aController,
const Hash aFpOfNodeToTry 

Constructor. Class will initiate connetion to given addr.

aAddrnetwork address to try
aPortport in said addr
aObserverclass wishing to receive status updates about this connection
aModeldatamodel reference
aControllerapplication controller reference
aFpOfNodeToTrysometimes we need to connect some particular node ; hash of the attempted host may be given here. It is not used by connection itself but the observers may query it in case of failed connection of the connection was attempted to some particular node. In particular this logic is used by publishing engine that needs to know not only successful connections but also failed ones and for failed ones we don't get node FP via normal mechanism (node greeting)
Connection::~Connection ( )

Method for tearing down a connection

Member Function Documentation

void Connection::blackListNetworkAddr ( QHostAddress  aAddr)
unsigned long Connection::bytesIn ( ) const

returs data transfer amount

unsigned long Connection::bytesOut ( ) const

returns data transfer amount

void Connection::checkForBucketFill ( )

method for keeping buckets filled. this checks if we have content that according to its network addr should belong to that peer ; and then adds it to send queue

void Connection::connectionAttemptFailed ( const Hash aNodeHash)

Emitted when outgoing connectio fails. Used for keeping count on nodes not to try immediately again

ConnectionState Connection::connectionState ( ) const

getter method for connection state

void Connection::disconnected ( )

Connected from QSslSocket. Called on close

void Connection::encryptedBytesWritten ( qint64  written)

Connected from QSslSocket. Called when bytes have been written

void Connection::error ( QTcpSocket::SocketError  socketError)
const Hash& Connection::fingerPrintOfNodeAttempted ( )

method for getting the hash this connection was trying to attempt .. if connection was originally asked to be to some particular node, this will return hash of the node ; if connection was to no particular node, a zero hash will be returned

void Connection::finished ( )
void Connection::flushSocket ( )

method that tries to flush pending output, if platform supports

bool Connection::forciblyCloseSocket ( )

Forcibly closes socket.

true if socket was still allocated and its "abort" method got called.
time_t Connection::getOpenTime ( ) const

method for getting open time of connection

Hash Connection::getPeerHash ( ) const

method for getting peering node fingerprint. if connection is not yet open, returns KNullHash

static bool Connection::Ipv6AddressesEqual ( const Q_IPV6ADDR &  aAddr1,
const Q_IPV6ADDR &  aAddr2 

helper method for comparing ipv6 addresses

bool Connection::isInbound ( ) const

method for getting information if connection is inbound

bool Connection::isInPrivateAddrSpace ( ) const

method for checking if connection is in private (non-routable) ipv4-addr space like 192.168.. network

void Connection::msleep ( int  aMilliSeconds)

stops execution for some time

Node* Connection::node ( ) const

getter method for node of this connection. value may be null if connection is still in early stage so non-nulliness must be tested

node of connection or NULL if handshake still pending. ownership is NOT transferred, it is not ok to delete the returned pointer.
QHostAddress Connection::peerAddress ( ) const

method for getting peer addr

void Connection::performRead ( )
void Connection::readLoop ( )

called from run()

void Connection::readyRead ( )

Connected from QSslSocket. Called when bytes are available

void Connection::run ( )

this class is a kind of a thread, we need to have run ; note that right now QThread is not inherited but our worker-method is still named run, called by thread when it is started ( from networklistener or networkconnectorengine)

void Connection::runForIncomingConnections ( )

2 versions of run, called from run(),first for incoming connections

void Connection::runForOutgoingConnections ( )

2 versions of run, called from run(),then for outgoing connections

void Connection::setNode ( Node aNode)

for testing purposes only: this should never be called in production setup. this does get called from test-code

void Connection::setStageOfBucketFill ( ProtocolItemType  aStage)

Method for setting bucket fill stage. See also stageOfBucketFill.

void Connection::setupSocketSignals ( )

method that sets up signals/slots of socket

void Connection::socketError ( QAbstractSocket::SocketError  socketError)

Connected from QSslSocket::error. Called on error

void Connection::socketReady ( )

Called when socket is encrypted and ready to transmit

void Connection::sslErrors ( const QList< QSslError > &  errors)

Connected from QSslSocket. Called on handshake errors

ProtocolItemType Connection::stageOfBucketFill ( ) const

Method for getting the bucket fill stage. See explanation at documentation of the variable Connection::iStageOfBucketFill for idea how this should be used

Member Data Documentation

QHostAddress Connection::iAddrToConnect

network address to connect, if connection is outgoing connection

quint32 Connection::iBytesExpectedInPacketBeingRead

when starting to receive packet from peer, length is stored here

unsigned long Connection::iBytesIn

transferred data amount

unsigned long Connection::iBytesOut

transferred data amount

int Connection::iBytesPendingWrite

indication if write operation has been started but is not yet complete

QByteArray* Connection::iBytesRead

when reading packet from peer, this contains bytes being read

ConnectionState Connection::iConnectionState

< closed/open etc.

MController& Connection::iController

application controller reference

Hash Connection::iEndOfBucket

Where our bucket ends. Our own node fp is the start of the bucket, here is the end

Hash Connection::iFpOfNodeWeTrying

It may be that connection is asked to specific node, in addition to being into some known network address. If the node is known, store the target node fingerprintin here. This is used at least in wishlist-connections where the connection itself will signal its open-for-business state when connection to asked node is ready

int Connection::iInvocationsSinceLastByteReceived

this variable here is used as counter during pending read of data packet, zeroed every time bytes are received ; if it reaches high number (a sign of stalled download) do drop connection to that peer

const unsigned Connection::iMinutesBetweenBucketFill = 30

how often peers are queried for new content to send/receive ; this is also max permitted lenght for data transmission inactivity ; nodes that have been idle longer than this are considered "dead"

Model& Connection::iModel

datamodel reference

bool Connection::iNeedsToRun

if set to false, connection closes itself

QList<QByteArray *> Connection::iNextProtocolItemToSend

This is the next item to send. This does not include the length. .. as protocol items over socket are sent so that length goes first, as uint32, followed by that many bytes. This QByteArray contains the bytes, not the uint32 that goes first. Reason is that this is wanted this way is that the class doing the sending to be aware of the length, forcing this way it to calculate it itself.

Node* Connection::iNodeOfConnectedPeer

node-data-structure of the connected node

unsigned Connection::iNumberOfPacketsReceived

nr of received complete protocol packets

ConnectionObserver& Connection::iObserver

received data is sent to ConnectionObserver

QHostAddress Connection::iPeerAddress

storage for peeraddress

Hash Connection::iPeerHash

hash of peering node

const int Connection::iPortToConnect

port to connect, if connection is outgoing connection

QList<SendQueueItem> Connection::iSendQueue

many things going on inside classified ads are about the connected node ; when node is disconnected, we may forget about many things that may have been in progress. therefore it may make sense to store also the queue of things to send in here ; when connection goes away, so goes the queue and no further processing needed.

The order of things in this list is significant, the first item to be append()ed should be sent first.

int Connection::iSleepBetweenSendOperations

How many milliseconds to sleep between send operations

QSslSocket* Connection::iSocket

socket for data transfer: the actual socket is owned by stack frame of the thread so even tough we have this pointer here, it may not be deleted

const int Connection::iSocketDescriptor

descriptor of already-connected socket if connection is incoming-connection

const bool Connection::iSocketIsIncoming

true if incoming socket

const time_t Connection::iSocketOpenTime

time of socket open

ProtocolItemType Connection::iStageOfBucketFill

method of handling around network churn is implemented in several places. .. churn requires us to copy stuff beloging to NodesAroundHash ( see nodemodel ) to nodes that are in the same bucket with us. Our concept of bucket is a bit stretched but there is kind of bucket and we will send of over new data to nodes that we think belongs to the bucket of connecting node.

sending the data happens in several stages, connection itself stores the stage here. filling the bucket according to stage then happens in NodeModel::getNextItemToSend method

quint32 Connection::iTimeOfBucketFill

time of last bucket fill

time_t Connection::iTimeOfLastActivity

last time there was any traffic with peer

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