/
socket.cpp
317 lines (263 loc) · 8.06 KB
/
socket.cpp
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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
/*
* The Doomsday Engine Project -- libdeng2
*
* Copyright (c) 2004-2011 Jaakko Keränen <jaakko.keranen@iki.fi>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <http://www.gnu.org/licenses/>.
*/
#include "de/Socket"
#include "de/Message"
#include "de/Writer"
#include "de/Reader"
using namespace de;
/// Version of the block transfer protocol.
static const duint PROTOCOL_VERSION = 0;
/// Size of the message header in bytes.
static const duint HEADER_SIZE = 4;
/// Maximum number of channels.
static const duint MAX_CHANNELS = 2;
struct Socket::Instance
{
enum ReceptionState {
ReceivingHeader,
ReceivingPayload
};
ReceptionState receptionState;
/// Apply Huffman encoding to payload data.
bool useHuffman;
/// Number of the active channel.
duint activeChannel;
Header incomingHeader;
/// Pointer to the internal socket data.
QTcpSocket* socket;
/// Buffer for incoming received messages.
QList<Message*> receivedMessages;
/// Number of bytes waiting to be written to the socket.
dint64 bytesToBeWritten;
Instance() :
receptionState(ReceivingHeader),
useHuffman(false),
activeChannel(0),
socket(0),
bytesToBeWritten(0) {}
~Instance() {
// Delete received messages left in the buffer.
foreach(Message* msg, receivedMessages) delete msg;
}
};
Socket::Header::Header() : version(PROTOCOL_VERSION), huffman(false), channel(0), size(0) {}
Socket::Socket(const Address& address)
{
d = new Instance;
d->socket = new QTcpSocket(this);
d->socket->connectToHost(address.host(), address.port());
initialize();
}
Socket::Socket(QTcpSocket* existingSocket)
{
d = new Instance;
d->socket = existingSocket;
d->socket->setParent(this);
initialize();
}
Socket::~Socket()
{
close();
delete d;
}
void Socket::initialize()
{
connect(d->socket, SIGNAL(bytesWritten(qint64)), this, SLOT(bytesWereWritten(qint64)));
connect(d->socket, SIGNAL(disconnected()), this, SLOT(socketDisconnected()));
connect(d->socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError)));
connect(d->socket, SIGNAL(readyRead()), this, SLOT(readIncomingBytes()));
}
void Socket::close()
{
flush();
// Prevent emitting of any more signals.
d->socket->disconnect();
d->socket->close();
}
duint Socket::channel() const
{
return d->activeChannel;
}
void Socket::setChannel(duint number)
{
DENG2_ASSERT(number < MAX_CHANNELS);
d->activeChannel = number;
}
void Socket::send(const IByteArray &packet)
{
send(packet, d->activeChannel);
}
Socket& Socket::operator << (const IByteArray& packet)
{
send(packet, d->activeChannel);
return *this;
}
duint32 Socket::packHeader(const Header& header)
{
/**
* Composese the 4-byte header to the beginning of the buffer.
* - 3 bits for flags.
* - 2 bits for the protocol version number.
* - 16+11 bits for the packet length (max: 134 MB).
*/
duint32 flags =
(header.huffman? Huffman : 0) |
(header.channel == 1? Channel1 : 0);
duint32 bits = ( (header.size & 0x7ffffff) |
((header.version & 3) << 27) |
(flags << 29) );
return bits;
}
void Socket::unpackHeader(duint32 headerBytes, Header& header)
{
duint flags = (headerBytes >> 29) & 7;
header.version = (headerBytes >> 27) & 3;
header.huffman = ((flags & Huffman) != 0);
header.channel = (flags & Channel1? 1 : 0);
header.size = headerBytes & 0x7ffffff;
}
void Socket::send(const IByteArray& packet, duint channel)
{
if(!d->socket)
{
/// @throw DisconnectedError Sending is not possible because the socket has been closed.
throw DisconnectedError("Socket::operator << ", "Socket is unavailable");
}
// Keep track of where we are with the traffic.
d->bytesToBeWritten += packet.size() + 4;
// Write the packet header: packet length, version, possible flags.
Header header;
header.channel = channel;
header.size = packet.size();
Block dest;
Writer(dest) << packHeader(header);
d->socket->write(dest);
// Write the data itself.
d->socket->write(Block(packet));
}
void Socket::readIncomingBytes()
{
forever
{
if(d->receptionState == Instance::ReceivingHeader)
{
if(d->socket->bytesAvailable() >= HEADER_SIZE)
{
// Get the header.
duint32 bits = 0;
Reader(Block(d->socket->read(HEADER_SIZE))) >> bits;
unpackHeader(bits, d->incomingHeader);
// Check for valid protocols.
if(d->incomingHeader.version > PROTOCOL_VERSION)
{
/// @throw UnknownProtocolError The received data block's protocol version number
/// was not recognized. This is probably because the remote end is not a libdeng2
/// application.
throw UnknownProtocolError("Socket::readIncomingBytes", "Incoming packet has unknown protocol");
}
d->receptionState = Instance::ReceivingPayload;
}
else
{
// Let's wait until more is available.
break;
}
}
if(d->receptionState == Instance::ReceivingPayload)
{
if(d->socket->bytesAvailable() >= d->incomingHeader.size)
{
d->receivedMessages.append(new Message(Address(d->socket->peerAddress(),
d->socket->peerPort()),
d->incomingHeader.channel,
Block(d->socket->read(d->incomingHeader.size))));
// Get the next message.
d->receptionState = Instance::ReceivingHeader;
}
else
{
// Let's wait until more is available.
break;
}
}
}
// Notification about available messages.
if(!d->receivedMessages.isEmpty())
{
emit messagesReady();
}
}
Message* Socket::receive()
{
if(d->receivedMessages.isEmpty())
{
return 0;
}
return d->receivedMessages.takeFirst();
}
Message* Socket::peek()
{
if(d->receivedMessages.isEmpty())
{
return 0;
}
return d->receivedMessages.first();
}
void Socket::flush()
{
// Wait until data has been written.
d->socket->flush();
d->socket->waitForBytesWritten();
}
Address Socket::peerAddress() const
{
if(isOpen())
{
return Address(d->socket->peerAddress(), d->socket->peerPort());
}
/// @throw PeerError Could not determine the TCP/IP address of the socket.
throw PeerError("Socket::peerAddress", "Socket is unavailable");
}
bool Socket::isOpen() const
{
return d->socket && d->socket->state() != QTcpSocket::UnconnectedState;
}
void Socket::socketDisconnected()
{
emit disconnected();
}
void Socket::socketError(QAbstractSocket::SocketError /*socketError*/)
{
LOG_AS("Socket");
LOG_WARNING(d->socket->errorString());
emit disconnected(); //error(socketError);
}
bool Socket::hasIncoming() const
{
return !d->receivedMessages.empty();
}
dsize Socket::bytesBuffered() const
{
return d->bytesToBeWritten;
}
void Socket::bytesWereWritten(qint64 bytes)
{
d->bytesToBeWritten -= bytes;
DENG2_ASSERT(d->bytesToBeWritten >= 0);
}