summaryrefslogtreecommitdiff
path: root/sapbtpeer.cc
blob: 188c37b929a2e5aa2e0b40aedd7b4b8aff80c816 (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
#include <QtCore/QtEndian>
#include "saprotocol.h"
#include "wmspeer.h"
#include "crc16.h"
#include "sapsocket.h"
#include "sapbtpeer.h"

#define PROTO_DEBUG 0

SAPBTPeer::SAPBTPeer(SAProtocol::Role role, QBluetoothSocket *socket, QObject *parent) :
    SAPPeer(role, socket->localAddress().toString(), socket->peerAddress().toString(), parent),
    _socket(socket),
    _curFrameLength(0),
    _peerDescriptionExchangeDone(false), _authenticationDone(false)
{
	connect(_socket, SIGNAL(readyRead()), SLOT(handleSocketData()));
	connect(_socket, SIGNAL(disconnected()), SLOT(handleSocketDisconnected()));
}

void SAPBTPeer::handleSocketData()
{
	uint bytes = _socket->bytesAvailable();
	const bool need_crc = _peerDescriptionExchangeDone && _authenticationDone;
	const uint header_size = need_crc ? 2 * sizeof(quint16) : 1 * sizeof(quint16);
	const uint footer_size = need_crc ? sizeof(quint16) : 0;

	while ((_curFrameLength == 0 && bytes >= header_size) ||
	       (_curFrameLength > 0 && bytes >= _curFrameLength + footer_size)) {
		if (_curFrameLength > 0) {
			// We are waiting for a full frame of known length
			QByteArray frame = _socket->read(_curFrameLength);
			Q_ASSERT(frame.size() == (int)_curFrameLength);
			_curFrameLength = 0;

			if (need_crc) {
				quint16 computed_crc = crc16(0, reinterpret_cast<const quint8*>(frame.constData()), frame.size());
				quint16 crc;
				_socket->read(reinterpret_cast<char*>(&crc), sizeof(quint16));
				crc = qFromBigEndian(crc);

				if (crc != computed_crc) {
					qWarning() << "CRC data failure";
					_socket->close(); // Drop the connection, no provision for resync.
					return;
				}
			}

			handleFrame(frame);
		} else {
			quint16 frame_length;
			bytes = _socket->read(reinterpret_cast<char*>(&frame_length), sizeof(quint16));
			Q_ASSERT(bytes == sizeof(quint16));
			_curFrameLength = qFromBigEndian(frame_length);
			Q_ASSERT(_curFrameLength > 0);

			if (need_crc) {
				// Compute the checksum of the BIG ENDIAN frame length.
				quint16 computed_crc = crc16(0, reinterpret_cast<quint8*>(&frame_length), sizeof(quint16));
				quint16 crc;
				_socket->read(reinterpret_cast<char*>(&crc), sizeof(quint16));
				crc = qFromBigEndian(crc);

				if (crc != computed_crc) {
					qWarning() << "CRC length failure";
					_curFrameLength = 0;
					_socket->close(); // Drop the connection, no provision for resync.
					return;
				}
			}
		}

		bytes = _socket->bytesAvailable();
	}
}

void SAPBTPeer::handleSocketDisconnected()
{
	qDebug() << "Socket disconnected";
	handleDisconnected();
}

void SAPBTPeer::sendFrame(const QByteArray &data)
{
	const bool need_crc = _peerDescriptionExchangeDone && _authenticationDone;
	quint16 frame_length = qToBigEndian<quint16>(data.length());
	_socket->write(reinterpret_cast<const char*>(&frame_length), sizeof(quint16));

	// Compute the checksum of the BIG ENDIAN frame length.
	if (need_crc) {
		quint16 crc = qToBigEndian(crc16(0, reinterpret_cast<quint8*>(&frame_length), sizeof(quint16)));
		_socket->write(reinterpret_cast<const char*>(&crc), sizeof(quint16));
	}

	_socket->write(data.constData(), data.size());

	if (need_crc) {
		quint16 crc = qToBigEndian(crc16(0, reinterpret_cast<const quint8*>(data.constData()), data.size()));
		_socket->write(reinterpret_cast<const char*>(&crc), sizeof(quint16));
	}

#if PROTO_DEBUG
	qDebug() << "Sent:" << data.toHex();
#endif
}

void SAPBTPeer::handleFrame(const QByteArray &data)
{
#if PROTO_DEBUG
	qDebug() << "Recv:" << data.toHex();
#endif

	if (!_peerDescriptionExchangeDone) {
		// This must be a peer description frame!
		SAProtocol::PeerDescription peerDesc = SAProtocol::unpackPeerDescription(data);
		qDebug() << peerDesc.product << peerDesc.manufacturer << peerDesc.name;
		qDebug() << "apdu=" << peerDesc.APDUSize << "ssdu=" << peerDesc.SSDUSize
				 << "sessions=" << peerDesc.sessions << "timeout=" << peerDesc.timeout;

		SAProtocol::PeerDescription myDesc = peerDesc;
		myDesc.messageType = 6; // Why?
		myDesc.status = 0; // This seems to be "accepted"
		myDesc.product = "RandomPhone";
		myDesc.manufacturer = "me";
		myDesc.name = "gearbttest";
		myDesc.profile = "SWatch"; // This is what Gear manager sends

		sendFrame(SAProtocol::packPeerDescription(myDesc));

		_peerDescriptionExchangeDone = true;
	} else if (!_authenticationDone) {
		// This must be a authentication frame...
		handleAuthenticationFrame(data);
	} else {
		SAProtocol::Frame frame = SAProtocol::unpackFrame(data);
		switch (frame.type) {
		case SAProtocol::FrameData:
			handleDataFrame(frame);
			break;
		case SAProtocol::FrameControl:
			handleControlFrame(frame);
			break;
		default:
			qWarning() << "Unknown frame type" << frame.type;
			break;
		}
	}
}

void SAPBTPeer::handleDataFrame(const SAProtocol::Frame &frame)
{
	Q_ASSERT(frame.type == SAProtocol::FrameData);

	handleSessionData(frame.sessionId, frame.data);
}

void SAPBTPeer::handleControlFrame(const SAProtocol::Frame &frame)
{
	Q_ASSERT(frame.type == SAProtocol::FrameControl);

	handleSessionControl(frame.sessionId, frame.data);
}

void SAPBTPeer::handleAuthenticationFrame(const QByteArray &data)
{
	SAProtocol::SecurityFrame sframe = SAProtocol::unpackSecurityFrame(data);

	switch (sframe.type) {
	case SAProtocol::SecurityAuthenticateRequest: {
		qDebug() << "Starting authorization...";
		SAProtocol::SecurityFrame response = _wms->respondToServerChallenge(sframe);
		if (!response.data.isEmpty()) {
			sendFrame(SAProtocol::packSecurityFrame(response));
		}
		break;
	}
	case SAProtocol::SecurityAuthenticateConfirm: {
		_authenticationDone = _wms->verifyServerResponse(sframe);
		if (_authenticationDone) {
			qDebug() << "Authentication confirmed";
			handleConnected();
		} else {
			qWarning() << "Authentication failure, closing connection";
			_socket->close(); // Will call "handleDisconnected" and emit disconnected signals.
		}
		break;
	}
	default:
		qWarning() << "Unknown security frame type" << sframe.type;
		break;
	}
}