summaryrefslogtreecommitdiffstats
path: root/src/shared/networkmessage.h
blob: 327f5445398969dd8bc31ead05e906881d4bf4dc (plain) (blame)
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
/*
 * NetworkMessage.h
 *
 *  Created on: 18.01.2013
 *      Author: sr
 */

#ifndef NETWORKMESSAGE_H_
#define NETWORKMESSAGE_H_

#define NM_READ_OK (1)
#define NM_READ_INCOMPLETE (2)
#define NM_READ_FAILED (0)

#include <QHostAddress>
#include <QByteArray>
#include <QString>

class QAbstractSocket;
class QUdpSocket;

// define QByteArrays for message ids. this prevents implicit instantiation of the same QByteArray over and over again
#define MSGTYPE(name) static const QByteArray _ ## name ( #name )
MSGTYPE(ID);
MSGTYPE(IMG);
MSGTYPE(LOGIN);
MSGTYPE(THUMB);
MSGTYPE(X);
MSGTYPE(Y);
MSGTYPE(VNCSERVER);
MSGTYPE(VNCCLIENT);
MSGTYPE(LOCK);
MSGTYPE(HASH);
MSGTYPE(SALT1);
MSGTYPE(SALT2);
MSGTYPE(IPLIST);
MSGTYPE(PORT);
MSGTYPE(CERT);
MSGTYPE(CHALLENGE);
MSGTYPE(ENABLE);
MSGTYPE(ERROR);
MSGTYPE(TUTOR);
MSGTYPE(EXAMMODE);
MSGTYPE(ATTENTION);


static const QByteArray __TRUE("1");
static const QByteArray __FALSE("0");
static const inline QByteArray& _BOOL(bool val) { if (val) return __TRUE; return __FALSE; }

class NetworkMessage
{
private:
	char *_buffer;
	quint32 _bufferSize, _bufferPos, _lastBufferSize;
	QHash<QByteArray, QByteArray> _fields;
	int _mode; // 0 = none, 1 = reading, 2 = writing, 3 = read complete, 4 = write complete

	void allocBuffer();
	bool parseHeader(char *header);
	bool parseMessage(char *buffer);
	void serializeMessage();

public:
	NetworkMessage();
	virtual ~NetworkMessage();
	int readMessage(QAbstractSocket *socket);
	int readMessage(char* data, quint32 len);
	bool writeMessage(QAbstractSocket *socket);
	bool writeMessage(QUdpSocket* socket, const QHostAddress& address, quint16 port);
	void reset() { _fields.clear(); _bufferSize = 0; _mode = 0; }
	bool readComplete() const { return _mode == 3; }
	bool writeComplete() const { return _mode == 4; }
	bool hasField(QByteArray& key) { return _fields.contains(key); }
	QString getFieldString(const QByteArray& key) const { return QString::fromUtf8(_fields.value(key)); }
	QByteArray getFieldBytes(const QByteArray& key) const { return _fields.value(key); }
	void setField(const QByteArray& key, const QByteArray& value) { if (_mode == 1 || _mode == 2) qFatal("setField called in bad state."); _fields.insert(key, value); _mode = 0; }
	void setField(const QByteArray& key, const QString& value) { setField(key, value.toUtf8()); }
	// Convenience
	void buildErrorMessage(const QString& error);
};

#endif /* NETWORKMESSAGE_H_ */