summaryrefslogtreecommitdiffstats
blob: 82fd17eea6c421c1ca017300f25500187bc1b346 (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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
/*
 * Copyright (c) 2011 Tobias Markmann
 * Licensed under the simplified BSD license.
 * See Documentation/Licenses/BSD-simplified.txt for more information.
 */

/*
 * Copyright (c) 2013 Isode Limited.
 * All rights reserved.
 * See the COPYING file for more information.
 */

#include "SOCKS5BytestreamClientSession.h"

#include <boost/bind.hpp>
#include <boost/numeric/conversion/cast.hpp>

#include <Swiften/Base/Algorithm.h>
#include <Swiften/Base/SafeByteArray.h>
#include <Swiften/Base/Concat.h>
#include <Swiften/Base/Log.h>
#include <Swiften/StringCodecs/Hexify.h>
#include <Swiften/FileTransfer/BytestreamException.h>
#include <Swiften/Network/TimerFactory.h>
#include <Swiften/Base/ByteArray.h>

namespace Swift {

SOCKS5BytestreamClientSession::SOCKS5BytestreamClientSession(
		boost::shared_ptr<Connection> connection, 
		const HostAddressPort& addressPort, 
		const std::string& destination, 
		TimerFactory* timerFactory) :
			connection(connection), 
			addressPort(addressPort), 
			destination(destination), 
			state(Initial), 
			chunkSize(131072) {
	weFailedTimeout = timerFactory->createTimer(2000);
	weFailedTimeout->onTick.connect(
			boost::bind(&SOCKS5BytestreamClientSession::handleWeFailedTimeout, this));
}

SOCKS5BytestreamClientSession::~SOCKS5BytestreamClientSession() {
}

void SOCKS5BytestreamClientSession::start() {
	assert(state == Initial);
	SWIFT_LOG(debug) << "Trying to connect via TCP to " << addressPort.toString() << "." << std::endl;
	weFailedTimeout->start();
	connectFinishedConnection = connection->onConnectFinished.connect(
			boost::bind(&SOCKS5BytestreamClientSession::handleConnectFinished, this, _1));
	connection->connect(addressPort);
}

void SOCKS5BytestreamClientSession::stop() {
	SWIFT_LOG(debug) << std::endl;
	if (state == Finished) {
		return;
	}
	closeConnection();
	readBytestream.reset();
	state = Finished;
}

void SOCKS5BytestreamClientSession::process() {
	SWIFT_LOG(debug) << "unprocessedData.size(): " << unprocessedData.size() << std::endl;
	ByteArray bndAddress;
	switch(state) {
		case Initial:
			hello();
			break;
		case Hello:
			if (unprocessedData.size() > 1) {
				unsigned char version = unprocessedData[0];
				unsigned char authMethod = unprocessedData[1];
				if (version != 5 || authMethod != 0) {
					// signal failure to upper level
					finish(true);
					return;
				}
				unprocessedData.clear();
				authenticate();
			}
			break;
		case Authenticating:
			if (unprocessedData.size() < 5) {
				// need more data to start progressing
				break;
			}
			if (unprocessedData[0] != '\x05') {
				// wrong version
				// disconnect & signal failure
				finish(true);
				break;
			}
			if (unprocessedData[1] != '\x00') {
				// no success
				// disconnect & signal failure
				finish(true);
				break;
			}
			if (unprocessedData[3] != '\x03') {
				// we expect x'03' = DOMAINNAME here
				// discconect & signal failure
				finish(true);
				break;
			}
			if (static_cast<size_t>(unprocessedData[4]) + 1 > unprocessedData.size() + 5) {
				// complete domainname and port not available yet
				break;
			}
			bndAddress = createByteArray(&vecptr(unprocessedData)[5], unprocessedData[4]);
			if (unprocessedData[unprocessedData[4] + 5] != 0 && bndAddress == createByteArray(destination)) {
				// we expect a 0 as port
				// disconnect and fail
				finish(true);
			}
			unprocessedData.clear();
			state = Ready;
			SWIFT_LOG(debug) << "session ready" << std::endl;
			// issue ready signal so the bytestream can be used for reading or writing
			weFailedTimeout->stop();
			onSessionReady(false);
			break;
		case Ready:
			SWIFT_LOG(debug) << "Received further data in Ready state." << std::endl;
			break;
		case Reading:
		case Writing:
		case Finished:
			SWIFT_LOG(debug) << "Unexpected receive of data. Current state: " << state << std::endl;
			SWIFT_LOG(debug) << "Data: " << Hexify::hexify(unprocessedData) << std::endl;
			unprocessedData.clear();
			//assert(false);
	}
}

void SOCKS5BytestreamClientSession::hello() {
	// Version 5, 1 auth method, No authentication
	const SafeByteArray hello = createSafeByteArray("\x05\x01\x00", 3);
	connection->write(hello);
	state = Hello;
}

void SOCKS5BytestreamClientSession::authenticate() {
	SWIFT_LOG(debug) << std::endl;
	SafeByteArray header = createSafeByteArray("\x05\x01\x00\x03", 4);
	SafeByteArray message = header;
	append(message, createSafeByteArray(boost::numeric_cast<char>(destination.size())));
	authenticateAddress = createByteArray(destination);
	append(message, authenticateAddress);
	append(message, createSafeByteArray("\x00\x00", 2)); // 2 byte for port
	connection->write(message);
	state = Authenticating;
}

void SOCKS5BytestreamClientSession::startReceiving(boost::shared_ptr<WriteBytestream> writeStream) {
	if (state == Ready) {
		state = Reading;
		writeBytestream = writeStream;
		writeBytestream->write(unprocessedData);
		//onBytesReceived(unprocessedData.size());
		unprocessedData.clear();
	} else {
		SWIFT_LOG(debug) << "Session isn't ready for transfer yet!" << std::endl;
	}
}

void SOCKS5BytestreamClientSession::startSending(boost::shared_ptr<ReadBytestream> readStream) {
	if (state == Ready) {
		state = Writing;
		readBytestream = readStream;
		dataWrittenConnection = connection->onDataWritten.connect(
				boost::bind(&SOCKS5BytestreamClientSession::sendData, this));
		sendData();
	} else {
		SWIFT_LOG(debug) << "Session isn't ready for transfer yet!" << std::endl;
	}
}

HostAddressPort SOCKS5BytestreamClientSession::getAddressPort() const {
	return addressPort;
}

void SOCKS5BytestreamClientSession::sendData() {
	if (!readBytestream->isFinished()) {
		try {
			boost::shared_ptr<ByteArray> dataToSend = readBytestream->read(boost::numeric_cast<size_t>(chunkSize));
			connection->write(createSafeByteArray(*dataToSend));
			onBytesSent(dataToSend->size());
		}
		catch (const BytestreamException&) {
			finish(true);
		}
	}
	else {
		finish(false);
	}
}

void SOCKS5BytestreamClientSession::finish(bool error) {
	SWIFT_LOG(debug) << std::endl;
	weFailedTimeout->stop();
	closeConnection();
	readBytestream.reset();
	if (state == Initial || state == Hello || state == Authenticating) {
		onSessionReady(true);
	}
	else {
		state = Finished;
		if (error) {
			onFinished(boost::optional<FileTransferError>(FileTransferError::ReadError));
		} else {
			onFinished(boost::optional<FileTransferError>());
		}
	}
}

void SOCKS5BytestreamClientSession::handleConnectFinished(bool error) {
	connectFinishedConnection.disconnect();
	if (error) {
		SWIFT_LOG(debug) << "Failed to connect via TCP to " << addressPort.toString() << "." << std::endl;
		finish(true);
	} else {
		SWIFT_LOG(debug) << "Successfully connected via TCP" << addressPort.toString() << "." << std::endl;
		disconnectedConnection = connection->onDisconnected.connect(
				boost::bind(&SOCKS5BytestreamClientSession::handleDisconnected, this, _1));
		dataReadConnection = connection->onDataRead.connect(
				boost::bind(&SOCKS5BytestreamClientSession::handleDataRead, this, _1));
		weFailedTimeout->start();
		process();
	}
}

void SOCKS5BytestreamClientSession::handleDataRead(boost::shared_ptr<SafeByteArray> data) {
	SWIFT_LOG(debug) << "state: " << state << " data.size() = " << data->size() << std::endl;
	if (state != Reading) {
		append(unprocessedData, *data);
		process();
	}
	else {
		writeBytestream->write(createByteArray(vecptr(*data), data->size()));
		//onBytesReceived(data->size());
	}
}

void SOCKS5BytestreamClientSession::handleDisconnected(const boost::optional<Connection::Error>& error) {
	SWIFT_LOG(debug) << (error ? (error == Connection::ReadError ? "Read Error" : "Write Error") : "No Error") << std::endl;
	if (error) {
		finish(true);
	}
}

void SOCKS5BytestreamClientSession::handleWeFailedTimeout() {
	SWIFT_LOG(debug) << "Failed due to timeout!" << std::endl;
	finish(true);
}

void SOCKS5BytestreamClientSession::closeConnection() {
	connectFinishedConnection.disconnect();
	dataWrittenConnection.disconnect();
	dataReadConnection.disconnect();
	disconnectedConnection.disconnect();
	connection->disconnect();
}

}