Example #1
0
/**
 * @function ssh.writeFile
 * 
 * ### Synopsis
 * 
 * var status = ssh.writeFile(handle, srcPath, dstPath);
 * var status = ssh.writeFile(handle, srcPath, dstPath, mode);
 * 
 * Write file to remote server via SCP.
 * 
 * @param {object} handle - opaque handle to already open SSH2 connection.
 * @param {string} srcPath - path to file in local file system to send.
 * @param {string} dstPath - path to file in remote file system to create.
 * @param {int} mode - desired resulting file permissions of file on remote end.
 * @return {boolean} success - true if the transfer succeeded, string error message if transfer failed.
 * 
 * ### Note
 * If mode is not provided, the file mode of the file being sent will be used.
 */
static JSVAL ssh2_scp_send(JSARGS args) {
	HandleScope scope;
    SSH2 *ssh2 = HANDLE(args[0]);
	String::Utf8Value srcPath(args[1]);
	String::Utf8Value dstPath(args[2]);
    int mode;
    struct stat fileinfo;
    if (stat(*srcPath, &fileinfo) != 0) {
        return scope.Close(String::New(strerror(errno)));
    }
    if (args.Length() > 3) {
        mode = args[3]->IntegerValue();
    }
    else {
        mode = fileinfo.st_mode;
    }
    mode &= 0777;
    int fd = open(*srcPath, O_RDONLY);
    if (fd < 0) {
        return scope.Close(String::New(strerror(errno)));
    }
#ifdef libssh2_scp_send64
    LIBSSH2_CHANNEL *channel = libssh2_scp_send64(ssh2->mSession, *dstPath, mode, fileinfo.st_size, 0, 0);
#else
    LIBSSH2_CHANNEL *channel = libssh2_scp_send(ssh2->mSession, *dstPath, mode, fileinfo.st_size);
#endif
    if (!channel) {
        char *errmsg;
        int errlen;
        libssh2_session_last_error(ssh2->mSession, &errmsg, &errlen, 0);
        return scope.Close(String::New(errmsg, errlen));
    }
    
    char mem[1024];
    ssize_t toWrite = fileinfo.st_size;
    while (toWrite > 0) {
        ssize_t nRead = read(fd, mem, 1024);
        if (nRead < 0) {
            int eNum = errno;
            libssh2_channel_free(channel);
            close(fd);
            return scope.Close(String::New(strerror(eNum)));
        }
        int rc = libssh2_channel_write(channel, mem, nRead);
        if (rc < 0) {
            char *errmsg;
            int errlen;
            libssh2_session_last_error(ssh2->mSession, &errmsg, &errlen, 0);
            libssh2_channel_free(channel);
            close(fd);
            return scope.Close(String::New(errmsg));
        }
        toWrite -= nRead;
    }
    close(fd);
    libssh2_channel_free(channel);
    return scope.Close(True());
}
Example #2
0
int SamplePool::ImportSample(Path &path) {

	if (count_==MAX_PIG_SAMPLES) return -1 ;

	// construct target path

	std::string dpath="samples:" ;
	dpath+=path.GetName() ;
	Path dstPath(dpath.c_str()) ;

    // Opens files

	I_File *fin=FileSystem::GetInstance()->Open(path.GetPath().c_str(),"r") ;
	if (!fin) {
		Trace::Error("Failed to open input file %s",path.GetPath().c_str()) ;
		return -1;
	} ;
	fin->Seek(0,SEEK_END) ;
	long size=fin->Tell() ;
	fin->Seek(0,SEEK_SET) ;

	I_File *fout=FileSystem::GetInstance()->Open(dstPath.GetPath().c_str(),"w") ;
	if (!fout) {
		fin->Close() ;
		delete (fin) ;
		return -1 ;
	} ;

	// copy file to current project

	char buffer[IMPORT_CHUNK_SIZE] ;
	while (size>0) {
		int count=(size>IMPORT_CHUNK_SIZE)?IMPORT_CHUNK_SIZE:size ;
		fin->Read(buffer,1,count) ;
		fout->Write(buffer,1,count) ;
		size-=count ;
	} ;

	fin->Close() ;
	fout->Close() ;
	delete(fin) ;
	delete(fout) ;

	// now load the sample

	bool status=loadSample(dstPath.GetPath().c_str()) ;

	SetChanged() ;
	SamplePoolEvent ev ;
	ev.index_=count_-1 ;
	ev.type_=SPET_INSERT ;
	NotifyObservers(&ev) ;
	return status?(count_-1):-1 ;
};
Example #3
0
    void
    TeaSafe::renameEntry(std::string const &src, std::string const &dst)
    {
        StateLock lock(m_stateMutex);
        std::string srcPath(src);
        char ch = *src.rbegin();
        // ignore trailing slash
        if (ch == '/') {
            std::string(src.begin(), src.end() - 1).swap(srcPath);
        }
        std::string dstPath(dst);
        char chDst = *dst.rbegin();
        // ignore trailing slash
        if (chDst == '/') {
            std::string(dst.begin(), dst.end() - 1).swap(dstPath);
        }

        // throw if source parent doesn't exist
        SharedTeaSafeFolder parentSrc = doGetParentTeaSafeFolder(srcPath);
        if (!parentSrc) {
            throw TeaSafeException(TeaSafeError::NotFound);
        }

        // throw if destination parent doesn't exist
        SharedTeaSafeFolder parentDst = doGetParentTeaSafeFolder(dstPath);
        if (!parentSrc) {
            throw TeaSafeException(TeaSafeError::NotFound);
        }

        // throw if destination already exists
        throwIfAlreadyExists(dstPath);

        // throw if source doesn't exist
        std::string const filename = boost::filesystem::path(srcPath).filename().string();
        SharedEntryInfo childInfo = parentSrc->getEntryInfo(filename);
        if (!childInfo) {
            throw TeaSafeException(TeaSafeError::NotFound);
        }

        // do moving / renaming
        // (i) Remove original entry metadata entry
        // (ii) Add new metadata entry with new file name
        parentSrc->putMetaDataOutOfUse(filename);
        std::string dstFilename = boost::filesystem::path(dstPath).filename().string();
        parentDst->writeNewMetaDataForEntry(dstFilename, childInfo->type(), childInfo->firstFileBlock());

    }
