aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/libs/poco/Net/src/FTPClientSession.cpp
blob: e0bf4489832ca7ed763d86116fb59cfbbad41163 (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
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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
//
// FTPClientSession.cpp
//
// Library: Net
// Package: FTP
// Module:  FTPClientSession
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier:	BSL-1.0
//


#include "Poco/Net/FTPClientSession.h"
#include "Poco/Net/SocketAddress.h"
#include "Poco/Net/SocketStream.h"
#include "Poco/Net/ServerSocket.h"
#include "Poco/Net/NetException.h"
#include "Poco/NumberFormatter.h"
#include "Poco/Ascii.h"


using Poco::NumberFormatter;


namespace Poco {
namespace Net {


FTPClientSession::FTPClientSession():
	_port(0),
	_pControlSocket(0),
	_pDataStream(0),
	_passiveMode(true),
	_fileType(TYPE_BINARY),
	_supports1738(true),
	_serverReady(false),
	_isLoggedIn(false),
	_timeout(DEFAULT_TIMEOUT)
{
}

	
FTPClientSession::FTPClientSession(const StreamSocket& socket):
	_host(socket.address().host().toString()),
	_port(socket.address().port()),
	_pControlSocket(new DialogSocket(socket)),
	_pDataStream(0),
	_passiveMode(true),
	_fileType(TYPE_BINARY),
	_supports1738(true),
	_serverReady(false),
	_isLoggedIn(false),
	_timeout(DEFAULT_TIMEOUT)
{
	_pControlSocket->setReceiveTimeout(_timeout);
}


FTPClientSession::FTPClientSession(const std::string& host,
	Poco::UInt16 port,
	const std::string& username,
	const std::string& password):
	_host(host),
	_port(port),
	_pControlSocket(new DialogSocket(SocketAddress(host, port))),
	_pDataStream(0),
	_passiveMode(true),
	_fileType(TYPE_BINARY),
	_supports1738(true),
	_serverReady(false),
	_isLoggedIn(false),
	_timeout(DEFAULT_TIMEOUT)
{
	if (!username.empty())
		login(username, password);
	else
		_pControlSocket->setReceiveTimeout(_timeout);
}


FTPClientSession::~FTPClientSession()
{
	try
	{
		close();
	}
	catch (...) 
	{
	}
}


void FTPClientSession::setTimeout(const Poco::Timespan& timeout)
{
	if (!isOpen())
		throw FTPException("Connection is closed.");

	_timeout = timeout;
	_pControlSocket->setReceiveTimeout(timeout);
}

	
Poco::Timespan FTPClientSession::getTimeout() const
{
	return _timeout;
}


void FTPClientSession::setPassive(bool flag, bool useRFC1738)
{
	_passiveMode  = flag;
	_supports1738 = useRFC1738;
}

	
bool FTPClientSession::getPassive() const
{
	return _passiveMode;
}


void FTPClientSession::open(const std::string& host,
	Poco::UInt16 port,
	const std::string& username,
	const std::string& password)
{
	_host = host;
	_port = port;
	if (!username.empty())
	{
		login(username, password);
	}
	else
	{
		_pControlSocket = new DialogSocket(SocketAddress(_host, _port));
		_pControlSocket->setReceiveTimeout(_timeout);
	}
}


void FTPClientSession::login(const std::string& username, const std::string& password)
{
	if (_isLoggedIn) logout();

	int status = FTP_POSITIVE_COMPLETION * 100;
	std::string response;
	if (!_pControlSocket)
	{
		_pControlSocket = new DialogSocket(SocketAddress(_host, _port));
		_pControlSocket->setReceiveTimeout(_timeout);
	}

	if (!_serverReady)
	{
		status = _pControlSocket->receiveStatusMessage(response);
		if (!isPositiveCompletion(status))
			throw FTPException("Cannot login to server", response, status);

		_serverReady = true;
	}

	status = sendCommand("USER", username, response);
	if (isPositiveIntermediate(status))
		status = sendCommand("PASS", password, response);
	if (!isPositiveCompletion(status)) 
		throw FTPException("Login denied", response, status);

	setFileType(_fileType);
	_isLoggedIn = true;
}


void FTPClientSession::logout()
{
	if (!isOpen())
		throw FTPException("Connection is closed.");

	if (_isLoggedIn)
	{
		try { endTransfer(); }
		catch (...) { }
		_isLoggedIn = false;
		std::string response;
		sendCommand("QUIT", response);
	}
}


void FTPClientSession::close()
{
	try { logout(); }
	catch (...) {}
	_serverReady = false;
	if (_pControlSocket)
	{
		_pControlSocket->close();
		delete _pControlSocket;
		_pControlSocket = 0;
	}
}


void FTPClientSession::setFileType(FTPClientSession::FileType type)
{
	std::string response;
	int status = sendCommand("TYPE", (type == TYPE_TEXT ? "A" : "I"), response);
	if (!isPositiveCompletion(status)) throw FTPException("Cannot set file type", response, status);
	_fileType = type;
}


FTPClientSession::FileType FTPClientSession::getFileType() const
{
	return _fileType;
}


std::string FTPClientSession::systemType()
{
	std::string response;
	int status = sendCommand("SYST", response);
	if (isPositiveCompletion(status))
		return response.substr(4);
	else
		throw FTPException("Cannot get remote system type", response, status);
}


void FTPClientSession::setWorkingDirectory(const std::string& path)
{
	std::string response;
	int status = sendCommand("CWD", path, response);
	if (!isPositiveCompletion(status))
		throw FTPException("Cannot change directory", response, status);
}


std::string FTPClientSession::getWorkingDirectory()
{
	std::string response;
	int status = sendCommand("PWD", response);
	if (isPositiveCompletion(status))
		return extractPath(response);
	else
		throw FTPException("Cannot get current working directory", response, status);
}


void FTPClientSession::cdup()
{
	std::string response;
	int status = sendCommand("CDUP", response);
	if (!isPositiveCompletion(status))
		throw FTPException("Cannot change directory", response, status);
}

	
void FTPClientSession::rename(const std::string& oldName, const std::string& newName)
{
	std::string response;
	int status = sendCommand("RNFR", oldName, response);
	if (!isPositiveIntermediate(status)) 
		throw FTPException(std::string("Cannot rename ") + oldName, response, status);
	status = sendCommand("RNTO", newName, response);
	if (!isPositiveCompletion(status)) 
		throw FTPException(std::string("Cannot rename to ") + newName, response, status);
}

	
void FTPClientSession::remove(const std::string& path)
{
	std::string response;
	int status = sendCommand("DELE", path, response);
	if (!isPositiveCompletion(status)) 
		throw FTPException(std::string("Cannot remove " + path), response, status);
}


void FTPClientSession::createDirectory(const std::string& path)
{
	std::string response;
	int status = sendCommand("MKD", path, response);
	if (!isPositiveCompletion(status)) 
		throw FTPException(std::string("Cannot create directory ") + path, response, status);
}


void FTPClientSession::removeDirectory(const std::string& path)
{
	std::string response;
	int status = sendCommand("RMD", path, response);
	if (!isPositiveCompletion(status)) 
		throw FTPException(std::string("Cannot remove directory ") + path, response, status);
}


std::istream& FTPClientSession::beginDownload(const std::string& path)
{
	if (!isOpen())
		throw FTPException("Connection is closed.");

	delete _pDataStream;
	_pDataStream = 0;
	_pDataStream = new SocketStream(establishDataConnection("RETR", path));
	return *_pDataStream;
}

	
void FTPClientSession::endDownload()
{
	endTransfer();
}

	
std::ostream& FTPClientSession::beginUpload(const std::string& path)
{
	if (!isOpen())
		throw FTPException("Connection is closed.");

	delete _pDataStream;
	_pDataStream = 0;
	_pDataStream = new SocketStream(establishDataConnection("STOR", path));
	return *_pDataStream;
}


void FTPClientSession::endUpload()
{
	endTransfer();
}


std::istream& FTPClientSession::beginList(const std::string& path, bool extended)
{
	if (!isOpen())
		throw FTPException("Connection is closed.");

	delete _pDataStream;
	_pDataStream = 0;
	_pDataStream = new SocketStream(establishDataConnection(extended ? "LIST" : "NLST", path));
	return *_pDataStream;
}


void FTPClientSession::endList()
{
	endTransfer();
}

	
void FTPClientSession::abort()
{
	if (!isOpen())
		throw FTPException("Connection is closed.");

	_pControlSocket->sendByte(DialogSocket::TELNET_IP);
	_pControlSocket->synch();
	std::string response;
	int status = sendCommand("ABOR", response);
	if (status == 426)
		status = _pControlSocket->receiveStatusMessage(response);
	if (status != 226) 
		throw FTPException("Cannot abort transfer", response, status);
}


int FTPClientSession::sendCommand(const std::string& command, std::string& response)
{
	if (!isOpen())
		throw FTPException("Connection is closed.");

	_pControlSocket->sendMessage(command);
	return _pControlSocket->receiveStatusMessage(response);
}


int FTPClientSession::sendCommand(const std::string& command, const std::string& arg, std::string& response)
{
	if (!isOpen())
		throw FTPException("Connection is closed.");

	_pControlSocket->sendMessage(command, arg);
	return _pControlSocket->receiveStatusMessage(response);
}


std::string FTPClientSession::extractPath(const std::string& response)
{
	std::string path;
	std::string::const_iterator it  = response.begin();
	std::string::const_iterator end = response.end();
	while (it != end && *it != '"') ++it;
	if (it != end)
	{
		++it;
		while (it != end)
		{
			if (*it == '"')
			{
				++it;
				if (it == end || (it != end && *it != '"')) break;
			}
			path += *it++;
		}
	}
	return path;
}


StreamSocket FTPClientSession::establishDataConnection(const std::string& command, const std::string& arg)
{
	if (_passiveMode)
		return passiveDataConnection(command, arg);
	else
		return activeDataConnection(command, arg);
}


StreamSocket FTPClientSession::activeDataConnection(const std::string& command, const std::string& arg)
{
	if (!isOpen())
		throw FTPException("Connection is closed.");

	ServerSocket server(SocketAddress(_pControlSocket->address().host(), 0));
	sendPortCommand(server.address());
	std::string response;
	int status = sendCommand(command, arg, response);
	if (!isPositivePreliminary(status)) 
		throw FTPException(command + " command failed", response, status);
	if (server.poll(_timeout, Socket::SELECT_READ))
		return server.acceptConnection();
	else
		throw FTPException("The server has not initiated a data connection");
}


StreamSocket FTPClientSession::passiveDataConnection(const std::string& command, const std::string& arg)
{
	SocketAddress sa(sendPassiveCommand());
	StreamSocket sock(sa);
	std::string response;
	int status = sendCommand(command, arg, response);
	if (!isPositivePreliminary(status)) 
		throw FTPException(command + " command failed", response, status);
	return sock;
}


void FTPClientSession::sendPortCommand(const SocketAddress& addr)
{
	if (_supports1738)
	{
		if (sendEPRT(addr))
			return;
		else
			_supports1738 = false;
	}
	sendPORT(addr);
}


SocketAddress FTPClientSession::sendPassiveCommand()
{
	SocketAddress addr;
	if (_supports1738)
	{
		if (sendEPSV(addr))
			return addr;
		else
			_supports1738 = false;
	}
	sendPASV(addr);
	return addr;
}


bool FTPClientSession::sendEPRT(const SocketAddress& addr)
{
	std::string arg("|");
	arg += addr.af() == AF_INET ? '1' : '2';
	arg += '|';
	arg += addr.host().toString();
	arg += '|';
	arg += NumberFormatter::format(addr.port());
	arg += '|';
	std::string response;
	int status = sendCommand("EPRT", arg, response);
	if (isPositiveCompletion(status))
		return true;
	else if (isPermanentNegative(status))
		return false;
	else
		throw FTPException("EPRT command failed", response, status);
}


void FTPClientSession::sendPORT(const SocketAddress& addr)
{
	std::string arg(addr.host().toString());
	for (std::string::iterator it = arg.begin(); it != arg.end(); ++it)
	{
		if (*it == '.') *it = ',';
	}
	arg += ',';
	Poco::UInt16 port = addr.port();
	arg += NumberFormatter::format(port/256);
	arg += ',';
	arg += NumberFormatter::format(port % 256);
	std::string response;
	int status = sendCommand("PORT", arg, response);
	if (!isPositiveCompletion(status)) 
		throw FTPException("PORT command failed", response, status);
}


bool FTPClientSession::sendEPSV(SocketAddress& addr)
{
	std::string response;
	int status = sendCommand("EPSV", response);
	if (isPositiveCompletion(status))
	{
		parseExtAddress(response, addr);
		return true;
	}
	else if (isPermanentNegative(status))
	{
		return false;
	}
	else throw FTPException("EPSV command failed", response, status);
}


void FTPClientSession::sendPASV(SocketAddress& addr)
{
	std::string response;
	int status = sendCommand("PASV", response);
	if (!isPositiveCompletion(status)) 
		throw FTPException("PASV command failed", response, status);
	parseAddress(response, addr);
}


void FTPClientSession::parseAddress(const std::string& str, SocketAddress& addr)
{
	std::string::const_iterator it  = str.begin();
	std::string::const_iterator end = str.end();
	while (it != end && *it != '(') ++it;
	if (it != end) ++it;
	std::string host;
	while (it != end && Poco::Ascii::isDigit(*it)) host += *it++;
	if (it != end && *it == ',') { host += '.'; ++it; }
	while (it != end && Poco::Ascii::isDigit(*it)) host += *it++;
	if (it != end && *it == ',') { host += '.'; ++it; }
	while (it != end && Poco::Ascii::isDigit(*it)) host += *it++;
	if (it != end && *it == ',') { host += '.'; ++it; }
	while (it != end && Poco::Ascii::isDigit(*it)) host += *it++;
	if (it != end && *it == ',') ++it;
	Poco::UInt16 portHi = 0;
	while (it != end && Poco::Ascii::isDigit(*it)) { portHi *= 10; portHi += *it++ - '0'; }
	if (it != end && *it == ',') ++it;
	Poco::UInt16 portLo = 0;
	while (it != end && Poco::Ascii::isDigit(*it)) { portLo *= 10; portLo += *it++ - '0'; }
	addr = SocketAddress(host, portHi*256 + portLo);
}


void FTPClientSession::parseExtAddress(const std::string& str, SocketAddress& addr)
{
	std::string::const_iterator it  = str.begin();
	std::string::const_iterator end = str.end();
	while (it != end && *it != '(') ++it;
	if (it != end) ++it;
	char delim = '|';
	if (it != end) delim = *it++;
	if (it != end && *it == delim) ++it;
	if (it != end && *it == delim) ++it;
	Poco::UInt16 port = 0;
	while (it != end && Poco::Ascii::isDigit(*it)) { port *= 10; port += *it++ - '0'; }	
	addr = SocketAddress(_pControlSocket->peerAddress().host(), port);	
}


void FTPClientSession::endTransfer()
{
	if (_pDataStream)
	{
		delete _pDataStream;
		_pDataStream = 0;
		std::string response;
		int status = _pControlSocket->receiveStatusMessage(response);
		if (!isPositiveCompletion(status)) 
			throw FTPException("Data transfer failed", response, status);
	}
}


} } // namespace Poco::Net