13 #define MAX_MSG_LEN 60000
15 #define BYTE_SWAP4(x) \
16 ((((x) & 0xFF000000u) >> 24) | \
17 (((x) & 0x00FF0000u) >> 8) | \
18 (((x) & 0x0000FF00u) << 8) | \
19 (((x) & 0x000000FFu) << 24))
21 #define BYTE_SWAP2(x) \
22 ((((x) & 0xFF00u) >> 8) | \
23 (((x) & 0x00FFu) << 8))
25 static quint16
_htons(
const quint16 x)
27 if (QSysInfo::ByteOrder == QSysInfo::BigEndian)
32 static quint32
_htonl(
const quint32 x)
34 if (QSysInfo::ByteOrder == QSysInfo::BigEndian)
39 static quint16
_ntohs(
const char *in)
41 return quint16(quint8(in[0]) << 8
45 static quint32
_ntohl(
const char *in)
47 return quint32(quint8(in[0])) << 24
48 | quint32(quint8(in[1])) << 16
49 | quint32(quint8(in[2])) << 8
50 | quint32(quint8(in[3]));
59 _buffer(nullptr), _bufferSize(0), _bufferPos(0), _lastBufferSize(0), _mode(0)
85 qDebug(
"NetworkMessage::readMessage(TCP) called when class was in mode %d!",
_mode);
96 qDebug(
"FIXME: Socket said 8 bytes available, but could not read 8...");
109 qDebug(
"Socket read failed (TCP), return code %d",
int(ret));
128 qDebug(
"NetworkMessage::readMessage(UDP) called when class was in mode %d!",
_mode);
134 qDebug(
"UDP message shorter than 8 bytes. ignored.");
148 if (header[0] !=
'P' || header[1] !=
'V' || header[2] !=
'S' || header[3] !=
'2') {
149 qDebug(
"Protocol magic wrong.");
155 qDebug(
"Disconnecting Client: MAX_MSG_LEN exceeded.");
159 qDebug(
"A Client sent an empty message.");
169 const quint16 keyLen =
_ntohs(ptr);
171 const quint16 valLen =
_ntohs(ptr);
173 if (
_bufferSize - (ptr - buffer) < keyLen + valLen) {
174 qDebug() <<
"Warning: Error parsing message. key(" << keyLen <<
")+value(" << valLen
175 <<
") length > total remaining bytes (" << (
_bufferSize - (ptr - buffer)) <<
")";
178 _fields.insert(QByteArray(ptr, keyLen), QByteArray(ptr + keyLen, valLen));
180 ptr += keyLen + valLen;
190 qDebug(
"NetworkMessage::writeMessage called when class was in mode %d!",
_mode);
217 qDebug(
"NetworkMessage::writeMessage called when class was in mode %d!",
_mode);
241 for (QHash<QByteArray, QByteArray>::const_iterator it =
_fields.begin(); it !=
_fields.end(); ++it) {
242 const QByteArray &ba = it.key();
243 const QByteArray &val = it.value();
244 quint16 keyLen =
_htons(quint16(ba.size()));
245 quint16 valLen =
_htons(quint16(val.size()));
247 buf.append(reinterpret_cast<const char*>(&keyLen), 2);
248 buf.append(reinterpret_cast<const char*>(&valLen), 2);
260 memcpy(
_buffer + 4, &flipped, 4);
#define NM_READ_INCOMPLETE
bool writeMessage(QAbstractSocket *socket)
bool parseHeader(char *header)
virtual ~NetworkMessage()
int readMessage(QAbstractSocket *socket)
static quint32 _htonl(const quint32 x)
QHash< QByteArray, QByteArray > _fields
static quint16 _htons(const quint16 x)
static quint16 _ntohs(const char *in)
void setField(const QByteArray &key, const QByteArray &value)
static quint32 _ntohl(const char *in)
bool parseMessage(char *buffer)
void buildErrorMessage(const QString &error)