Beispiel #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());
}
Beispiel #2
0
void SaveMgrWindow::SaveListCtrl::AddSaveFromPath(wxString path)
{
	if (!wxDirExists(path))
	{
		return;
	}

	wxFileName srcPath(path);
	wxFileName destPath(Path::Combine(m_inst->GetSavesDir(), srcPath.GetFullName()));

	// Skip if the destination is the same as the source.
	if (srcPath.SameAs(destPath))
	{
		return;
	}

	if (!wxFileExists(Path::Combine(path, "level.dat")) &&
		wxMessageBox(_("This folder does not contain a level.dat file. Continue?"), 
		_("Not a valid save."), wxOK | wxCANCEL | wxCENTER, GetParent()) == wxID_CANCEL)
	{
		return;
	}

	if (wxDirExists(destPath.GetFullPath()))
	{
		int ctr = 1;
		wxString dPathName = destPath.GetName();
		while (wxDirExists(destPath.GetFullPath()) && ctr < 9000)
		{
			destPath.SetName(wxString::Format("%s (%i)", dPathName.c_str(), ctr));
			ctr++;
		}

		if (wxMessageBox(wxString::Format(
			_("There's already a save with the filename '%s'. Copy to '%s' instead?"), 
			dPathName.c_str(), destPath.GetFullName().c_str()), 
			_("File already exists."), wxOK | wxCANCEL | wxCENTER, GetParent()) == wxCANCEL)
		{
			return;
		}
	}

	if (wxFileExists(destPath.GetFullPath()))
	{
		wxLogError("Failed to copy world. File already exists.");
		return;
	}

	FileCopyTask *task = new FileCopyTask(path, destPath.GetFullPath());
	TaskProgressDialog dlg(GetParent());
	dlg.ShowModal(task);
	delete task;

	RefreshList();
}
int main(int argc, char *argv[]) {
    Image<byte> I;
    Image<float> Vx, Vy;
    if (!load(I, argc > 1 ? argv[1] : srcPath("salon.png"))) {
        cout << "Echec de lecture d'image" << endl;
        return 1;
    }

    openWindow(I.width(), I.height());
    display(I);
    click();
    cout << "Contraste simple" << endl;
    affiche(I);
    gradient(I, Vx, Vy);
    click();
    cout << "Dérivée selon x par la fonction gradient" <<endl;
    affiche(Vx);
    click();
    cout << "Dérivée selon y par la fonction gradient" <<endl;
    affiche(Vy);

    click();

    Image<float> F = dx(I);

    cout << "Dérivée selon x par la fonction dx" <<endl;

    affiche(F);

    click();

    Image<float> U= dy(I);
    cout << "Dérivée selon y par la fonction dy" <<endl;

    affiche(U);

    click();

    masque(I,F,U);

    Image<float> z = poisson(F,U);
    cout << "Image reconstruite par poisson" <<endl;

    affiche(z);

    endGraphics();
    return 0;
}
Beispiel #4
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());

    }
Beispiel #5
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();
    }
}
Beispiel #7
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);
            }
        }
JNIEXPORT jlong JNICALL
Java_org_apache_subversion_javahl_SVNClient_doExport
(JNIEnv *env, jobject jthis, jstring jsrcPath, jstring jdestPath,
 jobject jrevision, jobject jpegRevision, jboolean jforce,
 jboolean jignoreExternals, jobject jdepth, jstring jnativeEOL)
{
  JNIEntry(SVNClient, doExport);
  SVNClient *cl = SVNClient::getCppObject(jthis);
  if (cl == NULL)
    {
      JNIUtil::throwError(_("bad C++ this"));
      return -1;
    }
  Revision revision(jrevision);
  if (JNIUtil::isExceptionThrown())
    return -1;

  Revision pegRevision(jpegRevision);
  if (JNIUtil::isExceptionThrown())
    return -1;

  JNIStringHolder srcPath(jsrcPath);
  if (JNIUtil::isExceptionThrown())
    return -1;

  JNIStringHolder destPath(jdestPath);
  if (JNIUtil::isExceptionThrown())
    return -1;

  JNIStringHolder nativeEOL(jnativeEOL);
  if (JNIUtil::isExceptionThrown())
    return -1;

  return cl->doExport(srcPath, destPath, revision, pegRevision,
                      jforce ? true : false, jignoreExternals ? true : false,
                      EnumMapper::toDepth(jdepth), nativeEOL);
}
/*!
  Returns a javascript path to \a src. The \a src must be one of URL, a absolute
  path or a relative path. If \a src is a relative path, it must exist
  in the public/js directory.
 */
