Debian Codegraph @

CodeLite/cl_sftp.cpp

raw
1 //////////////////////////////////////////////////////////////////////////////
2 //////////////////////////////////////////////////////////////////////////////
3 //
4 // copyright : (C) 2014 Eran Ifrah
5 // file name : cl_sftp.cpp
6 //
7 // -------------------------------------------------------------------------
8 // A
9 // _____ _ _ _ _
10 // / __ \ | | | | (_) |
11 // | / \/ ___ __| | ___| | _| |_ ___
12 // | | / _ \ / _ |/ _ \ | | | __/ _ )
13 // | \__/\ (_) | (_| | __/ |___| | || __/
14 // \____/\___/ \__,_|\___\_____/_|\__\___|
15 //
16 // F i l e
17 //
18 // This program is free software; you can redistribute it and/or modify
19 // it under the terms of the GNU General Public License as published by
20 // the Free Software Foundation; either version 2 of the License, or
21 // (at your option) any later version.
22 //
23 //////////////////////////////////////////////////////////////////////////////
24 //////////////////////////////////////////////////////////////////////////////
25
26 #if USE_SFTP
27 #include "cl_sftp.h"
28
29 #include "cl_standard_paths.h"
30 #include "file_logger.h"
31 #include "wx/tokenzr.h"
32
33 #include <atomic>
34 #include <libssh/sftp.h>
35 #include <string.h>
36 #include <sys/stat.h>
37 #include <wx/ffile.h>
38 #include <wx/filefn.h>
39
40 class SFTPDirCloser
41 {
42 sftp_dir m_dir;
43
44 public:
45 SFTPDirCloser(sftp_dir d)
46 : m_dir(d)
47 {
48 }
49 ~SFTPDirCloser() { sftp_closedir(m_dir); }
50 };
51
52 clSFTP::clSFTP(clSSH::Ptr_t ssh)
53 : m_ssh(ssh)
54 , m_sftp(NULL)
55 , m_connected(false)
56 {
57 }
58
59 clSFTP::~clSFTP() { Close(); }
60
61 /**
62 * @brief update 'attr' to include details about the symlink
63 */
64 static void clSFTPReadLink(SFTPAttribute::Ptr_t attr, SFTPSession_t sftp, const wxString& curdir)
65 {
66 if(!attr->IsSymlink()) {
67 return;
68 }
69 // build the symlink full path and read the target path
70 wxString symlinkPath = curdir + "/" + attr->GetName();
71 const char* target_path = sftp_readlink(sftp, symlinkPath.mb_str(wxConvUTF8).data());
72 if(target_path) {
73 wxString targetPath = target_path;
74 if(!targetPath.StartsWith("/")) {
75 // relative path
76 targetPath.Prepend(curdir + "/");
77 targetPath.Replace("//", "/");
78 }
79 attr->SetSymlinkPath(targetPath);
80 sftp_attributes linkattr = sftp_stat(sftp, targetPath.mb_str(wxConvUTF8).data());
81 if(linkattr) {
82 SFTPAttribute::Ptr_t targetAttr(new SFTPAttribute(linkattr));
83 if(targetAttr->IsFile()) {
84 attr->SetFile();
85 }
86 if(targetAttr->IsFolder()) {
87 attr->SetFolder();
88 }
89 }
90 }
91 }
92
93 void clSFTP::Initialize()
94 {
95 if(m_sftp)
96 return;
97
98 m_sftp = sftp_new(m_ssh->GetSession());
99 if(m_sftp == NULL) {
100 throw clException(wxString() << "Error allocating SFTP session: " << ssh_get_error(m_ssh->GetSession()));
101 }
102
103 int rc = sftp_init(m_sftp);
104 if(rc != SSH_OK) {
105 throw clException(wxString() << "Error initializing SFTP session: " << ssh_get_error(m_ssh->GetSession()),
106 sftp_get_error(m_sftp));
107 }
108 m_connected = true;
109 }
110
111 void clSFTP::Close()
112 {
113 if(m_sftp) {
114 sftp_free(m_sftp);
115 }
116
117 m_connected = false;
118 m_sftp = NULL;
119 }
120
121 void clSFTP::Write(const wxFileName& localFile, const wxString& remotePath)
122 {
123 if(!m_connected) {
124 throw clException("scp is not initialized!");
125 }
126
127 if(!localFile.Exists()) {
128 throw clException(wxString() << "scp::Write file '" << localFile.GetFullPath() << "' does not exist!");
129 }
130
131 wxFFile fp(localFile.GetFullPath(), "rb");
132 if(!fp.IsOpened()) {
133 throw clException(wxString() << "scp::Write could not open file '" << localFile.GetFullPath() << "'. "
134 << ::strerror(errno));
135 }
136
137 wxMemoryBuffer memBuffer;
138 size_t len = fp.Length();
139 void* buffer = memBuffer.GetWriteBuf(len);
140 size_t nbytes(0);
141 nbytes = fp.Read(buffer, fp.Length());
142 if(nbytes != (size_t)fp.Length()) {
143 throw clException(wxString() << "failed to read local file content. expected read size: " << len
144 << ". bytes read: " << nbytes);
145 }
146 fp.Close();
147 memBuffer.SetDataLen(len);
148 Write(memBuffer, remotePath);
149 }
150
151 void clSFTP::Write(const wxMemoryBuffer& fileContent, const wxString& remotePath)
152 {
153 if(!m_sftp) {
154 throw clException("SFTP is not initialized");
155 }
156
157 static size_t counter = 0;
158 int access_type = O_WRONLY | O_CREAT | O_TRUNC;
159 sftp_file file;
160 wxString tmpRemoteFile = remotePath;
161 tmpRemoteFile << ".codelitesftp" << (++counter);
162
163 auto cb = tmpRemoteFile.mb_str(wxConvUTF8);
164 file = sftp_open(m_sftp, cb.data(), access_type, 0644);
165 if(file == NULL) {
166 throw clException(wxString() << _("Can't open file: ") << tmpRemoteFile << ". "
167 << ssh_get_error(m_ssh->GetSession()),
168 sftp_get_error(m_sftp));
169 }
170
171 char* p = (char*)fileContent.GetData();
172 const int maxChunkSize = 65536;
173 wxInt64 bytesLeft = fileContent.GetDataLen();
174
175 while(bytesLeft > 0) {
176 wxInt64 chunkSize = bytesLeft > maxChunkSize ? maxChunkSize : bytesLeft;
177 wxInt64 bytesWritten = sftp_write(file, p, chunkSize);
178 if(bytesWritten < 0) {
179 sftp_close(file);
180 throw clException(wxString() << _("Can't write data to file: ") << tmpRemoteFile << ". "
181 << ssh_get_error(m_ssh->GetSession()),
182 sftp_get_error(m_sftp));
183 }
184 bytesLeft -= bytesWritten;
185 p += bytesWritten;
186 }
187 sftp_close(file);
188
189 // Unlink the original file if it exists
190 auto char_buffer_remote = remotePath.mb_str(wxConvUTF8);
191 SFTPAttribute::Ptr_t pattr(new SFTPAttribute(sftp_stat(m_sftp, char_buffer_remote.data())));
192
193 if(pattr->IsOk() && sftp_unlink(m_sftp, char_buffer_remote.data()) < 0) {
194 throw clException(wxString() << _("Failed to unlink file: ") << remotePath << ". "
195 << ssh_get_error(m_ssh->GetSession()),
196 sftp_get_error(m_sftp));
197 }
198
199 // Rename the file
200 if(sftp_rename(m_sftp, cb.data(), char_buffer_remote.data()) < 0) {
201 throw clException(wxString() << _("Failed to rename file: ") << tmpRemoteFile << " -> " << remotePath << ". "
202 << ssh_get_error(m_ssh->GetSession()),
203 sftp_get_error(m_sftp));
204 }
205
206 if(pattr->IsOk()) {
207 Chmod(remotePath, pattr->GetPermissions());
208 }
209 }
210
211 SFTPAttribute::List_t clSFTP::List(const wxString& folder, size_t flags, const wxString& filter)
212 {
213 sftp_dir dir;
214 sftp_attributes attributes;
215
216 if(!m_sftp) {
217 throw clException("SFTP is not initialized");
218 }
219
220 dir = sftp_opendir(m_sftp, folder.mb_str(wxConvUTF8).data());
221 if(!dir) {
222 throw clException(wxString() << _("Failed to list directory: ") << folder << ". "
223 << ssh_get_error(m_ssh->GetSession()),
224 sftp_get_error(m_sftp));
225 }
226
227 // Keep the current folder name
228 m_currentFolder = dir->name;
229
230 // Ensure the directory is closed
231 SFTPDirCloser dc(dir);
232 SFTPAttribute::List_t files;
233
234 attributes = sftp_readdir(m_sftp, dir);
235 while(attributes) {
236 SFTPAttribute::Ptr_t attr(new SFTPAttribute(attributes));
237 if(attr->IsSymlink()) {
238 clSFTPReadLink(attr, m_sftp, m_currentFolder);
239 }
240 attributes = sftp_readdir(m_sftp, dir);
241
242 // Don't show files ?
243 if(!(flags & SFTP_BROWSE_FILES) && !attr->IsFolder()) {
244 continue;
245
246 } else if((flags & SFTP_BROWSE_FILES) && !attr->IsFolder() // show files
247 && filter.IsEmpty()) { // no filter is given
248 files.push_back(attr);
249
250 } else if((flags & SFTP_BROWSE_FILES) && !attr->IsFolder() // show files
251 && !::wxMatchWild(filter, attr->GetName())) { // but the file does not match the filter
252 continue;
253
254 } else {
255 files.push_back(attr);
256 }
257 }
258 files.sort(SFTPAttribute::Compare);
259 return files;
260 }
261
262 SFTPAttribute::List_t clSFTP::CdUp(size_t flags, const wxString& filter)
263 {
264 wxString curfolder = m_currentFolder;
265 curfolder << "/../"; // Force a cd up
266
267 wxFileName fn(curfolder, "", wxPATH_UNIX);
268 fn.Normalize();
269 return List(fn.GetPath(false, wxPATH_UNIX), flags, filter);
270 }
271
272 SFTPAttribute::Ptr_t clSFTP::Read(const wxString& remotePath, wxMemoryBuffer& buffer)
273 {
274 if(!m_sftp) {
275 throw clException("SFTP is not initialized");
276 }
277
278 sftp_file file = sftp_open(m_sftp, remotePath.mb_str(wxConvUTF8).data(), O_RDONLY, 0);
279 if(file == NULL) {
280 throw clException(wxString() << _("Failed to open remote file: ") << remotePath << ". "
281 << ssh_get_error(m_ssh->GetSession()),
282 sftp_get_error(m_sftp));
283 }
284
285 SFTPAttribute::Ptr_t fileAttr = Stat(remotePath);
286 if(!fileAttr) {
287 throw clException(wxString() << _("Could not stat file:") << remotePath << ". "
288 << ssh_get_error(m_ssh->GetSession()),
289 sftp_get_error(m_sftp));
290 }
291 wxInt64 fileSize = fileAttr->GetSize();
292 if(fileSize == 0)
293 return fileAttr;
294
295 // Allocate buffer for the file content
296 char pBuffer[65536]; // buffer
297
298 // Read the entire file content
299 wxInt64 bytesLeft = fileSize;
300 wxInt64 bytesRead = 0;
301 while(bytesLeft > 0) {
302 wxInt64 nbytes = sftp_read(file, pBuffer, sizeof(pBuffer));
303 if(nbytes <= 0) {
304 break; // we will throw later
305 }
306 bytesRead += nbytes;
307 bytesLeft -= nbytes;
308 buffer.AppendData(pBuffer, nbytes);
309 }
310
311 if(bytesRead != fileSize) {
312 sftp_close(file);
313 buffer.Clear();
314 throw clException(wxString() << _("Could not read file:") << remotePath << ". "
315 << ssh_get_error(m_ssh->GetSession()),
316 sftp_get_error(m_sftp));
317 }
318 sftp_close(file);
319 return fileAttr;
320 }
321
322 void clSFTP::CreateDir(const wxString& dirname)
323 {
324 if(!m_sftp) {
325 throw clException("SFTP is not initialized");
326 }
327
328 int rc;
329 auto attr = sftp_stat(m_sftp, dirname.mb_str(wxConvUTF8).data());
330 if(attr) {
331 // already exists
332 sftp_attributes_free(attr);
333 clDEBUG() << "remote folder:" << dirname << "already exists. nothing to be done here" << endl;
334 // nothing to be done here
335 return;
336 }
337
338 rc = sftp_mkdir(m_sftp, dirname.mb_str(wxConvUTF8).data(), S_IRWXU);
339
340 if(rc != SSH_OK) {
341 wxString message;
342 message << _("SFTP: failed to create directory: ") << dirname << ". " << ssh_get_error(m_ssh->GetSession());
343 clERROR() << message << endl;
344 throw clException(message);
345 }
346 }
347
348 void clSFTP::Rename(const wxString& oldpath, const wxString& newpath)
349 {
350 if(!m_sftp) {
351 throw clException("SFTP is not initialized");
352 }
353
354 int rc;
355 rc = sftp_rename(m_sftp, oldpath.mb_str(wxConvUTF8).data(), newpath.mb_str(wxConvUTF8).data());
356
357 if(rc != SSH_OK) {
358 throw clException(wxString() << _("Failed to rename path. ") << ssh_get_error(m_ssh->GetSession()),
359 sftp_get_error(m_sftp));
360 }
361 }
362
363 void clSFTP::RemoveDir(const wxString& dirname)
364 {
365 if(!m_sftp) {
366 throw clException("SFTP is not initialized");
367 }
368
369 int rc;
370 rc = sftp_rmdir(m_sftp, dirname.mb_str(wxConvUTF8).data());
371
372 if(rc != SSH_OK) {
373 throw clException(wxString() << _("Failed to remove directory: ") << dirname << "\n" << GetErrorString());
374 }
375 }
376
377 void clSFTP::UnlinkFile(const wxString& path)
378 {
379 if(!m_sftp) {
380 throw clException("SFTP is not initialized");
381 }
382
383 int rc;
384 rc = sftp_unlink(m_sftp, path.mb_str(wxConvUTF8).data());
385
386 if(rc != SSH_OK) {
387 throw clException(wxString() << _("Failed to unlink path: ") << path << ". "
388 << ssh_get_error(m_ssh->GetSession()),
389 sftp_get_error(m_sftp));
390 }
391 }
392
393 SFTPAttribute::Ptr_t clSFTP::Stat(const wxString& path)
394 {
395 if(!m_sftp) {
396 throw clException("SFTP is not initialized");
397 }
398
399 sftp_attributes attr = sftp_stat(m_sftp, path.mb_str(wxConvUTF8).data());
400 if(!attr) {
401 throw clException(wxString() << _("Could not stat: ") << path << ". " << ssh_get_error(m_ssh->GetSession()),
402 sftp_get_error(m_sftp));
403 }
404 wxString target;
405 if(attr->type == SSH_FILEXFER_TYPE_SYMLINK) {
406 // this is a symlink file, read the symlink info
407 const char* ctarget = sftp_readlink(m_sftp, path.mb_str(wxConvUTF8).data());
408 if(!ctarget) {
409 throw clException(wxString() << _("Failed to read symlink target. ") << ssh_get_error(m_ssh->GetSession()));
410 }
411 target = ctarget;
412 }
413 SFTPAttribute::Ptr_t pattr(new SFTPAttribute(attr));
414 if(attr->type == SSH_FILEXFER_TYPE_SYMLINK) {
415 pattr->SetSymlinkPath(target);
416 }
417 return pattr;
418 }
419
420 void clSFTP::CreateRemoteFile(const wxString& remoteFullPath, const wxString& content)
421 {
422 // Create the path to the file
423 Mkpath(wxFileName(remoteFullPath).GetPath());
424 Write(content, remoteFullPath);
425 }
426
427 void clSFTP::CreateEmptyFile(const wxString& remotePath)
428 {
429 Mkpath(wxFileName(remotePath).GetPath());
430 wxMemoryBuffer mb;
431 Write(mb, remotePath);
432 }
433
434 void clSFTP::Mkpath(const wxString& remoteDirFullpath)
435 {
436 if(!m_sftp) {
437 throw clException("SFTP is not initialized");
438 }
439
440 wxString tmpPath = remoteDirFullpath;
441 tmpPath.Replace("\\", "/");
442 if(!tmpPath.StartsWith("/")) {
443 throw clException("Mkpath: path must be absolute");
444 }
445
446 wxFileName fn(remoteDirFullpath, "");
447 const wxArrayString& dirs = fn.GetDirs();
448 wxString curdir;
449
450 curdir << "/";
451 for(size_t i = 0; i < dirs.GetCount(); ++i) {
452 curdir << dirs.Item(i);
453 sftp_attributes attr = sftp_stat(m_sftp, curdir.mb_str(wxConvUTF8).data());
454 if(!attr) {
455 // directory does not exists
456 CreateDir(curdir);
457
458 } else {
459 // directory already exists
460 sftp_attributes_free(attr);
461 }
462 curdir << "/";
463 }
464 }
465
466 void clSFTP::CreateRemoteFile(const wxString& remoteFullPath, const wxFileName& localFile)
467 {
468 Mkpath(wxFileName(remoteFullPath).GetPath());
469 Write(localFile, remoteFullPath);
470 }
471
472 void clSFTP::Chmod(const wxString& remotePath, size_t permissions)
473 {
474 if(!m_sftp) {
475 throw clException("SFTP is not initialized");
476 }
477
478 if(permissions == 0)
479 return;
480
481 int rc = sftp_chmod(m_sftp, remotePath.mb_str(wxConvUTF8).data(), permissions);
482 if(rc != SSH_OK) {
483 throw clException(wxString() << _("Failed to chmod file: ") << remotePath << ". "
484 << ssh_get_error(m_ssh->GetSession()),
485 sftp_get_error(m_sftp));
486 }
487 }
488
489 wxString clSFTP::GetDefaultDownloadFolder(const SSHAccountInfo& accountInfo)
490 {
491 wxFileName path(clStandardPaths::Get().GetUserDataDir(), "");
492 path.AppendDir("sftp");
493 path.AppendDir("download");
494 if(!accountInfo.GetHost().empty()) {
495 path.AppendDir(accountInfo.GetHost());
496 }
497 return path.GetPath();
498 }
499
500 wxFileName clSFTP::GetLocalFileName(const SSHAccountInfo& accountInfo, const wxString& remotePath, bool mkdirRecrusive)
501 {
502 // Generate a temporary file location
503 wxFileName fnRemoteFile(remotePath);
504 wxFileName localFile(GetDefaultDownloadFolder(accountInfo), fnRemoteFile.GetFullName());
505 const wxArrayString& dirs = fnRemoteFile.GetDirs();
506 for(size_t i = 0; i < dirs.GetCount(); ++i) {
507 localFile.AppendDir(dirs.Item(i));
508 }
509
510 if(mkdirRecrusive) {
511 // Ensure that the path to the sftp temp folder exists
512 localFile.Mkdir(wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL);
513 }
514 return localFile.GetFullPath();
515 }
516
517 wxString clSFTP::GetErrorString() const
518 {
519 if(!m_sftp) {
520 return wxEmptyString;
521 }
522
523 int errorCode = sftp_get_error(m_sftp);
524 switch(errorCode) {
525 case SSH_FX_OK:
526 return "no error";
527 case SSH_FX_EOF:
528 return "end-of-file encountered";
529 case SSH_FX_NO_SUCH_FILE:
530 return "file does not exist";
531 case SSH_FX_PERMISSION_DENIED:
532 return "permission denied";
533 case SSH_FX_FAILURE:
534 return "generic failure";
535 case SSH_FX_BAD_MESSAGE:
536 return "garbage received from server";
537 case SSH_FX_NO_CONNECTION:
538 return "no connection has been set up";
539 case SSH_FX_CONNECTION_LOST:
540 return "there was a connection, but we lost it";
541 case SSH_FX_OP_UNSUPPORTED:
542 return "operation not supported by libssh yet";
543 case SSH_FX_INVALID_HANDLE:
544 return "invalid file handle";
545 case SSH_FX_NO_SUCH_PATH:
546 return "no such file or directory path exists";
547 case SSH_FX_FILE_ALREADY_EXISTS:
548 return "an attempt to create an already existing file or directory has been made";
549 case SSH_FX_WRITE_PROTECT:
550 return "write-protected filesystem";
551 case SSH_FX_NO_MEDIA:
552 return "no media was in remote drive";
553 default:
554 return wxEmptyString;
555 }
556 }
557
558 void clSFTP::SendKeepAlive()
559 {
560 if(!m_sftp || !m_ssh) {
561 return;
562 }
563 m_ssh->SendIgnore();
564 }
565
566 SFTPAttribute::List_t clSFTP::Chdir(const wxString& remotePath)
567 {
568 if(!m_sftp) {
569 throw clException("SFTP is not initialized");
570 }
571
572 // Check that the directory exists
573 auto attr = Stat(remotePath);
574 if(!attr->IsFolder()) {
575 throw clException("Chdir failed. " + remotePath + " is not a directory");
576 }
577 return List(remotePath, SFTP_BROWSE_FILES | SFTP_BROWSE_FOLDERS);
578 }
579
580 wxString clSFTP::ExecuteCommand(const wxString& command)
581 {
582 if(!m_sftp) {
583 throw clException("SFTP is not initialized");
584 }
585
586 ssh_channel channel = ssh_channel_new(m_ssh->GetSession());
587 if(!channel) {
588 throw clException("Failed to allocate ssh channel");
589 }
590
591 int rc = ssh_channel_open_session(channel);
592 if(rc != SSH_OK) {
593 ssh_channel_free(channel);
594 throw clException("Failed to open ssh channel");
595 }
596 rc = ssh_channel_request_exec(channel, command.mb_str(wxConvUTF8).data());
597 if(rc != SSH_OK) {
598 ssh_channel_close(channel);
599 ssh_channel_free(channel);
600 throw clException(wxString() << "Failed to execute command: " << command);
601 }
602
603 // read the result
604 char buffer[256];
605 int nbytes;
606
607 wxString result;
608 nbytes = ssh_channel_read(channel, buffer, sizeof(buffer) - 1, 0);
609 while(nbytes > 0) {
610 buffer[nbytes] = 0;
611 result << buffer;
612 nbytes = ssh_channel_read(channel, buffer, sizeof(buffer), 0);
613 }
614
615 if(nbytes < 0) {
616 ssh_channel_close(channel);
617 ssh_channel_free(channel);
618 throw clException(wxString() << "Failed to read from channel. Command: " << command);
619 }
620
621 ssh_channel_send_eof(channel);
622 ssh_channel_close(channel);
623 ssh_channel_free(channel);
624 return result;
625 }
626
627 bool clSFTP::GetChecksum(const wxString& remoteFile, size_t* checksum)
628 {
629 wxString command;
630 command << "cksum " << remoteFile;
631 try {
632 wxString output = ExecuteCommand(command);
633 auto parts = ::wxStringTokenize(output, " \t", wxTOKEN_STRTOK);
634 if(parts.empty()) {
635 return false;
636 }
637 // the checksum is the first part
638 unsigned long ck;
639 if(!parts[0].ToCULong(&ck)) {
640 return false;
641 }
642 *checksum = ck;
643 return true;
644 } catch(clException& e) {
645 clWARNING() << e.What() << endl;
646 return false;
647 }
648 }
649
650 #endif // USE_SFTP