summaryrefslogtreecommitdiff
path: root/sapsocket.cc
blob: 472865c5b2822575dd5cc393f9a2d996908122ff (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
#include <QtCore/QDebug>

#include "sappeer.h"
#include "sapconnection.h"
#include "sapsocket.h"

SAPSocket::SAPSocket(SAPConnection *conn, int sessionId, const SAPChannelInfo &chanInfo) :
	QObject(conn), _sessionId(sessionId), _info(chanInfo), _open(false),
	_seqNum(0), _expectedSeqNum(0)
{
}

SAPPeer * SAPSocket::peer()
{
	return connection()->peer();
}

SAPConnection * SAPSocket::connection()
{
	return static_cast<SAPConnection*>(parent());
}

SAPChannelInfo SAPSocket::channelInfo() const
{
	return _info;
}

bool SAPSocket::isOpen() const
{
	return _open;
}

bool SAPSocket::messageAvailable() const
{
	return !_in.empty();
}

QByteArray SAPSocket::receive()
{
	if (!_in.empty()) {
		return _in.dequeue();
	} else {
		return QByteArray();
	}
}

bool SAPSocket::send(const QByteArray &data)
{
	SAProtocol::DataFrame frame;

	frame.withSeqNum = isWithSeqNum();
	if (isReliable()) {
		frame.seqNum = _seqNum++;
	} else {
		frame.seqNum = 0;
	}
	frame.unk_1 = 0;
	frame.data = data;

	return peer()->writeToSession(_sessionId, SAProtocol::packDataFrame(frame));
}

void SAPSocket::setOpen(bool open)
{
	_open = open;
}

void SAPSocket::acceptIncomingData(const QByteArray &data)
{
	if (data.isEmpty()) return;
	SAProtocol::DataFrame frame = SAProtocol::unpackDataFrame(data, isWithSeqNum());

	if (isReliable()) {
		if (frame.seqNum != _expectedSeqNum) {
			qWarning() << "Unexpected sequence number" << frame.seqNum
					   << "on session" << _sessionId
					   << "(expected " << _expectedSeqNum << ")";
		}
		_expectedSeqNum = frame.seqNum + 1;

		// TODO Do we actually need to ack this somehow?
	}

	_in.enqueue(frame.data);

	emit messageReceived();
}

int SAPSocket::sessionId() const
{
	return _sessionId;
}

bool SAPSocket::isReliable() const
{
	return _info.qosType() == SAPChannelInfo::QoSReliabilityEnable;
}

bool SAPSocket::isWithSeqNum() const
{
	return _info.qosType() == SAPChannelInfo::QoSReliabilityDisable ||
		   _info.qosType() == SAPChannelInfo::QoSReliabilityEnable;
}