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 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724
|
/*
* Copyright (C) 2005-2013 Team XBMC
* http://xbmc.org
*
* This Program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with XBMC; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*
*/
#include "threads/SystemClock.h"
#include "SFTPFile.h"
#ifdef HAS_FILESYSTEM_SFTP
#include "threads/SingleLock.h"
#include "utils/log.h"
#include "URL.h"
#include <fcntl.h>
#include <sstream>
#ifdef TARGET_WINDOWS
#pragma comment(lib, "ssh.lib")
#endif
#ifndef S_ISDIR
#define S_ISDIR(m) ((m & _S_IFDIR) != 0)
#endif
#ifndef S_ISREG
#define S_ISREG(m) ((m & _S_IFREG) != 0)
#endif
#ifndef O_RDONLY
#define O_RDONLY _O_RDONLY
#endif
using namespace XFILE;
static std::string CorrectPath(const std::string& path)
{
if (path == "~")
return "./";
else if (path.substr(0, 2) == "~/")
return "./" + path.substr(2);
else
return "/" + path;
}
static const char * SFTPErrorText(int sftp_error)
{
switch(sftp_error)
{
case SSH_FX_OK:
return "No error";
case SSH_FX_EOF:
return "End-of-file encountered";
case SSH_FX_NO_SUCH_FILE:
return "File doesn't exist";
case SSH_FX_PERMISSION_DENIED:
return "Permission denied";
case SSH_FX_BAD_MESSAGE:
return "Garbage received from server";
case SSH_FX_NO_CONNECTION:
return "No connection has been set up";
case SSH_FX_CONNECTION_LOST:
return "There was a connection, but we lost it";
case SSH_FX_OP_UNSUPPORTED:
return "Operation not supported by the server";
case SSH_FX_INVALID_HANDLE:
return "Invalid file handle";
case SSH_FX_NO_SUCH_PATH:
return "No such file or directory path exists";
case SSH_FX_FILE_ALREADY_EXISTS:
return "An attempt to create an already existing file or directory has been made";
case SSH_FX_WRITE_PROTECT:
return "We are trying to write on a write-protected filesystem";
case SSH_FX_NO_MEDIA:
return "No media in remote drive";
case -1:
return "Not a valid error code, probably called on an invalid session";
default:
CLog::Log(LOGERROR, "SFTPErrorText: Unknown error code: %d", sftp_error);
}
return "Unknown error code";
}
CSFTPSession::CSFTPSession(const std::string &host, unsigned int port, const std::string &username, const std::string &password)
{
CLog::Log(LOGINFO, "SFTPSession: Creating new session on host '%s:%d' with user '%s'", host.c_str(), port, username.c_str());
CSingleLock lock(m_critSect);
if (!Connect(host, port, username, password))
Disconnect();
m_LastActive = XbmcThreads::SystemClockMillis();
}
CSFTPSession::~CSFTPSession()
{
CSingleLock lock(m_critSect);
Disconnect();
}
sftp_file CSFTPSession::CreateFileHande(const std::string &file)
{
if (m_connected)
{
CSingleLock lock(m_critSect);
m_LastActive = XbmcThreads::SystemClockMillis();
sftp_file handle = sftp_open(m_sftp_session, CorrectPath(file).c_str(), O_RDONLY, 0);
if (handle)
{
sftp_file_set_blocking(handle);
return handle;
}
else
CLog::Log(LOGERROR, "SFTPSession: Was connected but couldn't create filehandle for '%s'", file.c_str());
}
else
CLog::Log(LOGERROR, "SFTPSession: Not connected and can't create file handle for '%s'", file.c_str());
return NULL;
}
void CSFTPSession::CloseFileHandle(sftp_file handle)
{
CSingleLock lock(m_critSect);
sftp_close(handle);
}
bool CSFTPSession::GetDirectory(const std::string &base, const std::string &folder, CFileItemList &items)
{
int sftp_error = SSH_FX_OK;
if (m_connected)
{
sftp_dir dir = NULL;
{
CSingleLock lock(m_critSect);
m_LastActive = XbmcThreads::SystemClockMillis();
dir = sftp_opendir(m_sftp_session, CorrectPath(folder).c_str());
//Doing as little work as possible within the critical section
if (!dir)
sftp_error = sftp_get_error(m_sftp_session);
}
if (!dir)
{
CLog::Log(LOGERROR, "%s: %s for '%s'", __FUNCTION__, SFTPErrorText(sftp_error), folder.c_str());
}
else
{
bool read = true;
while (read)
{
sftp_attributes attributes = NULL;
{
CSingleLock lock(m_critSect);
read = sftp_dir_eof(dir) == 0;
attributes = sftp_readdir(m_sftp_session, dir);
}
if (attributes && (attributes->name == NULL || strcmp(attributes->name, "..") == 0 || strcmp(attributes->name, ".") == 0))
{
CSingleLock lock(m_critSect);
sftp_attributes_free(attributes);
continue;
}
if (attributes)
{
std::string itemName = attributes->name;
std::string localPath = folder;
localPath.append(itemName);
if (attributes->type == SSH_FILEXFER_TYPE_SYMLINK)
{
CSingleLock lock(m_critSect);
sftp_attributes_free(attributes);
attributes = sftp_stat(m_sftp_session, CorrectPath(localPath).c_str());
if (attributes == NULL)
continue;
}
CFileItemPtr pItem(new CFileItem);
pItem->SetLabel(itemName);
if (itemName[0] == '.')
pItem->SetProperty("file:hidden", true);
if (attributes->flags & SSH_FILEXFER_ATTR_ACMODTIME)
pItem->m_dateTime = attributes->mtime;
if (attributes->type & SSH_FILEXFER_TYPE_DIRECTORY)
{
localPath.append("/");
pItem->m_bIsFolder = true;
pItem->m_dwSize = 0;
}
else
{
pItem->m_dwSize = attributes->size;
}
pItem->SetPath(base + localPath);
items.Add(pItem);
{
CSingleLock lock(m_critSect);
sftp_attributes_free(attributes);
}
}
else
read = false;
}
{
CSingleLock lock(m_critSect);
sftp_closedir(dir);
}
return true;
}
}
else
CLog::Log(LOGERROR, "SFTPSession: Not connected, can't list directory '%s'", folder.c_str());
return false;
}
bool CSFTPSession::DirectoryExists(const char *path)
{
uint32_t permissions = 0;
bool exists = GetItemPermissions(path, permissions);
return exists && S_ISDIR(permissions);
}
bool CSFTPSession::FileExists(const char *path)
{
uint32_t permissions = 0;
bool exists = GetItemPermissions(path, permissions);
return exists && S_ISREG(permissions);
}
int CSFTPSession::Stat(const char *path, struct __stat64* buffer)
{
CSingleLock lock(m_critSect);
if(m_connected)
{
m_LastActive = XbmcThreads::SystemClockMillis();
sftp_attributes attributes = sftp_stat(m_sftp_session, CorrectPath(path).c_str());
if (attributes)
{
memset(buffer, 0, sizeof(struct __stat64));
buffer->st_size = attributes->size;
buffer->st_mtime = attributes->mtime;
buffer->st_atime = attributes->atime;
if S_ISDIR(attributes->permissions)
buffer->st_mode = _S_IFDIR;
else if S_ISREG(attributes->permissions)
buffer->st_mode = _S_IFREG;
sftp_attributes_free(attributes);
return 0;
}
else
{
CLog::Log(LOGERROR, "SFTPSession::Stat - Failed to get attributes for '%s'", path);
return -1;
}
}
else
{
CLog::Log(LOGERROR, "SFTPSession::Stat - Failed because not connected for '%s'", path);
return -1;
}
}
int CSFTPSession::Seek(sftp_file handle, uint64_t position)
{
CSingleLock lock(m_critSect);
m_LastActive = XbmcThreads::SystemClockMillis();
return sftp_seek64(handle, position);
}
int CSFTPSession::Read(sftp_file handle, void *buffer, size_t length)
{
CSingleLock lock(m_critSect);
m_LastActive = XbmcThreads::SystemClockMillis();
return sftp_read(handle, buffer, length);
}
int64_t CSFTPSession::GetPosition(sftp_file handle)
{
CSingleLock lock(m_critSect);
m_LastActive = XbmcThreads::SystemClockMillis();
return sftp_tell64(handle);
}
bool CSFTPSession::IsIdle()
{
return (XbmcThreads::SystemClockMillis() - m_LastActive) > 90000;
}
bool CSFTPSession::VerifyKnownHost(ssh_session session)
{
switch (ssh_is_server_known(session))
{
case SSH_SERVER_KNOWN_OK:
return true;
case SSH_SERVER_KNOWN_CHANGED:
CLog::Log(LOGERROR, "SFTPSession: Server that was known has changed");
return false;
case SSH_SERVER_FOUND_OTHER:
CLog::Log(LOGERROR, "SFTPSession: The host key for this server was not found but an other type of key exists. An attacker might change the default server key to confuse your client into thinking the key does not exist");
return false;
case SSH_SERVER_FILE_NOT_FOUND:
CLog::Log(LOGINFO, "SFTPSession: Server file was not found, creating a new one");
case SSH_SERVER_NOT_KNOWN:
CLog::Log(LOGINFO, "SFTPSession: Server unkown, we trust it for now");
if (ssh_write_knownhost(session) < 0)
{
CLog::Log(LOGERROR, "CSFTPSession: Failed to save host '%s'", strerror(errno));
return false;
}
return true;
case SSH_SERVER_ERROR:
CLog::Log(LOGERROR, "SFTPSession: Failed to verify host '%s'", ssh_get_error(session));
return false;
}
return false;
}
bool CSFTPSession::Connect(const std::string &host, unsigned int port, const std::string &username, const std::string &password)
{
int timeout = SFTP_TIMEOUT;
m_connected = false;
m_session = NULL;
m_sftp_session = NULL;
m_session=ssh_new();
if (m_session == NULL)
{
CLog::Log(LOGERROR, "SFTPSession: Failed to initialize session for host '%s'", host.c_str());
return false;
}
#if LIBSSH_VERSION_INT >= SSH_VERSION_INT(0,4,0)
if (ssh_options_set(m_session, SSH_OPTIONS_USER, username.c_str()) < 0)
{
CLog::Log(LOGERROR, "SFTPSession: Failed to set username '%s' for session", username.c_str());
return false;
}
if (ssh_options_set(m_session, SSH_OPTIONS_HOST, host.c_str()) < 0)
{
CLog::Log(LOGERROR, "SFTPSession: Failed to set host '%s' for session", host.c_str());
return false;
}
if (ssh_options_set(m_session, SSH_OPTIONS_PORT, &port) < 0)
{
CLog::Log(LOGERROR, "SFTPSession: Failed to set port '%d' for session", port);
return false;
}
ssh_options_set(m_session, SSH_OPTIONS_LOG_VERBOSITY, 0);
ssh_options_set(m_session, SSH_OPTIONS_TIMEOUT, &timeout);
#else
SSH_OPTIONS* options = ssh_options_new();
if (ssh_options_set_username(options, username.c_str()) < 0)
{
CLog::Log(LOGERROR, "SFTPSession: Failed to set username '%s' for session", username.c_str());
return false;
}
if (ssh_options_set_host(options, host.c_str()) < 0)
{
CLog::Log(LOGERROR, "SFTPSession: Failed to set host '%s' for session", host.c_str());
return false;
}
if (ssh_options_set_port(options, port) < 0)
{
CLog::Log(LOGERROR, "SFTPSession: Failed to set port '%d' for session", port);
return false;
}
ssh_options_set_timeout(options, timeout, 0);
ssh_options_set_log_verbosity(options, 0);
ssh_set_options(m_session, options);
#endif
if(ssh_connect(m_session))
{
CLog::Log(LOGERROR, "SFTPSession: Failed to connect '%s'", ssh_get_error(m_session));
return false;
}
if (!VerifyKnownHost(m_session))
{
CLog::Log(LOGERROR, "SFTPSession: Host is not known '%s'", ssh_get_error(m_session));
return false;
}
int noAuth = SSH_AUTH_DENIED;
if ((noAuth = ssh_userauth_none(m_session, NULL)) == SSH_AUTH_ERROR)
{
CLog::Log(LOGERROR, "SFTPSession: Failed to authenticate via guest '%s'", ssh_get_error(m_session));
return false;
}
#if LIBSSH_VERSION_MINOR >= 6
int method = ssh_userauth_list(m_session, NULL);
#else
int method = ssh_auth_list(m_session);
#endif
// Try to authenticate with public key first
int publicKeyAuth = SSH_AUTH_DENIED;
#if LIBSSH_VERSION_MINOR >= 6
if (method & SSH_AUTH_METHOD_PUBLICKEY && (publicKeyAuth = ssh_userauth_publickey_auto(m_session, NULL, NULL)) == SSH_AUTH_ERROR)
#else
if (method & SSH_AUTH_METHOD_PUBLICKEY && (publicKeyAuth = ssh_userauth_autopubkey(m_session, NULL)) == SSH_AUTH_ERROR)
#endif
{
CLog::Log(LOGERROR, "SFTPSession: Failed to authenticate via publickey '%s'", ssh_get_error(m_session));
return false;
}
// Try to authenticate with password
int passwordAuth = SSH_AUTH_DENIED;
if (method & SSH_AUTH_METHOD_PASSWORD)
{
if (publicKeyAuth != SSH_AUTH_SUCCESS &&
(passwordAuth = ssh_userauth_password(m_session, username.c_str(), password.c_str())) == SSH_AUTH_ERROR)
{
CLog::Log(LOGERROR, "SFTPSession: Failed to authenticate via password '%s'", ssh_get_error(m_session));
return false;
}
}
else if (!password.empty())
{
CLog::Log(LOGERROR, "SFTPSession: Password present, but server does not support password authentication");
}
if (noAuth == SSH_AUTH_SUCCESS || publicKeyAuth == SSH_AUTH_SUCCESS || passwordAuth == SSH_AUTH_SUCCESS)
{
m_sftp_session = sftp_new(m_session);
if (m_sftp_session == NULL)
{
CLog::Log(LOGERROR, "SFTPSession: Failed to initialize channel '%s'", ssh_get_error(m_session));
return false;
}
if (sftp_init(m_sftp_session))
{
CLog::Log(LOGERROR, "SFTPSession: Failed to initialize sftp '%s'", ssh_get_error(m_session));
return false;
}
m_connected = true;
}
else
{
CLog::Log(LOGERROR, "SFTPSession: No authentication method successful");
}
return m_connected;
}
void CSFTPSession::Disconnect()
{
if (m_sftp_session)
sftp_free(m_sftp_session);
if (m_session)
ssh_disconnect(m_session);
m_sftp_session = NULL;
m_session = NULL;
}
/*!
\brief Gets POSIX compatible permissions information about the specified file or directory.
\param path Remote SSH path to the file or directory.
\param permissions POSIX compatible permissions information for the file or directory (if it exists). i.e. can use macros S_ISDIR() etc.
\return Returns \e true, if it was possible to get permissions for the file or directory, \e false otherwise.
*/
bool CSFTPSession::GetItemPermissions(const char *path, uint32_t &permissions)
{
bool gotPermissions = false;
CSingleLock lock(m_critSect);
if(m_connected)
{
sftp_attributes attributes = sftp_stat(m_sftp_session, CorrectPath(path).c_str());
if (attributes)
{
if (attributes->flags & SSH_FILEXFER_ATTR_PERMISSIONS)
{
permissions = attributes->permissions;
gotPermissions = true;
}
sftp_attributes_free(attributes);
}
}
return gotPermissions;
}
CCriticalSection CSFTPSessionManager::m_critSect;
std::map<std::string, CSFTPSessionPtr> CSFTPSessionManager::sessions;
CSFTPSessionPtr CSFTPSessionManager::CreateSession(const CURL &url)
{
std::string username = url.GetUserName().c_str();
std::string password = url.GetPassWord().c_str();
std::string hostname = url.GetHostName().c_str();
unsigned int port = url.HasPort() ? url.GetPort() : 22;
return CSFTPSessionManager::CreateSession(hostname, port, username, password);
}
CSFTPSessionPtr CSFTPSessionManager::CreateSession(const std::string &host, unsigned int port, const std::string &username, const std::string &password)
{
// Convert port number to string
std::stringstream itoa;
itoa << port;
std::string portstr = itoa.str();
CSingleLock lock(m_critSect);
std::string key = username + ':' + password + '@' + host + ':' + portstr;
CSFTPSessionPtr ptr = sessions[key];
if (ptr == NULL)
{
ptr = CSFTPSessionPtr(new CSFTPSession(host, port, username, password));
sessions[key] = ptr;
}
return ptr;
}
void CSFTPSessionManager::ClearOutIdleSessions()
{
CSingleLock lock(m_critSect);
for(std::map<std::string, CSFTPSessionPtr>::iterator iter = sessions.begin(); iter != sessions.end();)
{
if (iter->second->IsIdle())
sessions.erase(iter++);
else
++iter;
}
}
void CSFTPSessionManager::DisconnectAllSessions()
{
CSingleLock lock(m_critSect);
sessions.clear();
}
CSFTPFile::CSFTPFile()
{
m_sftp_handle = NULL;
}
CSFTPFile::~CSFTPFile()
{
Close();
}
bool CSFTPFile::Open(const CURL& url)
{
m_session = CSFTPSessionManager::CreateSession(url);
if (m_session)
{
m_file = url.GetFileName().c_str();
m_sftp_handle = m_session->CreateFileHande(m_file);
return (m_sftp_handle != NULL);
}
else
{
CLog::Log(LOGERROR, "SFTPFile: Failed to allocate session");
return false;
}
}
void CSFTPFile::Close()
{
if (m_session && m_sftp_handle)
{
m_session->CloseFileHandle(m_sftp_handle);
m_sftp_handle = NULL;
m_session = CSFTPSessionPtr();
}
}
int64_t CSFTPFile::Seek(int64_t iFilePosition, int iWhence)
{
if (m_session && m_sftp_handle)
{
uint64_t position = 0;
if (iWhence == SEEK_SET)
position = iFilePosition;
else if (iWhence == SEEK_CUR)
position = GetPosition() + iFilePosition;
else if (iWhence == SEEK_END)
position = GetLength() + iFilePosition;
if (m_session->Seek(m_sftp_handle, position) == 0)
return GetPosition();
else
return -1;
}
else
{
CLog::Log(LOGERROR, "SFTPFile: Can't seek without a filehandle");
return -1;
}
}
ssize_t CSFTPFile::Read(void* lpBuf, size_t uiBufSize)
{
if (m_session && m_sftp_handle)
{
if (uiBufSize > SSIZE_MAX)
uiBufSize = SSIZE_MAX;
int rc = m_session->Read(m_sftp_handle, lpBuf, (size_t)uiBufSize);
if (rc >= 0)
return rc;
else
CLog::Log(LOGERROR, "SFTPFile: Failed to read %i", rc);
}
else
CLog::Log(LOGERROR, "SFTPFile: Can't read without a filehandle");
return 0;
}
bool CSFTPFile::Exists(const CURL& url)
{
CSFTPSessionPtr session = CSFTPSessionManager::CreateSession(url);
if (session)
return session->FileExists(url.GetFileName().c_str());
else
{
CLog::Log(LOGERROR, "SFTPFile: Failed to create session to check exists for '%s'", url.GetFileName().c_str());
return false;
}
}
int CSFTPFile::Stat(const CURL& url, struct __stat64* buffer)
{
CSFTPSessionPtr session = CSFTPSessionManager::CreateSession(url);
if (session)
return session->Stat(url.GetFileName().c_str(), buffer);
else
{
CLog::Log(LOGERROR, "SFTPFile: Failed to create session to stat for '%s'", url.GetFileName().c_str());
return -1;
}
}
int CSFTPFile::Stat(struct __stat64* buffer)
{
if (m_session)
return m_session->Stat(m_file.c_str(), buffer);
CLog::Log(LOGERROR, "SFTPFile: Can't stat without a session for '%s'", m_file.c_str());
return -1;
}
int64_t CSFTPFile::GetLength()
{
struct __stat64 buffer;
if (Stat(&buffer) != 0)
return 0;
else
{
int64_t length = buffer.st_size;
return length;
}
}
int64_t CSFTPFile::GetPosition()
{
if (m_session && m_sftp_handle)
return m_session->GetPosition(m_sftp_handle);
CLog::Log(LOGERROR, "SFTPFile: Can't get position without a filehandle for '%s'", m_file.c_str());
return 0;
}
int CSFTPFile::IoControl(EIoControl request, void* param)
{
if(request == IOCTRL_SEEK_POSSIBLE)
return 1;
return -1;
}
#endif
|