Example #4
0
/**
 * @function SFTP.writeFile
 * 
 * ### Synopsis
 * 
 * var status = SFTP.writeFile(handle, srcPath, dstPath);
 * var status = SFTP.writeFile(handle, srcPath, dstPath, mode);
 * 
 * Write file to remote server via SFTP.
 * 
 * @param {object} handle - opaque handle to already open SFTP connection.
 * @param {string} srcPath - path to file in local file system to send.
 * @param {string} dstPath - path to file in remote file system to create.
 * @param {int} mode - desired resulting file permissions of file on remote end.
 * @return {boolean} success - true if the transfer succeeded.
 * 
 * ### Note
 * If mode is not provided, the file mode of the file being sent will be used.
 */
static JSVAL sftp_writeFile (JSARGS args) {
    HandleScope scope;
    SFTP *handle = HANDLE(args[0]);
    String::Utf8Value srcPath(args[1]);
    String::Utf8Value dstPath(args[2]);
    int mode;
    struct stat fileinfo;
    if (stat(*srcPath, &fileinfo) != 0) {
        return scope.Close(String::New(strerror(errno)));
    }
    if (args.Length() > 3) {
        mode = args[3]->IntegerValue();
    }
    else {
        mode = fileinfo.st_mode;
    }
    mode &= 0777;
    int fd = open(*srcPath, O_RDONLY);
    if (fd < 0) {
        return scope.Close(String::New(strerror(errno)));
    }
    LIBSSH2_SFTP_HANDLE *sftp_handle = libssh2_sftp_open(handle->sftp_session, *dstPath, LIBSSH2_FXF_WRITE | LIBSSH2_FXF_CREAT | LIBSSH2_FXF_TRUNC, mode);

    char mem[1024];
    ssize_t toWrite = fileinfo.st_size;
    while (toWrite > 0) {
        ssize_t nRead = read(fd, mem, 1024);
        if (nRead < 0) {
            int eNum = errno;
            libssh2_sftp_close(sftp_handle);
            close(fd);
            errno = eNum;
            return scope.Close(False());
        }
        int rc = libssh2_sftp_write(sftp_handle, mem, nRead);
        if (rc < 0) {
            libssh2_sftp_close(sftp_handle);
            close(fd);
            return scope.Close(False());
        }
        toWrite -= nRead;
    }
    close(fd);
    libssh2_sftp_close(sftp_handle);
    return scope.Close(True());
}
void UsrGlblMgrEditDialog::CloneSet(cb_unused wxCommandEvent& event)
{
    wxTextEntryDialog d(this, _("Please specify a name for the new clone:"), _("Clone Set"));
    PlaceWindow(&d);
    if (d.ShowModal() == wxID_OK)
    {
        wxString clone = d.GetValue();
        Sanitise(clone);

        if (clone.IsEmpty())
            return;
        wxArrayString existing = m_CfgMan->EnumerateSubPaths(_T("/sets"));

        if (existing.Index(clone) != wxNOT_FOUND)
        {
            wxString msg;
            msg.Printf(_("Cowardly refusing overwrite existing set \"%s\"."), clone.wx_str());
            InfoWindow::Display(_("Clone Set"), msg);
            return;
        }

        wxString srcPath(cSets + m_CurrentSet + _T("/"));
        wxString dstPath(cSets + clone + _T("/"));
        wxString oldpath, newpath;

        wxArrayString vars = m_CfgMan->EnumerateSubPaths(srcPath);

        for (unsigned int i = 0; i < vars.GetCount(); ++i)
        {
            wxArrayString members = m_CfgMan->EnumerateKeys(srcPath + vars[i]);

            for (unsigned j = 0; j < members.GetCount(); ++j)
            {
                wxString item = vars[i] + _T("/") + members[j];
                m_CfgMan->Write(dstPath + item, m_CfgMan->Read(srcPath + item));
            }
        }
        m_CurrentSet = clone;
        UpdateChoices();
        Load();
    }
}
Example #6
0
VError XLinuxFile::Move(const VFilePath& inDestinationPath, VFileSystem *inDestinationFileSystem, VFile** outFile, FileCopyOptions /*inOptions*/) const
{
	VFilePath dstPath(inDestinationPath);

	if (dstPath.IsFolder())
	{
		VStr255 name;					//jmo - todo : NAME_MAX ?
		fOwner->GetName(name);
		dstPath.SetFileName(name);
	}

	PathBuffer pathBuffer;
	pathBuffer.Init(dstPath);

	//First we try to rename the file...
	VError verr;
	{
		RenameHelper rnmHlp;
		verr=rnmHlp.Rename(fPath, pathBuffer);
	}

	//If Rename() fails because src and dst are not on the same fs, we try a Copy()
	if(verr!=VE_OK && IS_NATIVE_VERROR(verr) && NATIVE_ERRCODE_FROM_VERROR(verr)==EXDEV)
	{
		CopyHelper cpHlp;
		verr = cpHlp.Copy(fPath, pathBuffer);

		// it's a move not a copy, so one must delete the source after a sucessful copy
		if (verr == VE_OK)
		{
			int res=unlink(fPath.GetPath());
			verr = (res==0) ? VE_OK :  MAKE_NATIVE_VERROR(errno);
		}
	}

	if (outFile != NULL)
	{
		*outFile = (verr == VE_OK) ? new VFile( dstPath, inDestinationFileSystem) : NULL;
	}

	return verr;
}
VError XLinuxFile::Move(const VFilePath& inDestinationPath, VFile** outFile, FileCopyOptions inOptions) const
{
	VFilePath dstPath(inDestinationPath);
	
	if (dstPath.IsFolder())
	{
		VStr255 name;					//jmo - todo : NAME_MAX ?
		fOwner->GetName(name);
		dstPath.SetFileName(name);
	}

	//First we try to rename the file...
	VError verr=Rename(dstPath.GetPath(), outFile);

	//If Rename() fails beacause src and dst are not on the same fs, we try a Copy()
	if(verr!=VE_OK && IS_NATIVE_VERROR(verr) && NATIVE_ERRCODE_FROM_VERROR(verr)==EXDEV)
		verr=Copy(inDestinationPath, outFile, inOptions);
	
	return verr;
}
Example #8
0
        inline
        void extractToPhysical(knoxcrypt::CoreFS &theBfs,
                              std::string const &path,
                              std::string const &dst,
                              std::function<void(std::string)> callback)
        {
            std::string dstPath(dst);

            // make sure destination parent has a trailing slash on the end
            if(*dstPath.rbegin() != '/') {
                dstPath.append("/");
            }

            // remove trailing slash from path
            std::string srcPath(path);
            if(*srcPath.rbegin() == '/') {
                srcPath = std::string(path.begin(), path.end() - 1);
            }
            
            // append filename on to dst path
            boost::filesystem::path p(srcPath);
            dstPath.append(p.filename().string());
            

            // create source and sink
            if(theBfs.fileExists(srcPath)) {
                std::stringstream ss;
                ss << "Extracting file "<<dstPath<<"...";
                callback(dstPath);
                knoxcrypt::FileDevice device = theBfs.openFile(srcPath, knoxcrypt::OpenDisposition::buildReadOnlyDisposition());
                device.seek(0, std::ios_base::beg);
                std::ofstream out(dstPath.c_str(), std::ios_base::binary);
                boost::iostreams::copy(device, out);
            } else if(theBfs.folderExists(srcPath)) {
                boost::filesystem::create_directory(dstPath);
                FolderExtractionVisitor visitor(theBfs, srcPath, dstPath, callback);
                recursiveExtract(visitor, theBfs, srcPath);
            }
        }
