示例#1
0
QString QtServiceBasePrivate::filePath() const
{
    QString ret;
    if (args.isEmpty())
        return ret;
    QFileInfo fi(args[0]);
    QDir dir(absPath(args[0]));
    return dir.absoluteFilePath(fi.fileName());
}
示例#2
0
void Shell::rm(size_t argc, const std::string* argv)
{
	if(argc < 1)
	{
		printError(ERR_ARGS_INVALID);
		return;
	}
	if(!session->deleteItem(absPath(argv[0]).c_str()))
		printError(session->getErrno());
}
示例#3
0
bool MaItem::load(const QString& filename)
{
	bool res = false;

	if (!filename.isEmpty())
		mFilename = filename;

	mRelPath.clear();
	mRelPath = relPath();
#ifdef _DEBUG
//	qDebug() << absPath();
#endif  // _DEBUG

	QFile file(absPath());
	if (file.open(QIODevice::ReadOnly))
	{
		QTextStream in(&file);
		in.setCodec("UTF-8");
		parseConfigLine(in.readLine());
		if (mIsEncrypted)
		{
			QByteArray s = in.readAll().toAscii();
			_engine->encrypt(s);
			QString s2(s);
			int i = s2.indexOf("\n");
			if (i > -1)
			{
				mCaption = s2.left(i);
				mNotes = s2.right(s2.length() - i - 1);
			}
		}
		else
		{
			mCaption = in.readLine();
			mNotes = in.readAll();
		}
		file.close();
		res = true;
	}

	// Loading the password from the password file:
	QFile file2(absPathToFilename(kPathwordFilename));
	if (file.exists() && file2.open(QIODevice::ReadOnly))
	{
		QTextStream in(&file2);
		in.setCodec("UTF-8");
		QByteArray ba = in.readAll().toAscii();
		QByteArray salt(QString(_engine->passwordEncryptionSalt()).toAscii());
		_engine->encrypt(ba, _engine->passwordEncryptionKey().toAscii(), salt);
		mPassword = ba;
		mPasswordDirty = false;
	}

	return res;
}
示例#4
0
void MaItem::save(bool onlyWhenDirty)
{
	if (!onlyWhenDirty || mDirty)
	{
		bool encrypt = isListEncrypted();
		if (mFilename.isEmpty())
			mFilename = mParentItem->nextChildFilename();
		QFile file(absPath());

		if (file.open(QIODevice::WriteOnly))
		{
			QTextStream out(&file);
			out.setCodec("UTF-8");
			out << configLine(encrypt);
			out << "\n";
			if (encrypt)
			{
				QByteArray s(mCaption.toAscii());
				s.append("\n");
				s.append(mNotes.toAscii());
				_engine->encrypt(s);
				out << s;
			}
			else
			{
				out << mCaption;
				out << "\n";
				out << mNotes;
			}
			file.close();
			mDirty = false;
		}
	}

	// Saving the password:
	if ((!onlyWhenDirty || mPasswordDirty) && !mPassword.isEmpty())
	{
		QFile pwdFile(absPathToFilename(kPathwordFilename));
		if (pwdFile.open(QIODevice::WriteOnly))
		{
			QTextStream out(&pwdFile);
			out.setCodec("UTF-8");
			QByteArray ba(mPassword.toAscii());
			QByteArray salt(QString(_engine->passwordEncryptionSalt()).toAscii());
			_engine->encrypt(ba, _engine->passwordEncryptionKey().toAscii(), salt);
			out << ba;
			pwdFile.close();
			mPasswordDirty = false;
		}
	}
}
示例#5
0
void Shell::see(size_t argc, const std::string* argv)
{
	if(argc < 1)
	{
		printError(ERR_ARGS_INVALID);
		return;
	}
	SafeInfo sfInfo;
	if(!session->getItemSafeInfo(absPath(argv[0]).c_str(), &sfInfo))
	{
		printError(session->getErrno());
		return;
	}
	if(sfInfo.sign & FL_TYPE_FILE)
		std::cout << "file:\t" << absPath(argv[0]);
	else
		std::cout << "folder:\t" << absPath(argv[0]);
	std::cout << "\tmode:\t" << sfInfo.sign % 8 << (sfInfo.sign / 8) % 8;
	std::cout << "\towner:\t" << sfInfo.uid;
	std::cout << "\tcreated:\t" << sfInfo.created;
	std::cout << "\tmodified:\t" << sfInfo.modified;
	std::cout << std::endl;
}
示例#6
0
void Shell::chmod(size_t argc, const std::string* argv)
{
	if(argc < 2)
	{
		printError(ERR_ARGS_INVALID);
		return;
	}
	bool parseSuc;
	int mod = parseInt(argv[1], parseSuc);
	if(!parseSuc || mod / 10 > 7 || mod % 10 > 7)
	{
		printError(ERR_ARGS_INVALID);
		return;
	}
	fsign sign = mod / 10 + (mod % 10) * 8;
	if(!session->changeModel(absPath(argv[0]).c_str(), sign))
		printError(session->getErrno());
}
示例#7
0
void Shell::cat(size_t argc, const std::string* argv)
{
	class _FDGuard
	{
		SessionClient* session;
	public:
		_FDGuard(SessionClient* _ss) : session(_ss) {}
		void operator () (int fd) { session->closeFile(fd); }
	};
	if(argc < 1)
	{
		printError(ERR_ARGS_INVALID);
		return;
	}
	const size_t BUFSIZE = 64;
	std::unique_ptr<char> buf(new char[BUFSIZE + 1]);
	int fd = session->openFile(absPath(argv[0]).c_str(), OPTYPE_READ);
	if(fd <= 0)
	{
		printError(session->getErrno());
		return;
	}
	Guard<int, _FDGuard> gd(fd, _FDGuard(session));
	size_t start = 0;
	while(true)
	{
		int len = session->readFile(fd, buf.get(), BUFSIZE);
		if(len < 0)
		{
			printError(session->getErrno());
			return;
		}
		else if(len == 0)
			break;
		else
		{
			start += len;
			buf.get()[len] = '\0';
			std::cout << buf.get();
		}
	}
	std::cout << std::endl;
	std::cout << "-------END-------" << std::endl;
}
示例#8
0
bool MaItem::remove()
{
	mDirty = false;
    QString absPath(this->absPath());
    const QDir& parentDir(this->parentDir());
	QFile f(absPath);

	if (f.exists())
    {
        QString newName(f.fileName());
        newName.append(kDeletedFileExtension);
        QString newPath(parentDir.filePath(newName));
        QFile f2(newPath);
        if (f2.exists())
            f2.remove();
        return !f.rename(f.fileName(), newName);
    }
	return false;
}
示例#9
0
void Shell::ls(size_t argc, const std::string* argv)
{
	std::string path;
	if(argc < 1)
		path = basePath;
	else
		path = absPath(argv[0]);
	std::vector<std::string> files;
	if(!session->readFolder(path.c_str(), files))
	{
		printError(session->getErrno());
		return;
	}
	if (files.size() == 0)
	{
		std::cout << "-------empty folder-------";
	}
	for(size_t i = 0; i < files.size(); ++i)
		std::cout << files[i] << "\t\t";
	std::cout << std::endl;
}
示例#10
0
std::vector<CacheManager::LoadedCacheInfo> CacheManager::cacheInformationFromDirectory(
    const Directory& dir) const
{
    std::vector<LoadedCacheInfo> result;
    std::vector<std::string> directories = dir.readDirectories(false);
    for (const auto& directory : directories) {
        Directory d(directory);

        // Extract the name of the directory
        // +1 as the last path delimiter is missing from the path
        std::string directoryName = directory.substr(dir.path().size() + 1);
        
        std::vector<std::string> hashes = d.readDirectories();
        for (const auto& hash : hashes) {
            // Extract the hash from the directory name
            // +1 as the last path delimiter is missing from the path
            std::string hashName = hash.substr(d.path().size() + 1);
            
            std::vector<std::string> files = Directory(hash).readFiles();
            // Cache directories should only contain a single file with the
            // same name as the directory
            if (files.size() > 1)
                LERROR("Directory '" << hash << "' contained more than one file");
            if (files.size() == 1) {
                // Extract the file name from the full path
                // +1 as the last path delimiter is missing from the path
                std::string filename = files[0].substr(Directory(hash).path().size() + 1);
				if (filename != directoryName)
					LERROR("File contained in cache directory '" <<
					hash << "' contains a file with name '" << filename <<
					"instead of the expected '" << directoryName << "'");
				else
					// Adding the absPath to normalize all / and \ for Windows 
					result.emplace_back(std::stoul(hashName), absPath(files[0]));
            }
        }
    }
    
    return result;
}
示例#11
0
void Shell::mkfile(size_t argc, const std::string* argv)
{
	if(argc < 1)
	{
		printError(ERR_ARGS_INVALID);
		return;
	}
	std::string abspth, parent, name;
	abspth = absPath(argv[0]);
	parent = parentPath(abspth);
	if(parent == "/")
		name = abspth.substr(1, abspth.size() - 1);
	else
		name = abspth.substr(parent.size() + 1, abspth.size() - (parent.size() + 1));
	if(parent == "" || name == "")
	{
		printError(ERR_ARGS_INVALID);
		return;
	}
	if(!session->createFile(parent.c_str(), name.c_str()))
		printError(session->getErrno());
}
示例#12
0
void EbookController::OnClickedLink(int pageNo, DrawInstr *link)
{
    ScopedMem<WCHAR> url(str::conv::FromHtmlUtf8(link->str.s, link->str.len));
    if (url::IsAbsolute(url)) {
        EbookTocDest dest(nullptr, url);
        cb->GotoLink(&dest);
        return;
    }

    if (Doc_Epub == doc.Type() && pages && (size_t)pageNo <= pages->Count()) {
        // normalize the URL by combining it with the chapter's base path
        for (int j = pageNo; j > 0; j--) {
            HtmlPage *p = pages->At(j - 1);
            // <pagebreak src="..." page_marker /> is usually the second instruction on a page
            for (size_t k = 0; k < std::min((size_t)2, p->instructions.Count()); k++) {
                DrawInstr& di = p->instructions.At(k);
                if (InstrAnchor == di.type && str::StartsWith(di.str.s + di.str.len, "\" page_marker />")) {
                    ScopedMem<char> basePath(str::DupN(di.str.s, di.str.len));
                    ScopedMem<char> relPath(ResolveHtmlEntities(link->str.s, link->str.len));
                    ScopedMem<char> absPath(NormalizeURL(relPath, basePath));
                    url.Set(str::conv::FromUtf8(absPath));
                    j = 0; // done
                    break;
                }
            }
        }
    }

    int idx = ResolvePageAnchor(url);
    if (-1 == idx && str::FindChar(url, '%')) {
        url::DecodeInPlace(url);
        idx = ResolvePageAnchor(url);
    }
    if (idx != -1) {
        EbookTocDest dest(nullptr, idx);
        cb->GotoLink(&dest);
    }
}
示例#13
0
void Shell::open(size_t argc, const std::string* argv)
{
	if(argc < 1)
	{
		printError(ERR_ARGS_INVALID);
		return;
	}
	fdtype_t type = 0;
	//根据参数填写打开的方式type
	for(size_t i = 1; i < argc; ++i)
	{
		const std::string& arg = argv[i];
		if(arg == "-r")								//读的方式打开
			type |= OPTYPE_READ;
		else if(arg == "-w")						//写的方式打开
			type |= OPTYPE_WRITE;
		else if(arg == "-rw" || arg == "-wr")		//读写的方式打开
			type |= OPTYPE_WRITE | OPTYPE_READ;
		else if(arg == "-lmr")						//加上读互斥锁
			type |= OPTYPE_RAD_MTX_LOCK;
		else if(arg == "-lsr")						//加上读共享锁
			type |= OPTYPE_RAD_SHR_LOCK;
		else if(arg == "-lmw")						//加上写互斥锁
			type |= OPTYPE_WTE_MTX_LOCK;
		else if(arg == "-lsw")						//加上写共享锁
			type |= OPTYPE_WTE_SHR_LOCK;
	}

	if(!(type & OPTYPE_READ) | (type & OPTYPE_WRITE))
		type |= OPTYPE_WRITE | OPTYPE_READ;
	int fd = session->openFile(absPath(argv[0]).c_str(), type);
	if(fd == 0)
		printError(session->getErrno());
	else
		std::cout << "fd: " << fd << std::endl;
}
void RenderablePlaneProjection::loadTexture() {
	if (_texturePath != "") {
        std::unique_ptr<ghoul::opengl::Texture> texture = ghoul::io::TextureReader::ref().loadTexture(absPath(_texturePath));
		if (texture) {
			texture->uploadTexture();
            // TODO: AnisotropicMipMap crashes on ATI cards ---abock
            //texture->setFilter(ghoul::opengl::Texture::FilterMode::AnisotropicMipMap);
            texture->setFilter(ghoul::opengl::Texture::FilterMode::Linear);
            _texture = std::move(texture);

			delete _textureFile;
			_textureFile = new ghoul::filesystem::File(_texturePath);
			_textureFile->setCallback([&](const ghoul::filesystem::File&) { _textureIsDirty = true; });
		}
	}
}
示例#15
0
bool SceneGraph::loadFromFile(const std::string& sceneDescription) {
    clear(); // Move this to a later stage to retain a proper scenegraph when the loading fails ---abock

    std::string absSceneFile = absPath(sceneDescription);

    // See if scene file exists
    if (!FileSys.fileExists(absSceneFile, true)) {
        LERROR("Could not load scene file '" << absSceneFile << "'. " <<
            "File not found");
        return false;
    }
    LINFO("Loading SceneGraph from file '" << absSceneFile << "'");

    // Load dictionary
    ghoul::Dictionary sceneDictionary;
    try {
        ghoul::lua::loadDictionaryFromFile(absSceneFile, sceneDictionary);
    }
    catch (...) {
        return false;
    }

    std::string sceneDescriptionDirectory =
    ghoul::filesystem::File(absSceneFile, true).directoryName();
    std::string sceneDirectory(".");
    sceneDictionary.getValue(KeyPathScene, sceneDirectory);

    // The scene path could either be an absolute or relative path to the description
    // paths directory
    std::string relativeCandidate = sceneDescriptionDirectory +
        ghoul::filesystem::FileSystem::PathSeparator + sceneDirectory;
    std::string absoluteCandidate = absPath(sceneDirectory);

    if (FileSys.directoryExists(relativeCandidate))
        sceneDirectory = relativeCandidate;
    else if (FileSys.directoryExists(absoluteCandidate))
        sceneDirectory = absoluteCandidate;
    else {
        LERROR("The '" << KeyPathScene << "' pointed to a "
            "path '" << sceneDirectory << "' that did not exist");
        return false;
    }

    ghoul::Dictionary moduleDictionary;
    bool success = sceneDictionary.getValue(KeyModules, moduleDictionary);
    if (!success)
        // There are no modules that are loaded
        return true;

    lua_State* state = ghoul::lua::createNewLuaState();
    OsEng.scriptEngine().initializeLuaState(state);

    // Get the common directory
    bool commonFolderSpecified = sceneDictionary.hasKey(KeyCommonFolder);
    bool commonFolderCorrectType = sceneDictionary.hasKeyAndValue<std::string>(KeyCommonFolder);

    if (commonFolderSpecified) {
        if (commonFolderCorrectType) {
            std::string commonFolder = sceneDictionary.value<std::string>(KeyCommonFolder);
            std::string fullCommonFolder = FileSys.pathByAppendingComponent(
                sceneDirectory,
                commonFolder
            );
            if (!FileSys.directoryExists(fullCommonFolder))
                LERROR("Specified common folder '" << fullCommonFolder << "' did not exist");
            else {
                if (!commonFolder.empty()) {
                    FileSys.registerPathToken(_commonModuleToken, commonFolder);
                    size_t nKeys = moduleDictionary.size();
                    moduleDictionary.setValue(std::to_string(nKeys + 1), commonFolder);
                }
            }
        }
        else
            LERROR("Specification for 'common' folder has invalid type");
    }

    std::vector<std::string> keys = moduleDictionary.keys();

    std::map<std::string, std::vector<std::string>> dependencies;
    std::map<std::string, std::string> parents;

    _rootNode = new SceneGraphNode;
    _rootNode->setName(SceneGraphNode::RootNodeName);
    SceneGraphNodeInternal* internalRoot = new SceneGraphNodeInternal;
    internalRoot->node = _rootNode;
    _nodes.push_back(internalRoot);

    std::sort(keys.begin(), keys.end());
    ghoul::filesystem::Directory oldDirectory = FileSys.currentDirectory();
    for (const std::string& key : keys) {
        std::string moduleName = moduleDictionary.value<std::string>(key);
        std::string modulePath = FileSys.pathByAppendingComponent(sceneDirectory, moduleName);

        if (!FileSys.directoryExists(modulePath)) {
            LERROR("Could not load module '" << moduleName << "'. Directory did not exist");
            continue;
        }

        std::string moduleFile = FileSys.pathByAppendingComponent(
            modulePath,
            moduleName + _moduleExtension
        );

        if (!FileSys.fileExists(moduleFile)) {
            LERROR("Could not load module file '" << moduleFile << "'. File did not exist");
            continue;
        }

        ghoul::Dictionary moduleDictionary;
        try {
            ghoul::lua::loadDictionaryFromFile(moduleFile, moduleDictionary, state);
        }
        catch (...) {
            continue;
        }

        std::vector<std::string> keys = moduleDictionary.keys();
        for (const std::string& key : keys) {
            if (!moduleDictionary.hasValue<ghoul::Dictionary>(key)) {
                LERROR("SceneGraphNode '" << key << "' is not a table in module '"
                                             << moduleFile << "'");
                continue;
            }

            ghoul::Dictionary element;
            std::string nodeName;
            std::string parentName;

            moduleDictionary.getValue(key, element);
            element.setValue(KeyPathModule, modulePath);

            element.getValue(SceneGraphNode::KeyName, nodeName);
            element.getValue(SceneGraphNode::KeyParentName, parentName);

            FileSys.setCurrentDirectory(modulePath);
            SceneGraphNode* node = SceneGraphNode::createFromDictionary(element);
            if (node == nullptr) {
                LERROR("Error loading SceneGraphNode '" << nodeName << "' in module '" << moduleName << "'");
                continue;
                //clear();
                //return false;
            }

            dependencies[nodeName].push_back(parentName);
            parents[nodeName] = parentName;
            // Also include loaded dependencies

            if (element.hasKey(SceneGraphNode::KeyDependencies)) {
                if (element.hasValue<ghoul::Dictionary>(SceneGraphNode::KeyDependencies)) {
                    ghoul::Dictionary nodeDependencies;
                    element.getValue(SceneGraphNode::KeyDependencies, nodeDependencies);

                    std::vector<std::string> keys = nodeDependencies.keys();
                    for (const std::string& key : keys) {
                        std::string value = nodeDependencies.value<std::string>(key);
                        dependencies[nodeName].push_back(value);
                    }
                }
                else {
                    LERROR("Dependencies did not have the corrent type");
                }
            }


            SceneGraphNodeInternal* internalNode = new SceneGraphNodeInternal;
            internalNode->node = node;
            _nodes.push_back(internalNode);
        }
    }
    ghoul::lua::destroyLuaState(state);
    FileSys.setCurrentDirectory(oldDirectory);

    for (SceneGraphNodeInternal* node : _nodes) {
        if (node->node == _rootNode)
            continue;
        std::string parent = parents[node->node->name()];
        SceneGraphNode* parentNode = sceneGraphNode(parent);
        if (parentNode == nullptr) {
            LERROR("Could not find parent '" << parent << "' for '" << node->node->name() << "'");
        }

        node->node->setParent(parentNode);
    }

    // Setup dependencies
    for (SceneGraphNodeInternal* node : _nodes) {
        std::vector<std::string> nodeDependencies = dependencies[node->node->name()];

        for (const std::string& dep : nodeDependencies) {
            SceneGraphNodeInternal* n = nodeByName(dep);
            if (n == nullptr) {
                LERROR("Dependent node '" << dep << "' was not loaded for '" <<node->node->name() << "'");
                continue;
            }
            node->outgoingEdges.push_back(n);
            n->incomingEdges.push_back(node);
        }
    }

    std::vector<SceneGraphNodeInternal*> nodesToDelete;
    for (SceneGraphNodeInternal* node : _nodes) {
        if (!nodeIsDependentOnRoot(node)) {
            LERROR("Node '" << node->node->name() << "' has no direct connection to Root.");
            nodesToDelete.push_back(node);
        }
    }

    for (SceneGraphNodeInternal* node : nodesToDelete) {
        _nodes.erase(std::find(_nodes.begin(), _nodes.end(), node));
        delete node;
    }

    bool s = sortTopologically();
    if (!s) {
        LERROR("Topological sort failed");
        return false;
    }
    
    return true;
}
示例#16
0
bool loadDictionaryFromFile(
    const std::string& filename,
    ghoul::Dictionary& dictionary,
    lua_State* state
    )
{
    const static std::string _loggerCat = "lua_loadDictionaryFromFile";

    if (state == nullptr) {
        if (_state == nullptr) {
            LDEBUG("Creating Lua state");
            _state = luaL_newstate();
            if (_state == nullptr) {
                LFATAL("Error creating new Lua state: Memory allocation error");
                return false;
            }
            LDEBUG("Open libraries");
            luaL_openlibs(_state);
        }
        state = _state;
    }

    if (filename.empty()) {
        LERROR("Filename was empty");
        return false;
    }

    if (!FileSys.fileExists(absPath(filename))) {
        LERROR("File '" << absPath(filename) << "' did not exist");
        return false;
    }

    LDEBUG("Loading dictionary script '" << filename << "'");
    int status = luaL_loadfile(state, absPath(filename).c_str());
    if (status != LUA_OK) {
        LERROR("Error loading script: '" << lua_tostring(state, -1) << "'");
        return false;
    }

    LDEBUG("Executing script");
    if (lua_pcall(state, 0, LUA_MULTRET, 0)) {
        LERROR("Error executing script: " << lua_tostring(state, -1));
        return false;
    }

    if (lua_isnil(state, -1)) {
        LERROR("Error in script: '" << filename << "'. Script did not return anything.");
        return false;
    }

    if (!lua_istable(state, -1)) {
        LERROR("Error in script: '" << filename << "'. Script did not return a table.");
        return false;
    }

    luaDictionaryFromState(state, dictionary);

    // Clean up after ourselves by cleaning the stack
    lua_settop(state, 0);

    return true;
}
示例#17
0
// Recursivly add all book files to the list
void BookList::addAllBooks (QString dirpath, bool isUserBooks, int parentindex)
{
    QDir cdir(absPath(dirpath));

    //Get all .folder or .obk files in the directory
    QStringList filter; filter << "*.folder" << "*.obk" << "*.pdf" << "*.link" << "*.html" << "*.htm";
    QFileInfoList list = cdir.entryInfoList(filter, QDir::AllEntries | QDir::NoSymLinks | QDir::NoDotAndDotDot, QDir::Name);

    //TODO: Add pdf, html, etc'

    for (int i=0; i<list.size(); i++)
    {
        Book::Filetype ft;
        if (list[i].fileName().endsWith(".folder", Qt::CaseInsensitive))
            ft = Book::Dir;
        else if (list[i].fileName().endsWith(".obk", Qt::CaseInsensitive))
            ft = Book::Normal;
        else if (list[i].fileName().endsWith(".html", Qt::CaseInsensitive) || list[i].fileName().endsWith(".htm", Qt::CaseInsensitive))
            ft = Book::Html;
        else if (list[i].fileName().endsWith(".pdf", Qt::CaseInsensitive))
            ft = Book::Pdf;
        else if (list[i].fileName().endsWith(".link", Qt::CaseInsensitive))
            ft = Book::Link;
        else
            ft = Book::Unkown;

        if ( ft != Book::Unkown )
        {
            if ( list[i].fileName().indexOf("Pics") != -1 )
                continue;

            QString Name = list[i].fileName();
            if (!isUserBooks)
                Name.replace(QRegExp("^[0-9 ]*"), "").replace("_", " ").replace(".obk", "");

            //Create BookListItem
            Book *b = new Book(parentindex != -1 ? (*this)[parentindex] : NULL,
                                   list[i].absoluteFilePath(), list[i].absoluteFilePath(), Name, ft, isUserBooks);

            //Tell the parent it has a new child
            if (b->getParent() != NULL)
                b->getParent()->add_child(b);

            //Add this book to the list
            push_back(b);

            //Add folder entry, and all files in that folder
            if (ft == Book::Dir)
            {
                //Do the whole thing again for any dir, sending it's index in the list as the
                // Parents index of all it's children
                addAllBooks(list[i].absoluteFilePath().replace(".folder", ""), isUserBooks, this->size() - 1);

                //Add confs for this directory
                QList <QString> t;
                t.clear();
                if (ReadFileToList(list[i].absoluteFilePath(), t , "UTF-8")) AddBookConfs(b, t);
            }

            //Add orayta-book
            else if ( ft == Book::Normal )
            {
                //Add confs for this book
                QList <QString> t;
                t.clear();
                if (ReadZipComment(list[i].absoluteFilePath(), t, "UTF-8")) AddBookConfs(b, t);
            }

            else if ( ft == Book::Link )
            {
                //Add confs for this book
                AddBookConfs(b, readfile(b->getPath(), "UTF-8").split("\n"));
            }

            else if ( ft == Book::Html )
            {
                //Add confs for this book
                AddBookConfs(b, readfile(b->getPath().replace(QRegExp("\\.\\w{3,4}$"),".conf"), "UTF-8").split("\n"));
            }

        }
    }

    /*
    for (int i=0; i<list.size(); i++)
    {
        Book::Filetype ft;

        // set the file type
        if (list[i].isDir())
            ft = Book::Dir;
        else if (list[i].fileName().endsWith(".txt", Qt::CaseInsensitive))
            ft = Book::Normal;
        else if (list[i].fileName().endsWith(".html", Qt::CaseInsensitive) || list[i].fileName().endsWith(".htm", Qt::CaseInsensitive))
            ft = Book::Html;
        else if (list[i].fileName().endsWith(".pdf", Qt::CaseInsensitive))
            ft = Book::Pdf;
        else if (list[i].fileName().endsWith(".link", Qt::CaseInsensitive))
            ft = Book::Link;
        else
            ft = Book::Unkown;

        if ( ft != Book::Unkown )
        {
            if ( list[i].fileName().indexOf("Pics") != -1 )
                continue;

            QString Name = list[i].fileName();
            if (!isUserBooks)
                Name.replace(QRegExp("^[0-9 ]*"), "").replace("_", " ");

            //Create BookListItem
            Book *b = new Book(parentindex != -1 ? (*this)[parentindex] : NULL,
                                   list[i].absoluteFilePath(), list[i].absoluteFilePath(), Name, ft, isUserBooks);

            //Tell the parent it has a new child
            if (b->getParent() != NULL)
                b->getParent()->add_child(b);

            //Add this book to the list
            push_back(b);

            if ( ft == Book::Normal )
            {
                //Add confs for this book
                AddBookConfs(b, b->getPath().replace(".txt",".conf"));
            }

            if ( ft == Book::Html )
            {
                //Add confs for this book
                AddBookConfs(b, b->getPath().replace(QRegExp("\\.\\w{3,4}$"),".conf"));
            }

            if ( ft == Book::Link )
            {
                //Add confs for this book
                AddBookConfs(b, b->getPath());
            }

            if ( isUserBooks )
            {
                //b->setIsInSearch(false);
            }
            else
            {
                // call this after AddBookConfs
                b->loadFont();
            }

            if (ft == Book::Dir)
            {
                //Do the whole thing again for any dir, sending it's index in the list as the
                // Parents index of all it's children
                addAllBooks(list[i].absoluteFilePath(), isUserBooks, this->size() - 1);

                //Add confs for this directory
                AddBookConfs(b, b->getPath().append(".conf"));

            }
        }
    }
    */
}
示例#18
0
void InteractionHandler::writeKeyboardDocumentation(const std::string& type, const std::string& file)
{
    if (type == "text") {
        std::ofstream f;
        f.exceptions(~std::ofstream::goodbit);
        f.open(absPath(file));
        
        for (const auto& p : _keyLua) {
            f << std::to_string(p.first) << ": " <<
                p.second << std::endl;
        }
    }
    else if (type == "html") {
        std::ofstream f;
        f.exceptions(~std::ofstream::goodbit);
        f.open(absPath(file));

#ifdef JSON
        std::stringstream json;
        json << "[";
        for (const auto& p : _keyLua) {
            json << "{";
            json << "\"key\": \"" << std::to_string(p.first) << "\",";
            json << "\"script\": \"" << p.second << "\",";
            json << "},";
        }
        json << "]";

        std::string jsonText = json.str();

#else
        std::stringstream html;

        html << "<html>\n"
             << "\t<head>\n"
             << "\t\t<title>Key Bindings</title>\n"
             << "\t</head>\n"
             << "<body>\n"
             << "<table cellpadding=3 cellspacing=0 border=1>\n"
             << "\t<caption>Key Bindings</caption>\n\n"
             << "\t<thead>\n"
             << "\t\t<tr>\n"
             << "\t\t\t<td>Key</td>\n"
             << "\t\t\t<td>Binding</td>\n"
             << "\t\t</tr>\n"
             << "\t</thead>\n"
             << "\t<tbody>\n";

        for (const auto& p : _keyLua) {
            html << "\t\t<tr>\n"
                 << "\t\t\t<td>" << std::to_string(p.first) << "</td>\n"
                 << "\t\t\t<td>" << p.second << "</td>\n"
                 << "\t\t</tr>\n";
        }

        html << "\t</tbody>\n"
             << "</table>\n"
             << "</html>";

        f << html.str();
#endif

    }
    else {
        throw ghoul::RuntimeError(
            "Unsupported keyboard documentation type '" + type + "'",
            "InteractionHandler"
        );
    }
}
示例#19
0
void RenderableStars::update(const UpdateData& data) {
    if (_dataIsDirty) {
        const int value = _colorOption;
        LDEBUG("Regenerating data");

        createDataSlice(ColorOption(value));

        int size = static_cast<int>(_slicedData.size());

        if (_vao == 0) {
            glGenVertexArrays(1, &_vao);
            LDEBUG("Generating Vertex Array id '" << _vao << "'");
        }
        if (_vbo == 0) {
            glGenBuffers(1, &_vbo);
            LDEBUG("Generating Vertex Buffer Object id '" << _vbo << "'");
        }
        glBindVertexArray(_vao);
        glBindBuffer(GL_ARRAY_BUFFER, _vbo);
        glBufferData(GL_ARRAY_BUFFER,
            size*sizeof(GLfloat),
            &_slicedData[0],
            GL_STATIC_DRAW);

        GLint positionAttrib = _program->attributeLocation("in_position");
        GLint brightnessDataAttrib = _program->attributeLocation("in_brightness");

        const size_t nStars = _fullData.size() / _nValuesPerStar;
        const size_t nValues = _slicedData.size() / nStars;

        GLsizei stride = static_cast<GLsizei>(sizeof(GLfloat) * nValues);

        glEnableVertexAttribArray(positionAttrib);
        glEnableVertexAttribArray(brightnessDataAttrib);
        const int colorOption = _colorOption;
        switch (colorOption) {
        case ColorOption::Color:
            glVertexAttribPointer(positionAttrib, 4, GL_FLOAT, GL_FALSE, stride,
                reinterpret_cast<void*>(offsetof(ColorVBOLayout, position)));
            glVertexAttribPointer(brightnessDataAttrib, 3, GL_FLOAT, GL_FALSE, stride,
                reinterpret_cast<void*>(offsetof(ColorVBOLayout, bvColor)));
            
            break;
        case ColorOption::Velocity:
            {
                glVertexAttribPointer(positionAttrib, 4, GL_FLOAT, GL_FALSE, stride,
                    reinterpret_cast<void*>(offsetof(VelocityVBOLayout, position)));
                glVertexAttribPointer(brightnessDataAttrib, 3, GL_FLOAT, GL_FALSE, stride,
                    reinterpret_cast<void*>(offsetof(VelocityVBOLayout, bvColor)));

                GLint velocityAttrib = _program->attributeLocation("in_velocity");
                glEnableVertexAttribArray(velocityAttrib);
                glVertexAttribPointer(velocityAttrib, 3, GL_FLOAT, GL_TRUE, stride,
                    reinterpret_cast<void*>(offsetof(VelocityVBOLayout, vx)));

                break;
            }
        case ColorOption::Speed:
            {
                glVertexAttribPointer(positionAttrib, 4, GL_FLOAT, GL_FALSE, stride,
                    reinterpret_cast<void*>(offsetof(SpeedVBOLayout, position)));
                glVertexAttribPointer(brightnessDataAttrib, 3, GL_FLOAT, GL_FALSE, stride,
                    reinterpret_cast<void*>(offsetof(SpeedVBOLayout, bvColor)));

                GLint speedAttrib = _program->attributeLocation("in_speed");
                glEnableVertexAttribArray(speedAttrib);
                glVertexAttribPointer(speedAttrib, 1, GL_FLOAT, GL_TRUE, stride,
                    reinterpret_cast<void*>(offsetof(SpeedVBOLayout, speed)));

            }
        }

        glBindBuffer(GL_ARRAY_BUFFER, 0);
        glBindVertexArray(0);

        _dataIsDirty = false;
    }    

    if (_pointSpreadFunctionTextureIsDirty) {
        LDEBUG("Reloading Point Spread Function texture");
        _pointSpreadFunctionTexture = nullptr;
        if (_pointSpreadFunctionTexturePath.value() != "") {
            _pointSpreadFunctionTexture = std::move(ghoul::io::TextureReader::ref().loadTexture(absPath(_pointSpreadFunctionTexturePath)));
            
            if (_pointSpreadFunctionTexture) {
                LDEBUG("Loaded texture from '" << absPath(_pointSpreadFunctionTexturePath) << "'");
                _pointSpreadFunctionTexture->uploadTexture();
            }
            _pointSpreadFunctionTexture->setFilter(ghoul::opengl::Texture::FilterMode::AnisotropicMipMap);

            delete _psfTextureFile;
            _psfTextureFile = new ghoul::filesystem::File(_pointSpreadFunctionTexturePath);
            _psfTextureFile->setCallback([&](const ghoul::filesystem::File&) { _pointSpreadFunctionTextureIsDirty = true; });
        }
        _pointSpreadFunctionTextureIsDirty = false;
    }

    if (_colorTextureIsDirty) {
        LDEBUG("Reloading Color Texture");
        _colorTexture = nullptr;
        if (_colorTexturePath.value() != "") {
            _colorTexture = std::move(ghoul::io::TextureReader::ref().loadTexture(absPath(_colorTexturePath)));
            if (_colorTexture) {
                LDEBUG("Loaded texture from '" << absPath(_colorTexturePath) << "'");
                _colorTexture->uploadTexture();
            }

            delete _colorTextureFile;
            _colorTextureFile = new ghoul::filesystem::File(_colorTexturePath);
            _colorTextureFile->setCallback([&](const ghoul::filesystem::File&) { _colorTextureIsDirty = true; });
        }
        _colorTextureIsDirty = false;
    }
}
bool Filters::BT_ThMLHTML::handleToken(sword::SWBuf &buf, const char *token, sword::BasicFilterUserData *userData) {
    if (!substituteToken(buf, token) && !substituteEscapeString(buf, token)) {
        sword::XMLTag tag(token);
        BT_UserData* myUserData = dynamic_cast<BT_UserData*>(userData);
        sword::SWModule* myModule = const_cast<sword::SWModule*>(myUserData->module); //hack to be able to call stuff like Lang()

        if ( tag.getName() && !sword::stricmp(tag.getName(), "foreign") ) { // a text part in another language, we have to set the right font

            if (tag.getAttribute("lang")) {
                const char* abbrev = tag.getAttribute("lang");
                //const CLanguageMgr::Language* const language = CPointers::languageMgr()->languageForAbbrev( QString::fromLatin1(abbrev) );

                buf.append("<span class=\"foreign\" lang=\"");
                buf.append(abbrev);
                buf.append("\">");
            }
        }
        else if (tag.getName() && !sword::stricmp(tag.getName(), "sync")) { //lemmas, morph codes or strongs

            if (tag.getAttribute("type") && (!sword::stricmp(tag.getAttribute("type"), "morph") || !sword::stricmp(tag.getAttribute("type"), "Strongs") || !sword::stricmp(tag.getAttribute("type"), "lemma"))) { // Morph or Strong
                buf.append('<');
                buf.append(token);
                buf.append('>');
            }
        }
        else if (tag.getName() && !sword::stricmp(tag.getName(), "note")) { // <note> tag

            if (!tag.isEndTag() && !tag.isEmpty()) {
                //appending is faster than appendFormatted
                buf.append(" <span class=\"footnote\" note=\"");
                buf.append(myModule->Name());
                buf.append('/');
                buf.append(myUserData->key->getShortText());
                buf.append('/');
                buf.append( QString::number(myUserData->swordFootnote++).toUtf8().constData() );
                buf.append("\">*</span> ");

                myUserData->suspendTextPassThru = true;
                myUserData->inFootnoteTag = true;
            }
            else if (tag.isEndTag() && !tag.isEmpty()) { //end tag
                //buf += ")</span>";
                myUserData->suspendTextPassThru = false;
                myUserData->inFootnoteTag = false;
            }
        }
        else if (tag.getName() && !sword::stricmp(tag.getName(), "scripRef")) { // a scripRef
            //scrip refs which are embeded in footnotes may not be displayed!

            if (!myUserData->inFootnoteTag) {
                if (tag.isEndTag()) {
                    if (myUserData->inscriptRef) { // like "<scripRef passage="John 3:16">See John 3:16</scripRef>"
                        buf.append("</a></span>");

                        myUserData->inscriptRef = false;
                        myUserData->suspendTextPassThru = false;
                    }
                    else { // like "<scripRef>John 3:16</scripRef>"

                        CSwordModuleInfo* mod = CBTConfig::get(CBTConfig::standardBible);
                        //Q_ASSERT(mod); tested later
                        if (mod) {
                            ReferenceManager::ParseOptions options;
                            options.refBase = QString::fromUtf8(myUserData->key->getText()); //current module key
                            options.refDestinationModule = QString(mod->name());
                            options.sourceLanguage = QString(myModule->Lang());
                            options.destinationLanguage = QString("en");

                            //it's ok to split the reference, because to descriptive text is given
                            bool insertSemicolon = false;
                            buf.append("<span class=\"crossreference\">");
                            QStringList refs = QString::fromUtf8(myUserData->lastTextNode.c_str()).split(";");
                            QString oldRef; //the previous reference to use as a base for the next refs
                            for (QStringList::iterator it(refs.begin()); it != refs.end(); ++it) {

                                if (! oldRef.isEmpty() ) {
                                    options.refBase = oldRef; //use the last ref as a base, e.g. Rom 1,2-3, when the next ref is only 3:3-10
                                }
                                const QString completeRef( ReferenceManager::parseVerseReference((*it), options) );

                                oldRef = completeRef; //use the parsed result as the base for the next ref.

                                if (insertSemicolon) { //prepend a ref divider if we're after the first one
                                    buf.append("; ");
                                }

                                buf.append("<a href=\"");
                                buf.append(
                                    ReferenceManager::encodeHyperlink(
                                        mod->name(),
                                        completeRef,
                                        ReferenceManager::typeFromModule(mod->type())
                                    ).toUtf8().constData()
                                );

                                buf.append("\" crossrefs=\"");
                                buf.append((const char*)completeRef.toUtf8());
                                buf.append("\">");

                                buf.append((const char*)(*it).toUtf8());

                                buf.append("</a>");

                                insertSemicolon = true;
                            }
                            buf.append("</span>"); //crossref end
                        }

                        myUserData->suspendTextPassThru = false;
                    }
                }
                else if (tag.getAttribute("passage") ) { //the passage was given as a parameter value
                    myUserData->inscriptRef = true;
                    myUserData->suspendTextPassThru = false;

                    const char* ref = tag.getAttribute("passage");
                    Q_ASSERT(ref);

                    CSwordModuleInfo* mod = CBTConfig::get(CBTConfig::standardBible);
                    //Q_ASSERT(mod); tested later

                    ReferenceManager::ParseOptions options;
                    options.refBase = QString::fromUtf8(myUserData->key->getText());

                    options.sourceLanguage = myModule->Lang();
                    options.destinationLanguage = QString("en");

                    const QString completeRef = ReferenceManager::parseVerseReference(QString::fromUtf8(ref), options);

                    if (mod) {
                        options.refDestinationModule = QString(mod->name());
                        buf.append("<span class=\"crossreference\">");
                        buf.append("<a href=\"");
                        buf.append(
                            ReferenceManager::encodeHyperlink(
                                mod->name(),
                                completeRef,
                                ReferenceManager::typeFromModule(mod->type())
                            ).toUtf8().constData()
                        );
                        buf.append("\" crossrefs=\"");
                        buf.append((const char*)completeRef.toUtf8());
                        buf.append("\">");
                    }
                    else {
                        buf.append("<span><a>");
                    }
                }
                else if ( !tag.getAttribute("passage") ) { // we're starting a scripRef like "<scripRef>John 3:16</scripRef>"
                    myUserData->inscriptRef = false;

                    // let's stop text from going to output, the text get's added in the -tag handler
                    myUserData->suspendTextPassThru = true;
                }
            }
        }
        else if (tag.getName() && !sword::stricmp(tag.getName(), "div")) {
            if (tag.isEndTag()) {
                buf.append("</div>");
            }
            else if ( tag.getAttribute("class") && !sword::stricmp(tag.getAttribute("class"), "sechead") ) {
                buf.append("<div class=\"sectiontitle\">");
            }
            else if (tag.getAttribute("class") && !sword::stricmp(tag.getAttribute("class"), "title")) {
                buf.append("<div class=\"booktitle\">");
            }
        }
        else if (tag.getName() && !sword::stricmp(tag.getName(), "img") && tag.getAttribute("src")) {
            const char* value = tag.getAttribute("src");

            if (value[0] == '/') {
                value++; //strip the first /
            }

            buf.append("<img src=\"");
            QString absPath(QTextCodec::codecForLocale()->toUnicode(myUserData->module->getConfigEntry("AbsoluteDataPath")));
            QString relPath(QString::fromUtf8(value));
            QString url(QUrl::fromLocalFile(absPath.append('/').append(relPath)).toString());
            buf.append(url.toUtf8().data());
            buf.append("\" />");
        }
        else { // let unknown token pass thru
            return sword::ThMLHTML::handleToken(buf, token, userData);
        }
    }

    return true;
}
示例#21
0
status_t handle_request( RequestPB *pb )
{
	HTTPResponse	response;
	pb->closeConnection = false;
	
	const char		*sPtr; // General purpose string pointer
	// Temporary buffers
	int32			fieldSize = 1024;
	char			fieldValue[1024];
	char			headBuffer[1024];
	int32 			contentLength = 0;
	
	// ****
	// Get PATH_INFO and SCRIPT_NAME from path; Setup absPath of CGI
	// ****
	char PATH_INFO[1024];
	char SCRIPT_NAME[256];
	
	// Get SCRIPT_NAME
	strxcpy( SCRIPT_NAME, pb->resourcePath->Path(), 255 );
	
	strxcpy( PATH_INFO, pb->brURI->path+strlen( pb->resourcePath->Path()+1 ), 1023 );
	
	
	// Make absolute CGI path from web-directory and requested path
	BPath		absPath( pb->webDirectory->Path(), pb->resourcePath->Path()+1 );
	
	// ****
	// Make sure CGI exists and Check Permission
	// ****
	
	if( pb->authenticate &&	!pb->realms->Authenticate( pb->request, &response, pb->brURI->path, absPath.Path(), S_IXOTH ) )
	{
		pb->Logprintf( "%ld Status-Line: %s\n", pb->sn, response.GetStatusLine() );
		return B_OK;
	}
	
	// ****
	// Setup meta-variables in new environment
	// ****
	char		params[2048];
	
	// Should we use the CGI script command line?
	// This should be done on a GET or HEAD where the URL query string
	// 		does not contain any unencoded '=' characters.
	if( *pb->brURI->query && 
		((pb->request->GetMethod() == METHOD_GET)||(pb->request->GetMethod() == METHOD_HEAD))&&
		!strchr( pb->brURI->query, '=' ) )
	{
		uri_unescape_str( params, pb->brURI->query, 2048 );
	}
	else
		uri_unescape_str( params, pb->brURI->params, 2048 );
	
	// Environment to be used by the CGI
	Environment 	env( pb->environ );
	
	// AUTH_TYPE
	if( pb->request->FindHeader( kHEAD_AUTHORIZATION, fieldValue, fieldSize ) )
	{
		sPtr = fieldValue;
		sPtr = get_next_token( headBuffer, sPtr, fieldSize );
		env.PutEnv( "AUTH_TYPE", headBuffer );
		if( strcasecmp( headBuffer, "Basic" ) == 0 )
		{
			// REMOTE_USER
			sPtr = get_next_token( headBuffer, sPtr, fieldSize );
			decode_base64( headBuffer, headBuffer, fieldSize );
			sPtr = get_next_token( fieldValue, headBuffer, fieldSize, ":" );
			env.PutEnv( "REMOTE_USER", fieldValue );
		}
	}
	
	// CONTENT_LENGTH
	if( pb->request->FindHeader( kHEAD_LENGTH, fieldValue, fieldSize ) )
		env.PutEnv( "CONTENT_LENGTH", fieldValue );
	
	// CONTENT_TYPE
	if( pb->request->FindHeader( kHEAD_TYPE, fieldValue, fieldSize ) )
		env.PutEnv( "CONTENT_TYPE", fieldValue );
	
	// GATEWAY_INTERFACE
	env.PutEnv( "GATEWAY_INTERFACE", "CGI/1.1" );
	// HTTP_*
	for( int i=0; (sPtr = pb->request->HeaderAt( i )); i++ )
	{
		sPtr = get_next_token( fieldValue, sPtr, fieldSize, ":" );
		sprintf( headBuffer, "HTTP_%s", http_to_cgi_header( fieldValue ) );
		sPtr = get_next_token( fieldValue, sPtr, fieldSize, ":" );
		env.PutEnv( headBuffer, fieldValue );
	}
	
	// PATH_INFO
	env.PutEnv( "PATH_INFO", PATH_INFO );
	
	// PATH_TRANSLATED
	if( *PATH_INFO )
	{
		BPath		pathTrans( pb->webDirectory->Path(), PATH_INFO+1 );
		
		if( pathTrans.Path() )
			env.PutEnv( "PATH_TRANSLATED", pathTrans.Path() );
	}
	
	// QUERY_STRING
	env.PutEnv( "QUERY_STRING", pb->brURI->query );
	
	// REMOTE_ADDR
	env.PutEnv( "REMOTE_ADDR", pb->request->GetRemoteHost() );
	
	// REMOTE_HOST
	// Ya, right... like were going to waste valuable time with a DNS lookup!
	env.PutEnv( "REMOTE_HOST", "" );
	
	// REMOTE_IDENT
	// Ha! Perform an Ident lookup... I don't think so.
	
	// REQUEST_METHOD
	env.PutEnv( "REQUEST_METHOD", http_find_method( pb->request->GetMethod() ) );
	
	// SCRIPT_NAME
	env.PutEnv( "SCRIPT_NAME", SCRIPT_NAME );
	
	// SERVER_NAME
	env.PutEnv( "SERVER_NAME", pb->brURI->host );
	
	// SERVER_PORT
	sprintf( fieldValue, "%u", pb->request->GetPort() );
	env.PutEnv( "SERVER_PORT", fieldValue );
	
	// SERVER_PROTOCOL
	env.PutEnv( "SERVER_PROTOCOL", pb->request->GetVersion() );
	
	// SERVER_SOFTWARE
	env.PutEnv( "SERVER_SOFTWARE", "RobinHood" );
	
	// PWD
	BPath		PWD( absPath );
	PWD.GetParent( &PWD );
	env.PutEnv( "PWD", PWD.Path() );
	
	// ****
	// Create pipes
	// ****
	
	pid_t	pid;
	int 	ipipe[2], opipe[2];
	
	if( pipe(ipipe) < 0 )
	{
		response.SetHTMLMessage( 500, "Pipe creation failed!" );
		pb->request->SendReply( &response );
		return B_OK;
	}
	if( pipe(opipe) < 0 ) 
	{
		close( ipipe[0] );
		close( ipipe[1] );
		response.SetHTMLMessage( 500, "Pipe creation failed!" );
		pb->request->SendReply( &response );
		return B_OK;
	}
	
	// ****
	// Setup args for execve()
	// ****
	
	// Setup command string; copy CGI path and append params
	char command[4096];
	sPtr = strxcpy( command, absPath.Path(), 4095 );
	
	// Disabled because of security risk
	/*
	if( *params && !strpbrk( params, ";&" ) )
	{
		sPtr = strxcpy( (char *)sPtr, " ", command+4095-sPtr );
		strxcpy( (char *)sPtr, params, command+4095-sPtr ); // Append params
	}*/
	
	char *args[4];
	args[0] = "/bin/sh";
	args[1] = "-c";
	args[2] = command;
	args[3] = NULL;
	
	pb->Logprintf( "%ld Exec: %s\n", pb->sn, command );
	
	// ****
	// Start sub-process using fork() dup2() and exec()
	// ****
	
	pid = fork();
	if( pid == (pid_t)0 ) // If we are the child process...
	{
		// Make this process the process group leader
		setpgid( 0, 0 );
		fflush(stdout); // sync stdout... 
		
		// Set pipes to stdin and stdout
		if( dup2( opipe[0], STDIN_FILENO ) < 0 )
			exit( 0 );
		if( dup2( ipipe[1], STDOUT_FILENO ) < 0 )
			exit( 0 );
		// Close unused ends of pipes
		close( opipe[1] );
		close( ipipe[0] );
		
		// Set Current Working Directory to that of script
		chdir( PWD.Path() );
		
		// Execute CGI in this process by means of /bin/sh 
		execve( args[0], args, env.GetEnvironment() );
		exit( 0 ); // If for some reason execve() fails...
	}
	else if( pid < (pid_t)0 ) // Something Bad happened!
	{
		close( opipe[0] );
		close( opipe[1] );
		close( ipipe[0] );
		close( ipipe[1] );
		response.SetHTMLMessage( 500, "Fork failed!" );
		pb->request->SendReply( &response );
		return true;
	}
	// Close unused ends of pipes
	close( opipe[0] );
	close( ipipe[1] );
	
	// ****
	// Talk to CGI
	// ****
	
	bool		persistant = true;
	
	// Defined to make code easier to read
	int			inDes = ipipe[0]; // input file descripter
	int			outDes = opipe[1]; // output file descripter
	
	// Make a BDataIO wrapper for the in and out pipes
	DesIO		pipeIO( inDes, outDes );
	
	// If the request contains a content body, feed it into stdin of the CGI script
	if( pb->request->GetContentLength() > 0 )
		pb->request->SendBody( &pipeIO );
	
	// Buffer the response body for better performance
	response.SetBodyBuffering( true );
	
	// Read first line to detect use of Non-Parsed Header Output
	io_getline( &pipeIO, headBuffer, fieldSize );
	
	// Strip the '\r' character if there is one
	int32	size;
	size = strlen( headBuffer )-1;
	if( headBuffer[size] == '\r' )
		headBuffer[size] = 0;
	
	// Is NPH Output?
	if( strncmp( "HTTP/", headBuffer, 5 ) == 0 )
	{
		DataIOPump		ioPump;
		BufferedIO		bufio( pb->request->GetReplyIO() );
		bufio.DoAllocate();
		
		io_printf( &bufio, "%s\r\n", headBuffer );
		ioPump.StartPump( &pipeIO, &bufio, contentLength );
		bufio.Flush();
		persistant = false;
	}
	else // using Parsed Header Output
	{
		// Add Date header
		time_t			now;
		struct tm 		*brokentime;
		
		now = time( NULL );
		brTimeLock.Lock();
		brokentime = gmtime( &now );
		strftime (fieldValue, 256, kHTTP_DATE, brokentime);
		brTimeLock.Unlock();
		
		response.AddHeader( kHEAD_DATE, fieldValue );
		
		// Add line used to detect NPH as CGI header
		response.AddHeader( headBuffer );
		
		// Receive the CGI headers
		response.ReceiveHeaders( &pipeIO );
			
		// If Location header, don't expect any more headers
		if( (sPtr = response.FindHeader( "Location", fieldValue, fieldSize )) )
		{
			response.SetStatusLine( 302 ); // 302 Moved Temporarily
		}
		else
		{
			if( (sPtr = response.FindHeader( "Status", fieldValue, fieldSize )) )
			{
				response.RemoveHeader( (char *)sPtr ); // Don't forward to client
				response.SetStatusLine( fieldValue );
			}
			else
				response.SetStatusLine( 200 );
		}
		
		// Don't cache the response
		if( !response.FindHeader( "Cache-Control", fieldValue, fieldSize ) )
			response.AddHeader( "Cache-Control: no-cache" );
		if( !response.FindHeader( "Pragma", fieldValue, fieldSize ) )
			response.AddHeader( "Pragma: no-cache" );
		
		// Content-Length header?
		int32		contentLength = 0;
		
		if( (sPtr = response.FindHeader( kHEAD_LENGTH, fieldValue, fieldSize )) )
		{
			contentLength = strtol( fieldValue, (char **)&headBuffer, 10 );
			response.SetContentLength( contentLength );
		}
		else // No content-length provided; close connection on return
		{
			response.AddHeader( "Connection: close" );
			persistant = false;
		}
		
		pb->Logprintf( "%ld Status-Line: %s\n", pb->sn, response.GetStatusLine() );
		if( pb->request->GetMethod() != METHOD_HEAD )
			response.SetMessageBody( &pipeIO );
		pb->request->SendReply( &response );
	}
	
	// Close remaining ends of pipes
	close( ipipe[0] );
	close( opipe[1] );
	pb->closeConnection = !persistant;
	return B_OK;
}
示例#22
0
    RenderableGalaxy::RenderableGalaxy(const ghoul::Dictionary& dictionary)
    : Renderable(dictionary)
    , _stepSize("stepSize", "Step Size", 0.012, 0.0005, 0.05)
    , _pointStepSize("pointStepSize", "Point Step Size", 0.01, 0.01, 0.1)
    , _translation("translation", "Translation", glm::vec3(0.0, 0.0, 0.0), glm::vec3(0.0), glm::vec3(10.0))
    , _rotation("rotation", "Euler rotation", glm::vec3(0.0, 0.0, 0.0), glm::vec3(0), glm::vec3(6.28))
    , _enabledPointsRatio("nEnabledPointsRatio", "Enabled points", 0.2, 0, 1) {

    float stepSize;
    glm::vec3 scaling, translation, rotation;
    glm::vec4 color;
    ghoul::Dictionary volumeDictionary, pointsDictionary;

    if (dictionary.getValue("Translation", translation)) {
        _translation = translation;
    }
    if (dictionary.getValue("Rotation", rotation)) {
        _rotation = rotation;
    }
    if (dictionary.getValue("StepSize", stepSize)) {
        _stepSize = stepSize;
    }
    if (dictionary.getValue("Volume", volumeDictionary)) {
        std::string volumeFilename;
        if (volumeDictionary.getValue("Filename", volumeFilename)) {
            _volumeFilename = absPath(volumeFilename);
        } else {
            LERROR("No volume filename specified.");
        }
        glm::vec3 volumeDimensions;
        if (volumeDictionary.getValue("Dimensions", volumeDimensions)) {
            _volumeDimensions = static_cast<glm::ivec3>(volumeDimensions);
        } else {
            LERROR("No volume dimensions specified.");
        }
        glm::vec3 volumeSize;
        if (volumeDictionary.getValue("Size", volumeSize)) {
            _volumeSize = static_cast<glm::vec3>(volumeSize);
        }
        else {
            LERROR("No volume dimensions specified.");
        }

    } else {
        LERROR("No volume dictionary specified.");
    }
    if (dictionary.getValue("Points", pointsDictionary)) {
        std::string pointsFilename;
        if (pointsDictionary.getValue("Filename", pointsFilename)) {
            _pointsFilename = absPath(pointsFilename);
        } else {
            LERROR("No points filename specified.");
        }
        glm::vec3 pointsScaling;
        if (pointsDictionary.getValue("Scaling", pointsScaling)) {
            _pointScaling = static_cast<glm::vec3>(pointsScaling);
        }
        else {
            LERROR("No volume dimensions specified.");
        }
    } else {
        LERROR("No points dictionary specified.");
    }

}
示例#23
0
 std::unique_ptr<ghoul::opengl::Texture> ScreenSpaceImage::loadFromDisk() {
    if (_texturePath.value() != "")
        return (ghoul::io::TextureReader::ref().loadTexture(absPath(_texturePath.value())));
    return nullptr;
 }