QString TViewHelper::jsPath(const QString &src, bool withTimestamp) const
{
    return srcPath(src, "/js/", withTimestamp);
}
Beispiel #10
0
static bool localUpdate( const char * pDest, const char * pSrc )
{
	bool bRestart = false;

	ASSERT( pDest[ strlen(pDest) - 1 ] == PATH_SEPERATORC );
	ASSERT( pSrc[ strlen(pSrc) - 1 ] == PATH_SEPERATORC );

	Path srcPath( pSrc );
	CharString sMask( srcPath.directory() + "*" );
	FindFile ff( sMask );

	// make sure destination directory exists
	FileDisk::createDirectory( pDest );

	// move files
	for(int i=0;i<ff.fileCount();i++)
	{
		CharString dstFile;
		dstFile.format( "%s%s", pDest, ff.file(i) );
		CharString srcFile;
		srcFile.format( "%s%s", pSrc, ff.file(i) );

		bool copyFile = false;
		bool copyUpdate = false;
		if ( FileDisk::fileExists( dstFile ) )
		{
			// make sure date of src file is newer
			if ( FileDisk::fileDate( srcFile ) > FileDisk::fileDate( dstFile ) )
			{
				copyFile = true;

				// attempt to delete the old file, if it fails then use MirrorUpdate
				if (! FileDisk::deleteFile( dstFile ) )
					copyUpdate = true;
			}
		}
		else
			copyFile = true;

		bRestart |= copyFile;

		if ( copyFile && copyUpdate )
			FileDisk::copyFile( srcFile, dstFile + ".upd" );
		else if ( copyFile )
			FileDisk::copyFile( srcFile, dstFile );
	}

	// recurse into subdirectories
	for(int i=0;i<ff.directoryCount();i++)
	{
		if ( ff.directory(i)[0] == '.' )
			continue;

		CharString newDst;
		newDst.format( "%s%s" PATH_SEPERATOR, pDest, ff.directory( i ) );
		CharString newSrc;
		newSrc.format( "%s%s" PATH_SEPERATOR, pSrc, ff.directory( i ) );

		bRestart |= localUpdate( newDst, newSrc );
	}

	return bRestart;
}
Beispiel #11
0
static bool copyFiles(const char *toolsDir, const char *tmpDir, const char *globList[]) {
    SetLastError(0);
    WIN32_FIND_DATAA srcFindData;
    WIN32_FIND_DATAA destFindData;
    for (const char **glob = globList; *glob != NULL; glob++) {
        CPath globDir = CPath(*glob).dirName();

        CPath fullGlob(toolsDir);
        fullGlob.addPath(*glob);

        HANDLE srcH = FindFirstFileA(fullGlob.cstr(), &srcFindData);
        if (srcH == INVALID_HANDLE_VALUE) {
            displayLastError("Failed to list files: %s", *glob);
            return false;
        }
        do {
            // Skip directories
            if ((srcFindData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0) {
                continue;
            }
            CPath srcPath(toolsDir);
            srcPath.addPath(globDir).addPath(srcFindData.cFileName);

            CPath destPath(tmpDir);
            destPath.addPath(globDir).addPath(srcFindData.cFileName);

            // Skip copy if files are likely to not have changed.
            HANDLE destH = FindFirstFileA(destPath.cstr(), &destFindData);
            if (destH != INVALID_HANDLE_VALUE) {
                // Size must be same for us to skip it.
                if (srcFindData.nFileSizeHigh == destFindData.nFileSizeHigh &&
                    srcFindData.nFileSizeLow  == destFindData.nFileSizeLow) {
                    // Creation & access times can differ. However if the dest write time
                    // is >= than the source write time, it should be the same file.
                    LARGE_INTEGER srcWriteTime;
                    LARGE_INTEGER dstWriteTime;
                    srcWriteTime.HighPart = srcFindData.ftLastWriteTime.dwHighDateTime;
                    srcWriteTime.LowPart  = srcFindData.ftLastWriteTime.dwLowDateTime;
                    dstWriteTime.HighPart = destFindData.ftLastWriteTime.dwHighDateTime;
                    dstWriteTime.LowPart  = destFindData.ftLastWriteTime.dwLowDateTime;
                    if (dstWriteTime.QuadPart >= srcWriteTime.QuadPart) {
                        FindClose(destH);
                        continue;
                    }
                }

                FindClose(destH);

                // CopyFile copies some attributes. It's common for tools to be unzipped
                // as read-only so we need to remove any r-o attribute on existing
                // files if we want a recopy to succeed.
                if ((destFindData.dwFileAttributes & FILE_ATTRIBUTE_READONLY) != 0) {
                    SetFileAttributes(destPath.cstr(),
                        destFindData.dwFileAttributes ^ FILE_ATTRIBUTE_READONLY);
                }
            }

            if (!CopyFileA(srcPath.cstr(), destPath.cstr(), false /*bFailIfExists*/)) {
                FindClose(srcH);
                displayLastError("Failed to copy file: %s", destPath.cstr());
                return false;
            }
        } while (FindNextFileA(srcH, &srcFindData) != 0);
        FindClose(srcH);
    }
    return true;
}