Example #9
0
VError XLinuxFile::Copy(const VFilePath& inDestination, VFileSystem *inDestinationFileSystem, VFile** outFile, FileCopyOptions /*inOptions*/) const
{
	VFilePath dstPath(inDestination);

	if(dstPath.IsFolder())
	{
		VStr255 name;					//jmo - todo : NAME_MAX ?
		fOwner->GetName(name);
		dstPath.SetFileName(name);
	}

	PathBuffer pathBuffer;
	pathBuffer.Init(dstPath);

	CopyHelper cpHlp;
	VError err = cpHlp.Copy(fPath, pathBuffer);

	if (outFile != NULL)
	{
		*outFile = (err == VE_OK) ? new VFile( dstPath, inDestinationFileSystem) : NULL;
	}

	return err;
}
Example #10
0
int _tmain(int argc, _TCHAR* argv[])
{
	if (argc < 3) {
		_tprintf(_T("Usage: rf <source file/disk path> <desnitantion folder/file>\nFor disk use \\\\.\\H: as source path"));
		return -1;
	}
	HANDLE hFile = CreateFile(argv[1], GENERIC_READ, FILE_SHARE_WRITE | FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
	if (hFile != INVALID_HANDLE_VALUE) {
		UINT64 currentDone(0), totalSize(0);
		LARGE_INTEGER fileSize = {0};
		GetFileSizeEx(hFile, &fileSize);
		totalSize = fileSize.QuadPart;
		if (totalSize == 0) { // Disk Path
			ULARGE_INTEGER li = {0};
			GetDiskFreeSpaceEx(argv[1]+4, NULL, &li, NULL);
			totalSize = li.QuadPart;
		}
		Progress progress;
		progress.SetTask(totalSize);
		ConsoleProgress cp;
		Path dstPath(argv[2]);
		auto updateWSTime = ProcessUtil::GetTickCount(); // Update Writing speed time
		lprintf(_T("\nTime Elapsed: "));
		CountTimer timeElapsed;
		lprintf(_T("\t\t\t\tTime Remaining: "));
		CountTimer timeRemaining(true);
		if (dstPath.IsDir()) {
            CRecoverManager recoverManger;
            recoverManger.SetInputFileHandle(hFile);
            recoverManger.SetSavePath(dstPath);
            recoverManger.SetTotal(totalSize);
            recoverManger.Initialize();
            recoverManger.BeginRecover();
			while (recoverManger.ProcessRecover()) {
                currentDone = recoverManger.GetCurrentDone();
				if (progress.UpdateProgress(currentDone))
					cp.ShowPercentage(progress.GetCurrentPercentageDone());
				auto curTime = ProcessUtil::GetTickCount();
				if (curTime - updateWSTime >= 5000) { // 5 secs passed
					timeRemaining.SetTimeDuration((timeElapsed.GetTimeDuration() * totalSize) / currentDone);
					updateWSTime = curTime;
				}
				timeElapsed.PrintTimeDuration();
				timeRemaining.PrintTimeDuration();
			}
            if (progress.UpdateProgress(currentDone))
                cp.ShowPercentage(progress.GetCurrentPercentageDone());
            recoverManger.EndRecover();
            progress.UpdateProgress(totalSize);
            cp.ShowPercentage(progress.GetCurrentPercentageDone());
        }
		else {
			CFileMapping fileDstMap;
			CFileMapping fileSrcMap;
			//fileSrcMap.GetFileMapping(hFile);
			fileSrcMap.SetFileHandle(hFile);
			//HANDLE hDestFile = CreateFile(argv[2], GENERIC_ALL, FILE_SHARE_READ, NULL, CREATE_ALWAYS, 0, NULL);
			//if (hDestFile != INVALID_HANDLE_VALUE) {
			//	fileDstMap.SetFileHandle(hDestFile);
			if (fileDstMap.GetFileMapping(argv[2], totalSize) != NULL) {
				std::vector<char> buffer;
				buffer.resize(1024*1024);
				size_t size = buffer.size();
				char *buf = &buffer[0];
				while (currentDone < totalSize) {
					DWORD nBytesRead(fileSrcMap.Read(buf, (UINT)size));
					if (nBytesRead > 0) {
						fileDstMap.Write(buf, nBytesRead);
						currentDone += nBytesRead;
						if (progress.UpdateProgress(currentDone))
							cp.ShowPercentage(progress.GetCurrentPercentageDone());
						auto curTime = ProcessUtil::GetTickCount();
						if (curTime - updateWSTime >= 5000) { // 5 secs passed
							double p = progress.GetCurrentPercentageDone();
							if (p < 0.01)
								p = 0.01;
							timeRemaining.SetTimeDuration(__int64((timeElapsed.GetTimeDuration() * (100-p)) / p));
							updateWSTime = curTime;
						}
						timeElapsed.PrintTimeDuration();
						timeRemaining.PrintTimeDuration();
					}
					else break;
				}
				//CloseHandle(hDestFile);
			}
			else _tprintf(_T("Cannot open file: '%s'\nError: %d"), argv[2], GetLastError());
		}
		CloseHandle(hFile);
	}
    else {
        bool bError(true);
        if (GetLastError() == ERROR_ACCESS_DENIED)
            bError = !ProcessUtil::RunApplication(argc, (LPCTSTR*)argv, RAF_ADMIN);
        if (bError)
            _tprintf(_T("Cannot open file: '%s'\nError: %d"), argv[1], GetLastError());
    }
	return 0;
}
Example #11
0
/// for extracting a teasafe file to somewhere on a physical disk location
/// example usage:
/// extract file.txt file:///some/parent/path/
void com_extract(teasafe::TeaSafe &theBfs, std::string const &path, std::string const &dst)
{
    std::string dstPath(dst.begin() + 7, dst.end());
    teasafe::utility::extractToPhysical(theBfs, path, dstPath, std::bind(operationCallback,
                                                                         std::placeholders::_1));
}