示例#24
0
void Shell::ocp(size_t argc, const std::string* argv)
{
	class _FDGuard
	{
		SessionClient* session;
	public:
		_FDGuard(SessionClient* _ss) : session(_ss) {}
		void operator () (int fd) { session->closeFile(fd); }
	};

	class _OFDGuard
	{
	public:
		void operator () (FILE* fd) { fclose(fd); }
	};
	if(argc < 2)
	{
		printError(ERR_ARGS_INVALID);
		return;
	}

	FILE* ofd = fopen(argv[0].c_str(), "r");
	if(ofd == nullptr)
	{
		printError(ERR_OFILE_OPEN_FAIL);
		return;
	}
	Guard<FILE*, _OFDGuard> ogd(ofd, _OFDGuard());
	std::string abspth, parent, name;
	abspth = absPath(argv[1]);
	parent = parentPath(abspth);
	if(parent == "/")
		name = abspth.substr(1, abspth.size() - 1);
	else
		name = abspth.substr(parent.size() + 1, abspth.size() - (parent.size() + 1));
	if(parent == "" || name == "")
	{
		printError(ERR_ARGS_INVALID);
		return;
	}
	if(!session->createFile(parent.c_str(), name.c_str()))
	{
		printError(session->getErrno());
		return;
	}
	int fd = session->openFile(absPath(argv[1]).c_str(), OPTYPE_WRITE);
	if(fd <= 0)
	{
		printError(session->getErrno());
		return;
	}
	Guard<int, _FDGuard> gd(fd, _FDGuard(session));
	size_t start = 0;
	const size_t BUFSIZE = 64;
	std::unique_ptr<char> buf(new char[BUFSIZE]);
	while(true)
	{
		int len = fread(buf.get(), sizeof(char), BUFSIZE, ofd);
		if(len < 0)
		{
			printError(ERR_OFILE_READ_FAIL);
			return;
		}
		else if(len == 0)
			break;
		else
		{
			start += len;
			int has = 0;
			while(has != len)
			{
				int cl = session->writeFile(fd, buf.get() + has, len - has);
				if(cl < 0)
				{
					printError(session->getErrno());
					return;
				}
				if(cl == 0)
				{
					printError(ERR_UNKNOW);
					return;
				}
				has += cl;
			}
		}
	}
}
示例#25
0
std::string Shell::evrPath(std::string path)
{
	return absPath("/evr/" + path);
}
示例#26
0
static void handleclient(u64 conn_s_p)
{
	// todo: clean up
	
	int conn_s = (int)conn_s_p;
	int list_s_data = -1;
	int conn_s_data = -1;
	int datareq = 0;
	
	char		cwd[256];
	char		rnfr[256];
	char		filename[256];
	char		user[32];
	u32		rest = 0;
	int		authd = 0;
	int		active = 1;
	Lv2FsFile	tempfd;
	char		buf[BUFFER_SIZE];

	char	buffer[1024];
	char	client_cmd[8][128];
	ssize_t	bytes;
	
	#if LOGIN_CHECK == 1
	// load password file
	char passwordcheck[33];
						
	// check if password file exists - if not, use default password
	if(exists(PASSWORD_FPATH) == 0)
	{
		Lv2FsFile fd;
		u64 read;
		
		lv2FsOpen(PASSWORD_FPATH, LV2_O_RDONLY, &fd, 0, NULL, 0);
		lv2FsRead(fd, passwordcheck, 32, &read);
		lv2FsClose(fd);
		
		if(strlen(passwordcheck) != 32)
		{
			strcpy(passwordcheck, LOGIN_PASSWORD);
		}
	}
	else
	{
		strcpy(passwordcheck, LOGIN_PASSWORD);
	}
	#endif
	
	// start directory
	strcpy(cwd, "/");
	
	// welcome message
	swritel(conn_s, "220-OpenPS3FTP by @jjolano\r\n");
	sprintf(buffer, "220 Version %s\r\n", VERSION);
	swritel(conn_s, buffer);
	
	while(exitapp == 0 && active && (bytes = sreadl(conn_s, buffer, 1024)) > 0)
	{
		// get rid of the newline at the end of the string
		buffer[strcspn(buffer, "\n")] = '\0';
		buffer[strcspn(buffer, "\r")] = '\0';
		
		// parse received string into array
		int parameter_count = 0;
		
		char *result = strtok(buffer, " ");
		
		strcpy(client_cmd[0], result);
		
		while(parameter_count < 7 && (result = strtok(NULL, " ")) != NULL)
		{
			parameter_count++;
			strcpy(client_cmd[parameter_count], result);
		}
		
		// identify the command
		int cmd_id;
		for(cmd_id = 0; cmd_id < client_cmds_count; cmd_id++)
		{
			if(strcasecmp(client_cmd[0], client_cmds[cmd_id]) == 0)
			{
				break;
			}
		}
		
		// execute command
		if(authd == 0)
		{
			// not logged in
			
			switch(cmd_id)
			{
				case 0: // USER
					#if LOGIN_CHECK == 1
					if(parameter_count >= 1)
					{
						int i;
						for(i = 2; i <= parameter_count; i++)
						{
							strcat(client_cmd[1], " ");
							strcat(client_cmd[1], client_cmd[i]);
						}
						
						strcpy(user, client_cmd[1]);
						sprintf(buffer, "331 User %s OK. Password required\r\n", user);
						swritel(conn_s, buffer);
					}
					else
					{
						swritel(conn_s, "501 Please provide a username\r\n");
					}
					#else
					sprintf(buffer, "331 User %s OK. Password (not really) required\r\n", user);
					swritel(conn_s, buffer);
					#endif
					break;
				case 1: // PASS
					#if LOGIN_CHECK == 1
					if(parameter_count >= 1)
					{
						int i;
						for(i = 2; i <= parameter_count; i++)
						{
							strcat(client_cmd[1], " ");
							strcat(client_cmd[1], client_cmd[i]);
						}
						
						// hash the password given
						char output[33];
						md5(output, client_cmd[1]);
					
						if(strcmp(user, LOGIN_USERNAME) == 0 && strcmp(output, passwordcheck) == 0)
						{
							swritel(conn_s, "230 Successful authentication\r\n");
							authd = 1;
						}
						else
						{
							swritel(conn_s, "430 Invalid username or password - \r\n");
						}
					}
					else
					{
						swritel(conn_s, "501 Invalid username or password\r\n");
					}
					#else
					swritel(conn_s, "230 Successful authentication\r\n");
					authd = 1;
					#endif
					break;
				case 2: // QUIT
					swritel(conn_s, "221 See you later\r\n");
					active = 0;
					break;
				default: swritel(conn_s, "530 You are not logged in\r\n");
			}
		}
		else
		{
			// logged in
			
			switch(cmd_id)
			{
				case 0: // USER
				case 1: // PASS
					swritel(conn_s, "530 You are already logged in\r\n");
					break;
				case 2: // QUIT
					swritel(conn_s, "221 See you later\r\n");
					active = 0;
					break;
				case 3: // PASV
					rest = 0;
				
					netSocketInfo snf;
				
					int ret = netGetSockInfo(conn_s, &snf, 1);
				
					if(ret >= 0 && snf.local_adr.s_addr != 0)
					{
						// assign a random port for passive mode
						srand(conn_s);
						
						int rand1 = (rand() % 251) + 4;
						int rand2 = rand() % 256;
						
						sprintf(buffer, "227 Entering Passive Mode (%u,%u,%u,%u,%i,%i)\r\n",
							(snf.local_adr.s_addr & 0xFF000000) >> 24,
							(snf.local_adr.s_addr & 0xFF0000) >> 16,
							(snf.local_adr.s_addr & 0xFF00) >> 8,
							(snf.local_adr.s_addr & 0xFF),
							rand1, rand2);
						
						short int pasvport = (rand1 * 256) + rand2;
						
						struct sockaddr_in servaddr;
						memset(&servaddr, 0, sizeof(servaddr));
						servaddr.sin_family      = AF_INET;
						servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
						servaddr.sin_port        = htons(pasvport);
						
						list_s_data = netSocket(AF_INET, SOCK_STREAM, 0);
						netBind(list_s_data, (struct sockaddr *) &servaddr, sizeof(servaddr));
						netListen(list_s_data, 1);
						
						swritel(conn_s, buffer);
						
						if((conn_s_data = netAccept(list_s_data, NULL, NULL)) == -1)
						{
							swritel(conn_s, "550 PASV command failed\r\n");
						}
						else
						{
							datareq = 1;
						}
						break;
					}
		
					swritel(conn_s, "550 PASV command failed\r\n");
					break;
				case 4: // PORT
					if(parameter_count == 1)
					{
						rest = 0;
						
						char connectinfo[32];
						strcpy(connectinfo, client_cmd[1]);
						
						char data[7][4];
						int i = 0;
						
						char *result = strtok(connectinfo, ",");
	
						strcpy(data[0], result);
	
						while(i < 6 && (result = strtok(NULL, ",")) != NULL)
						{
							i++;
							strcpy(data[i], result);
						}
					
						char conn_ipaddr[16];
						sprintf(conn_ipaddr, "%s.%s.%s.%s", data[0], data[1], data[2], data[3]);
						
						struct sockaddr_in servaddr;
						memset(&servaddr, 0, sizeof(servaddr));
						servaddr.sin_family	= AF_INET;
						servaddr.sin_port	= htons((atoi(data[4]) * 256) + atoi(data[5]));
						inet_pton(AF_INET, conn_ipaddr, &servaddr.sin_addr);
						
						conn_s_data = netSocket(AF_INET, SOCK_STREAM, 0);
					
						if(connect(conn_s_data, (struct sockaddr *)&servaddr, sizeof(servaddr)) == 0)
						{
							swritel(conn_s, "200 PORT command successful\r\n");
							datareq = 1;
						}
						else
						{
							swritel(conn_s, "550 PORT command failed\r\n");
						}
					}
					else
					{
						swritel(conn_s, "501 Syntax error\r\n");
					}
					break;
				case 5: // SITE
					if(strcasecmp(client_cmd[1], "CHMOD") == 0)
					{
						int i;
						for(i = 4; i <= parameter_count; i++)
						{
							strcat(client_cmd[3], " ");
							strcat(client_cmd[3], client_cmd[i]);
						}
						
						absPath(filename, client_cmd[3], cwd);
					
						char perms[4];
						sprintf(perms, "0%s", client_cmd[2]);
						
						if(lv2FsChmod(filename, S_IFMT | strtol(perms, NULL, 8)) == 0)
						{
							swritel(conn_s, "250 File permissions successfully set\r\n");
						}
						else
						{
							swritel(conn_s, "550 Failed to set file permissions\r\n");
						}
					}
					else
					{
						swritel(conn_s, "500 Unrecognized SITE command\r\n");
					}
					break;
				case 6: // FEAT
					swritel(conn_s, "211- Extensions supported:\r\n");
				
					int i;
					for(i = 0; i < feat_cmds_count; i++)
					{
						sprintf(buffer, " %s\r\n", feat_cmds[i]);
						swritel(conn_s, buffer);
					}
				
					swritel(conn_s, "211 End.\r\n");
					break;
				case 7: // TYPE
					swritel(conn_s, "200 TYPE command successful\r\n");
					break;
				case 8: // REST
					if(parameter_count == 1)
					{
						rest = atoi(client_cmd[1]);
						swritel(conn_s, "350 REST command successful\r\n");
					}
					else
					{
						swritel(conn_s, "501 Syntax error\r\n");
					}
					break;
				case 9: // RETR
					if(parameter_count >= 1)
					{
						if(conn_s_data == -1)
						{
							swritel(conn_s, "425 No data connection\r\n");
							break;
						}
					
						swritel(conn_s, "150 Opening data connection\r\n");

						int i;
						for(i = 2; i <= parameter_count; i++)
						{
							strcat(client_cmd[1], " ");
							strcat(client_cmd[1], client_cmd[i]);
						}
						
						absPath(filename, client_cmd[1], cwd);
						
						u64 pos;
						u64 read = -1;
					
						Lv2FsFile fd;
					
						lv2FsOpen(filename, LV2_O_RDONLY, &fd, 0, NULL, 0);
						lv2FsLSeek64(fd, (s64)rest, SEEK_SET, &pos);
					
						if(fd >= 0)
						{
							while(lv2FsRead(fd, buf, BUFFER_SIZE - 1, &read) == 0 && read > 0)
							{
								netSend(conn_s_data, buf, read, 0);
							}
						
							if(read == 0)
							{
								swritel(conn_s, "226 Transfer complete\r\n");
							}
							else
							{
								swritel(conn_s, "426 Transfer failed\r\n");
							}
						}
						else
						{
							swritel(conn_s, "452 File access error\r\n");
						}
						
						lv2FsClose(fd);
					}
					else
					{
						swritel(conn_s, "501 Syntax error\r\n");
					}
					break;
				case 10: // PWD
					sprintf(buffer, "257 \"%s\" is the current directory\r\n", cwd);
					swritel(conn_s, buffer);
					break;
				case 11: // CWD
					if(parameter_count >= 1)
					{
						int i;
						for(i = 2; i <= parameter_count; i++)
						{
							strcat(client_cmd[1], " ");
							strcat(client_cmd[1], client_cmd[i]);
						}
						
						strcpy(filename, client_cmd[1]);
						
						if(strcmp(filename, "../") == 0)
						{
							for(int i = strlen(cwd) - 2; i > 0; i--)
							{
								if(cwd[i] != '/')
								{
									cwd[i] = '\0';
								}
								else
								{
									break;
								}
							}
							
							sprintf(buffer, "250 Directory change successful: %s\r\n", cwd);
							swritel(conn_s, buffer);
							break;
						}
					
						if(filename[0] == '/')
						{
							strcpy(cwd, (strlen(filename) == 1) ? "/" : filename);
						}
						else
						{
							strcat(cwd, filename);
						}
					
						if(cwd[strlen(cwd) - 1] != '/')
						{
							strcat(cwd, "/");
						}
					
						if(isDir(cwd))
						{
							sprintf(buffer, "250 Directory change successful: %s\r\n", cwd);
						}
						else
						{
							sprintf(buffer, "550 Could not change directory: %s\r\n", cwd);
						}
					
						swritel(conn_s, buffer);
					}
					else
					{
						sprintf(buffer, "257 \"%s\" is the current directory\r\n", cwd);
						swritel(conn_s, buffer);
					}
					break;
				case 12: // CDUP
					for(int i = strlen(cwd) - 2; i > 0; i--)
					{
						if(cwd[i] != '/')
						{
							cwd[i] = '\0';
						}
						else
						{
							break;
						}
					}
				
					sprintf(buffer, "250 Directory change successful: %s\r\n", cwd);
					swritel(conn_s, buffer);
					break;
				case 13: // NLST
					if(conn_s_data == -1)
					{
						swritel(conn_s, "425 No data connection\r\n");
						break;
					}
				
					swritel(conn_s, "150 Opening data connection\r\n");
				
					if(parameter_count >= 1)
					{
						int i;
						for(i = 2; i <= parameter_count; i++)
						{
							strcat(client_cmd[1], " ");
							strcat(client_cmd[1], client_cmd[i]);
						}
						
						absPath(filename, client_cmd[1], cwd);
					}
					else
					{
						strcpy(filename, cwd);
					}
				
					if(lv2FsOpenDir(filename, &tempfd) == 0)
					{
						u64 read;
						Lv2FsDirent ent;
					
						while(lv2FsReadDir(tempfd, &ent, &read) == 0 && read != 0)
						{
							sprintf(buffer, "%s\r\n", ent.d_name);
							swritel(conn_s_data, buffer);
						}
						
						swritel(conn_s, "226 Transfer complete\r\n");
					}
					else
					{
						swritel(conn_s, "451 Cannot access directory\r\n");
					}
				
					lv2FsCloseDir(tempfd);
					break;
				case 14: // LIST
					if(conn_s_data == -1)
					{
						swritel(conn_s, "425 No data connection\r\n");
						break;
					}
				
					swritel(conn_s, "150 Opening data connection\r\n");
				
					if(parameter_count >= 1)
					{
						int i;
						for(i = 2; i <= parameter_count; i++)
						{
							strcat(client_cmd[1], " ");
							strcat(client_cmd[1], client_cmd[i]);
						}
						
						absPath(filename, client_cmd[1], cwd);
					}
					else
					{
						strcpy(filename, cwd);
					}
				
					if(lv2FsOpenDir(filename, &tempfd) == 0)
					{
						u64 read;
						Lv2FsDirent ent;
						
						while(lv2FsReadDir(tempfd, &ent, &read) == 0 && read != 0)
						{
							sprintf(filename, "%s%s", cwd, ent.d_name);
							
							Lv2FsStat entry;
							lv2FsStat(filename, &entry);
						
							struct tm *tm;
							char timebuf[32];
							tm = localtime(&entry.st_mtime);
							strftime(timebuf, 31, "%b %d %Y", tm);
						
							sprintf(buffer, "%s%s%s%s%s%s%s%s%s%s 1 root root %lu %s %s\r\n", 
								((entry.st_mode & S_IFDIR) != 0)?"d":"-", 
								((entry.st_mode & S_IRUSR) != 0)?"r":"-",
								((entry.st_mode & S_IWUSR) != 0)?"w":"-",
								((entry.st_mode & S_IXUSR) != 0)?"x":"-",
								((entry.st_mode & S_IRGRP) != 0)?"r":"-",
								((entry.st_mode & S_IWGRP) != 0)?"w":"-",
								((entry.st_mode & S_IXGRP) != 0)?"x":"-",
								((entry.st_mode & S_IROTH) != 0)?"r":"-",
								((entry.st_mode & S_IWOTH) != 0)?"w":"-",
								((entry.st_mode & S_IXOTH) != 0)?"x":"-",
								(long unsigned int)entry.st_size, 
								timebuf, 
								ent.d_name);

							swritel(conn_s_data, buffer);
						}
						
						swritel(conn_s, "226 Transfer complete\r\n");
					}
					else
					{
						swritel(conn_s, "451 Cannot access directory\r\n");
					}
				
					lv2FsCloseDir(tempfd);
					break;
				case 15: // STOR
					if(parameter_count >= 1)
					{
						if(conn_s_data == -1)
						{
							swritel(conn_s, "425 No data connection\r\n");
							break;
						}
						
						swritel(conn_s, "150 Opening data connection\r\n");

						int i;
						for(i = 2; i <= parameter_count; i++)
						{
							strcat(client_cmd[1], " ");
							strcat(client_cmd[1], client_cmd[i]);
						}
						
						absPath(filename, client_cmd[1], cwd);
						
						u64 pos;
						u64 read = -1;
						u64 write = -1;
						
						Lv2FsFile fd;
					
						lv2FsOpen(filename, LV2_O_WRONLY | LV2_O_CREAT, &fd, 0, NULL, 0);
						lv2FsChmod(filename, S_IFMT | 0666);
					
						lv2FsLSeek64(fd, (s32)rest, SEEK_SET, &pos);
						
						if(fd >= 0)
						{
							while((read = (u64)netRecv(conn_s_data, buf, BUFFER_SIZE - 1, MSG_WAITALL)) > 0)
							{
								lv2FsWrite(fd, buf, read, &write);
							
								if(write != read)
								{
									break;
								}
							}
							
							if(read == 0)
							{
								swritel(conn_s, "226 Transfer complete\r\n");
							}
							else
							{
								swritel(conn_s, "426 Transfer failed\r\n");
							}
						}
						else
						{
							swritel(conn_s, "452 File access error\r\n");
						}
						
						lv2FsClose(fd);
					}
					else
					{
						swritel(conn_s, "501 Syntax error\r\n");
					}
					break;
				case 16: // NOOP
					swritel(conn_s, "200 Zzzz...\r\n");
					break;
				case 17: // DELE
					if(parameter_count >= 1)
					{
						int i;
						for(i = 2; i <= parameter_count; i++)
						{
							strcat(client_cmd[1], " ");
							strcat(client_cmd[1], client_cmd[i]);
						}
						
						absPath(filename, client_cmd[1], cwd);
						
						if(lv2FsUnlink(filename) == 0)
						{
							swritel(conn_s, "250 File successfully deleted\r\n");
						}
						else
						{
							swritel(conn_s, "550 Failed to delete file\r\n");
						}
					}
					else
					{
						swritel(conn_s, "501 Syntax error\r\n");
					}
					break;
				case 18: // MKD
					if(parameter_count >= 1)
					{
						int i;
						for(i = 2; i <= parameter_count; i++)
						{
							strcat(client_cmd[1], " ");
							strcat(client_cmd[1], client_cmd[i]);
						}
						
						absPath(filename, client_cmd[1], cwd);
					
						if(lv2FsMkdir(filename, 0775) == 0)
						{
							swritel(conn_s, "250 Directory successfully created\r\n");
						}
						else
						{
							swritel(conn_s, "550 Failed to create directory\r\n");
						}
					}
					else
					{
						swritel(conn_s, "501 Syntax error\r\n");
					}
					break;
				case 19: // RMD
					if(parameter_count >= 1)
					{
						int i;
						for(i = 2; i <= parameter_count; i++)
						{
							strcat(client_cmd[1], " ");
							strcat(client_cmd[1], client_cmd[i]);
						}
						
						absPath(filename, client_cmd[1], cwd);
					
						if(lv2FsRmdir(filename) == 0)
						{
							swritel(conn_s, "250 Directory successfully deleted\r\n");
						}
						else
						{
							swritel(conn_s, "550 Failed to remove directory\r\n");
						}
					}
					else
					{
						swritel(conn_s, "501 Syntax error\r\n");
					}
					break;
				case 20: // RNFR
					if(parameter_count >= 1)
					{
						int i;
						for(i = 2; i <= parameter_count; i++)
						{
							strcat(client_cmd[1], " ");
							strcat(client_cmd[1], client_cmd[i]);
						}
						
						absPath(rnfr, client_cmd[1], cwd);
					
						if(exists(rnfr) == 0)
						{
							swritel(conn_s, "350 RNFR successful - ready for destination\r\n");
						}
						else
						{
							swritel(conn_s, "550 RNFR failed - file does not exist\r\n");
						}
					}
					else
					{
						swritel(conn_s, "501 Syntax error\r\n");
					}
					break;
				case 21: // RNTO
					if(parameter_count >= 1)
					{
						int i;
						for(i = 2; i <= parameter_count; i++)
						{
							strcat(client_cmd[1], " ");
							strcat(client_cmd[1], client_cmd[i]);
						}
						
						absPath(filename, client_cmd[1], cwd);
					
						if(lv2FsRename(rnfr, filename) == 0)
						{
							swritel(conn_s, "250 File successfully renamed\r\n");
						}
						else
						{
							swritel(conn_s, "550 Failed to rename file\r\n");
						}
					}
					else
					{
						swritel(conn_s, "501 Syntax error\r\n");
					}
					break;
				case 22: // SIZE
					if(parameter_count >= 1)
					{
						int i;
						for(i = 2; i <= parameter_count; i++)
						{
							strcat(client_cmd[1], " ");
							strcat(client_cmd[1], client_cmd[i]);
						}
						
						absPath(filename, client_cmd[1], cwd);
					
						Lv2FsStat entry;
						
						if(lv2FsStat(filename, &entry) == 0)
						{
							sprintf(buffer, "213 %lu\r\n", (long unsigned int)entry.st_size);
						}
						else
						{
							sprintf(buffer, "550 Requested file doesn't exist\r\n");
						}
					
						swritel(conn_s, buffer);
					}
					else
					{
						swritel(conn_s, "501 Syntax error\r\n");
					}
					break;
				case 23: // SYST
					swritel(conn_s, "215 UNIX Type: L8\r\n");
					break;
				case 24: // HELP
					swritel(conn_s, "214 No help for you.\r\n");
					break;
				case 25: // PASSWD
					if(parameter_count >= 1)
					{
						int i;
						for(i = 2; i <= parameter_count; i++)
						{
							strcat(client_cmd[1], " ");
							strcat(client_cmd[1], client_cmd[i]);
						}
						
						// hash the password given
						char output[33];
						md5(output, client_cmd[1]);
					
						Lv2FsFile fd;
						u64 written;
					
						lv2FsOpen(PASSWORD_FPATH, LV2_O_WRONLY | LV2_O_CREAT, &fd, 0, NULL, 0);
						lv2FsWrite(fd, output, 32, &written);
						lv2FsClose(fd);
					
						swritel(conn_s, "200 Password successfully changed\r\n");
					}
					else
					{
						swritel(conn_s, "501 Invalid password\r\n");
					}
					break;
				case 26: // MLSD
					if(conn_s_data == -1)
					{
						swritel(conn_s, "425 No data connection\r\n");
						break;
					}
				
					swritel(conn_s, "150 Opening data connection\r\n");
				
					if(parameter_count >= 1)
					{
						int i;
						for(i = 2; i <= parameter_count; i++)
						{
							strcat(client_cmd[1], " ");
							strcat(client_cmd[1], client_cmd[i]);
						}
						
						absPath(filename, client_cmd[1], cwd);
					}
					else
					{
						strcpy(filename, cwd);
					}
				
					if(lv2FsOpenDir(filename, &tempfd) == 0)
					{
						u64 read;
						Lv2FsDirent ent;
					
						while(lv2FsReadDir(tempfd, &ent, &read) == 0 && read != 0)
						{
							sprintf(filename, "%s%s", cwd, ent.d_name);
							
							Lv2FsStat entry;
							lv2FsStat(filename, &entry);
						
							struct tm *tm;
							char timebuf[32];
							tm = localtime(&entry.st_mtime);
							strftime(timebuf, 31, "%Y%m%d%H%M%S", tm);
						
							int permint = 0;

							permint +=	(((entry.st_mode & S_IRUSR) != 0)?400:0) +
									(((entry.st_mode & S_IWUSR) != 0)?200:0) +
									(((entry.st_mode & S_IXUSR) != 0)?100:0);
						
							permint +=	(((entry.st_mode & S_IRGRP) != 0)?40:0) +
									(((entry.st_mode & S_IWGRP) != 0)?20:0) +
									(((entry.st_mode & S_IXGRP) != 0)?10:0);
						
							permint +=	(((entry.st_mode & S_IROTH) != 0)?4:0) +
									(((entry.st_mode & S_IWOTH) != 0)?2:0) +
									(((entry.st_mode & S_IXOTH) != 0)?1:0);
						
							sprintf(buffer, "type=%s;size=%lu;modify=%s;UNIX.mode=0%i;UNIX.uid=root;UNIX.gid=root; %s\r\n", 
								((entry.st_mode & S_IFDIR) != 0)?"dir":"file", 
								(long unsigned int)entry.st_size, 
								timebuf, 
								permint,
								ent.d_name);
						
							swritel(conn_s_data, buffer);
						}
						
						swritel(conn_s, "226 Transfer complete\r\n");
					}
					else
					{
						swritel(conn_s, "501 Directory access error\r\n");
					}

					lv2FsCloseDir(tempfd);
					break;
				case 27: // MLST
					swritel(conn_s, "250- Listing directory");
				
					if(parameter_count >= 1)
					{
						int i;
						for(i = 2; i <= parameter_count; i++)
						{
							strcat(client_cmd[1], " ");
							strcat(client_cmd[1], client_cmd[i]);
						}
						
						absPath(filename, client_cmd[1], cwd);
					}
					else
					{
						strcpy(filename, cwd);
					}
					
					if(lv2FsOpenDir(filename, &tempfd) == 0)
					{
						u64 read;
						Lv2FsDirent ent;
					
						while(lv2FsReadDir(tempfd, &ent, &read) == 0 && read != 0)
						{
							sprintf(filename, "%s%s", cwd, ent.d_name);
							
							Lv2FsStat entry;
							lv2FsStat(filename, &entry);
						
							struct tm *tm;
							char timebuf[32];
							tm = localtime(&entry.st_mtime);
							strftime(timebuf, 31, "%Y%m%d%H%M%S", tm);
						
							int permint = 0;

							permint +=	(((entry.st_mode & S_IRUSR) != 0)?400:0) +
									(((entry.st_mode & S_IWUSR) != 0)?200:0) +
									(((entry.st_mode & S_IXUSR) != 0)?100:0);
						
							permint +=	(((entry.st_mode & S_IRGRP) != 0)?40:0) +
									(((entry.st_mode & S_IWGRP) != 0)?20:0) +
									(((entry.st_mode & S_IXGRP) != 0)?10:0);
						
							permint +=	(((entry.st_mode & S_IROTH) != 0)?4:0) +
									(((entry.st_mode & S_IWOTH) != 0)?2:0) +
									(((entry.st_mode & S_IXOTH) != 0)?1:0);
						
							sprintf(buffer, " type=%s;size=%lu;modify=%s;UNIX.mode=0%i;UNIX.uid=root;UNIX.gid=root; %s\r\n", 
								((entry.st_mode & S_IFDIR) != 0)?"dir":"file", 
								(long unsigned int)entry.st_size, 
								timebuf, 
								permint,
								ent.d_name);
						
							swritel(conn_s, buffer);
						}
					}
				
					swritel(conn_s, "250 End\r\n");
				
					lv2FsCloseDir(tempfd);
					break;
				case 28: // EXITAPP
					swritel(conn_s, "221 Exiting OpenPS3FTP, bye\r\n");
					exitapp = 1;
					break;
				case 29: // TEST
					swritel(conn_s, "211-Listing parameters\r\n");
					sprintf(buffer, "211-Count: %i\r\n", parameter_count);
					swritel(conn_s, buffer);
					
					int tx;
					for(tx = 0; tx <= parameter_count; tx++)
					{
						sprintf(buffer, " %i:%s\r\n", tx, client_cmd[tx]);
						swritel(conn_s, buffer);
					}
					
					swritel(conn_s, "211 End\r\n");
					break;
				default: swritel(conn_s, "500 Unrecognized command\r\n");
			}
			
			if(datareq == 1)
			{
				datareq = 0;
			}
			else
			{
				// close any active data connections
				if(conn_s_data > -1)
				{
					netShutdown(conn_s_data, 2);
					netClose(conn_s_data);
					conn_s_data = -1;
				}
				
				if(list_s_data > -1)
				{
					netShutdown(list_s_data, 2);
					netClose(list_s_data);
					list_s_data = -1;
				}
			}
		}
	}
std::vector<RenderableFieldlines::Line>
RenderableFieldlines::generateFieldlinesVolumeKameleon()
{
    std::string model;
    bool success = _vectorFieldInfo.getValue(keyVectorFieldVolumeModel, model);
    if (!success) {
        LERROR(keyVectorField << " does not name a model");
        return {};
    }

    std::string fileName;
    success = _vectorFieldInfo.getValue(keyVectorFieldFile, fileName);
    if (!success) {
        LERROR(keyVectorField << " does not name a file");
        return {};
    }
    fileName = absPath(fileName);

    //KameleonWrapper::Model modelType;
    if (model != vectorFieldKameleonModelBATSRUS) {
        //modelType = KameleonWrapper::Model::BATSRUS;
    //else {
        LERROR(keyVectorField << "." << keyVectorFieldVolumeModel << " model '" << 
            model << "' not supported");
        return {};
    }

    std::string v1 = std::string(keyVectorFieldVolumeVariable) + ".1";
    std::string v2 = std::string(keyVectorFieldVolumeVariable) + ".2";
    std::string v3 = std::string(keyVectorFieldVolumeVariable) + ".3";

    bool threeVariables =
        _vectorFieldInfo.hasKeyAndValue<std::string>(v1) &&
        _vectorFieldInfo.hasKeyAndValue<std::string>(v2) &&
        _vectorFieldInfo.hasKeyAndValue<std::string>(v3);

    bool lorentzForce =
      _vectorFieldInfo.hasKeyAndValue<std::string>(v1) &&
      (_vectorFieldInfo.value<std::string>(v1) == vectorFieldKameleonVariableLorentz);

    if (!threeVariables && !lorentzForce) {
        LERROR(keyVectorField << " does not name variables");
        return {};
    }

    if (threeVariables) {
        std::string xVariable, yVariable, zVariable;
        _vectorFieldInfo.getValue(v1, xVariable);
        _vectorFieldInfo.getValue(v2, yVariable);
        _vectorFieldInfo.getValue(v3, zVariable);

        KameleonWrapper kw(fileName);
        return kw.getClassifiedFieldLines(xVariable, yVariable, zVariable, _seedPoints, _stepSize);
    }
    
    if (lorentzForce) {
        KameleonWrapper kw(fileName);
        return kw.getLorentzTrajectories(_seedPoints, _fieldlineColor, _stepSize);
    }
    
    ghoul_assert(false, "Should not reach this");
    return {};
}
示例#28
0
void MainWindow::initialize() {
    // Get the news information
    QNetworkRequest request;
    request.setUrl(QUrl(NewsURL));
    
    _newsReply = _networkManager.get(request);
    QObject::connect(_newsReply, SIGNAL(finished()),
            this, SLOT(newsReadyRead())
    );
    QObject::connect(_newsReply, SIGNAL(error(QNetworkReply::NetworkError)),
            this, SLOT(newsNetworkError())
    );

    _shortcutWidget = new ShortcutWidget(this, Qt::Popup | Qt::Dialog);
    _shortcutWidget->setWindowModality(Qt::WindowModal);
    _shortcutWidget->hide();

    _syncWidget = new SyncWidget(this, Qt::Popup | Qt::Dialog);
    _syncWidget->setWindowModality(Qt::WindowModal);
    _syncWidget->hide();

    ghoul::logging::LogManager::initialize(ghoul::logging::LogManager::LogLevel::Debug);
    LogMgr.addLog( std::make_unique< ghoul::logging::ConsoleLog >() );
    // TODO: This can crash the system in cases where the logfile can't be created ---abock
    LogMgr.addLog( std::make_unique< ghoul::logging::HTMLLog >("LauncherLog.html", ghoul::logging::HTMLLog::Append::No) );
    LogMgr.addLog( std::make_unique< QLog >() );

    std::string configurationFile = _configurationFile;
    
    _configuration = new openspace::ConfigurationManager;
    configurationFile = _configuration->findConfiguration( configurationFile );
    _configuration->loadFromFile(configurationFile);

    // Load all available scenes
    QString modulesDirectory = QString::fromStdString(absPath("${SCENE}"));
    QDir d(modulesDirectory);
    d.setFilter(QDir::Files);
    QFileInfoList list = d.entryInfoList();
    _scenes->addItem("Use Default");
    for (const QFileInfo& i : list) {
        QString file = i.fileName();
        file = file.replace(".scene", "");
        _sceneFiles.insert(file, i.absoluteFilePath());
        _scenes->addItem(file);
    }
    _scenes->setCurrentText("Use Default");
    _syncWidget->setSceneFiles(_sceneFiles);

    // Load all available configuration files
    QString configurationDirectory = QString::fromStdString(absPath("${SGCT}"));
    d = QDir(configurationDirectory);
    d.setFilter(QDir::Files);
    list = d.entryInfoList();
    _configurations->addItem("Use Default");
    for (const QFileInfo& i : list) {
        QString file = i.fileName();
        file = file.replace(".xml", "");
        _configurationFiles.insert(file, i.absoluteFilePath());
        _configurations->addItem(file);
    }
    _configurations->setCurrentText("Use Default");
}