summaryrefslogtreecommitdiff
path: root/sap/sapsocket.cc
blob: 390aef0d8d1f45fc091eea99fc260ead5203f7f2 (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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
#include <QtCore/QDebug>
#include <QtCore/QTimerEvent>
#include <limits>

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

#define DELAYED_ACK_TIME 1000
#define RESEND_TIME 5000
#define WINDOW_SIZE_MSGS 10

SAPSocket::SAPSocket(SAPConnection *conn, int sessionId, const SAPChannelInfo &chanInfo) :
	QObject(conn), _sessionId(sessionId), _info(chanInfo), _open(false),
	_outLastAck(0), _outFlyingPkts(0), _inLastSeqNum(0), _inLastAck(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)
{
	if (!isOpen()) {
		qWarning() << "Socket is not yet open";
		return false;
	}

	if (data.size() > 65000) {
		qWarning() << "Fragmentation is not yet supported";
		return false;
	}

	if (isReliable()) {
		int seqNum = (_outLastAck + _out.size() + 1) % std::numeric_limits<quint16>::max();
		if (_outFlyingPkts >= WINDOW_SIZE_MSGS) {
			// Send buffer is not empty; enqueue
			qDebug() << _sessionId << "Enqueuing" << seqNum << " size=" << data.size();
		} else {
			qDebug() << _sessionId << "Sending" << seqNum << " size=" << data.size();
			sendPacket(seqNum, data);
			_outFlyingPkts++;
		}
		_out.append(data);
		if (!_resendTimer.isActive()) {
			_resendTimer.start(RESEND_TIME, Qt::CoarseTimer, this);
		}
		qDebug() << _sessionId << "pending" << _out.size() << " flying" << _outFlyingPkts;
	} else {
		// Just send the packet as is.
		sendPacket(0, data);
	}

	return true;
}

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

void SAPSocket::acceptIncomingData(const QByteArray &data)
{
	SAProtocol::DataFrame frame = SAProtocol::unpackDataFrame(data,
									isReliable(), supportsFragmentation());

	if (isReliable()) {
		quint16 expectedSeqNum = _inLastSeqNum + 1;
		if (frame.seqNum != expectedSeqNum) {
			qWarning() << "Unexpected sequence number" << frame.seqNum
					   << "on session" << _sessionId
					   << "(expected " << expectedSeqNum << ")";
		} else {
			_inLastSeqNum = frame.seqNum;
			qDebug() << _sessionId << "Got seqNum" << frame.seqNum << " size=" << data.size();

			if (!_ackTimer.isActive()) {
				_ackTimer.start(DELAYED_ACK_TIME, Qt::CoarseTimer, this);
			}
		}
	}

	_in.enqueue(frame.data);

	emit messageReceived();
}

void SAPSocket::acceptIncomingControl(const QByteArray &data)
{
	SAProtocol::ControlFrame frame = SAProtocol::unpackControlFrame(data);

	if (!isReliable()) {
		qWarning() << "Received a control frame but socket is not in QoS mode";
		return;
	}

	switch (frame.type) {
	case SAProtocol::ControlFrameBlockAck:
		handleBlockAck(frame.seqNum);
		break;
	default:
		qWarning() << "Unhandled control frame type" << frame.type;
		break;
	}
}

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

void SAPSocket::timerEvent(QTimerEvent *event)
{
	if (event->timerId() == _ackTimer.timerId()) {
		qDebug() << "Ack timer tick";
		if (_inLastSeqNum != _inLastAck) {
			sendBlockAck(_inLastSeqNum);

			_inLastAck = _inLastSeqNum;
		}
		_ackTimer.stop();
	} else if (event->timerId() == _resendTimer.timerId()) {
		qDebug() << "Resend timer tick";
		if (!_out.isEmpty()) {
			_outFlyingPkts = 0; // Assume everything went wrong
			sendPacketsFromQueue();
		} else {
			_resendTimer.stop();
		}
	} else {
		QObject::timerEvent(event);
	}
}

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

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

void SAPSocket::sendBlockAck(int seqNum)
{
	SAProtocol::ControlFrame frame;
	frame.type = SAProtocol::ControlFrameBlockAck;
	frame.seqNum = seqNum;
	peer()->writeControlToSession(_sessionId, SAProtocol::packControlFrame(frame));
}

void SAPSocket::sendPacket(int seqNum, const QByteArray &data)
{
	SAProtocol::DataFrame frame;
	frame.withSeqNum = isReliable();
	frame.seqNum = seqNum;
	frame.withFragStatus = supportsFragmentation();
	frame.fragStatus = SAProtocol::FragmentNone;
	frame.data = data;
	peer()->writeDataToSession(_sessionId, SAProtocol::packDataFrame(frame));
}

void SAPSocket::handleBlockAck(int seqNum)
{
	qDebug() << _sessionId << "Received block ack for" << seqNum;
	int n = seqNum - _outLastAck;
	if (n < 0) n += std::numeric_limits<quint16>::max();

	qDebug() << _sessionId << "pending" << _out.size() << " flying" << _outFlyingPkts << " n" << n;

	if (n <= 0) {
		qWarning() << _sessionId << "repeated ack";
		return;
	}

	if (n <= _out.size()) {
		_out.erase(_out.begin(), _out.begin() + n);
		_outLastAck += static_cast<unsigned int>(n);
		_outFlyingPkts -= n;
		qDebug() << _sessionId << "new outlastack" << _outLastAck;
	}

	qDebug() << _sessionId << "pending" << _out.size() << " flying" << _outFlyingPkts;

	Q_ASSERT(_outFlyingPkts <= _out.size());

	if (_outFlyingPkts == 0 || _out.size() == 0) {
		qDebug() << _sessionId << "Stopping resend timer";
		_resendTimer.stop();
	}

	sendPacketsFromQueue();
}

void SAPSocket::sendPacketsFromQueue()
{
	const int n = qMin(WINDOW_SIZE_MSGS, _out.size()) - _outFlyingPkts;

	Q_ASSERT(n >= 0);

	for (int i = _outFlyingPkts; i < _outFlyingPkts + n; i++) {
		int seqNum = _outLastAck + i + 1;
		const QByteArray &pkt = _out.at(i);
		qDebug() << _sessionId << "Sending packet" << seqNum << "size=" << pkt.size();
		sendPacket(seqNum, pkt);
	}

	_outFlyingPkts += n;

	Q_ASSERT(_outFlyingPkts <= _out.size());

	qDebug() << _sessionId << "pending" << _out.size() << " flying" << _outFlyingPkts << " n" << n;

	if (n > 0 && !_resendTimer.isActive()) {
		_resendTimer.start(RESEND_TIME, Qt::CoarseTimer, this);
	}
}