예제 #1
0
	void cFontLoader::
		ExportDFFToFile(tDistanceFontHandle font, const Twine& in_path /*= ""*/)
	{
		auto& dff = DistanceFont(font);
		size_t face_size = cSerialization::SerializedSize(dff.Face());
		cDFFFile pair(dff, face_size);
		AlignedBuffer<16> buffer;
		cSerialization::SerializeLZMA(pair,buffer);
		cStringRef file_data(buffer.ptr<char>(), buffer.size());

		try{
			if (sys::path::has_filename(in_path))
			{
				WriteFileToDisk(file_data, in_path);
			}
			else
			{
				cSmallVector<char, 256> path_buf;
				cStringRef temp_path = in_path.toNullTerminatedStringRef(path_buf);
				sys::path::append(path_buf, in_path, dff.FontName() + ".dff");
				cStringRef full_path(path_buf.data(), path_buf.size());
				WriteFileToDisk(file_data, full_path);
			}
		}
		catch (const Exception& e)
		{
			Log::Warn("Swallowed exception while trying to write dff file: %s",
								e.what());
		}
	}
예제 #2
0
/// Copy a directory from host_source_path (on the host FS) to nand_target_path on the NAND.
///
/// Both paths should not have trailing slashes. To specify the NAND root, use "".
static bool CopySysmenuFilesToFS(FS::FileSystem* fs, const std::string& host_source_path,
                                 const std::string& nand_target_path)
{
  const auto entries = File::ScanDirectoryTree(host_source_path, false);
  for (const File::FSTEntry& entry : entries.children)
  {
    const std::string host_path = host_source_path + '/' + entry.virtualName;
    const std::string nand_path = nand_target_path + '/' + entry.virtualName;
    constexpr FS::Modes public_modes{FS::Mode::ReadWrite, FS::Mode::ReadWrite, FS::Mode::ReadWrite};

    if (entry.isDirectory)
    {
      fs->CreateDirectory(IOS::SYSMENU_UID, IOS::SYSMENU_GID, nand_path, 0, public_modes);
      if (!CopySysmenuFilesToFS(fs, host_path, nand_path))
        return false;
    }
    else
    {
      // Do not overwrite any existing files.
      if (fs->GetMetadata(IOS::SYSMENU_UID, IOS::SYSMENU_UID, nand_path).Succeeded())
        continue;

      File::IOFile host_file{host_path, "rb"};
      std::vector<u8> file_data(host_file.GetSize());
      if (!host_file.ReadBytes(file_data.data(), file_data.size()))
        return false;

      const auto nand_file =
          fs->CreateAndOpenFile(IOS::SYSMENU_UID, IOS::SYSMENU_GID, nand_path, public_modes);
      if (!nand_file || !nand_file->Write(file_data.data(), file_data.size()))
        return false;
    }
  }
  return true;
}
예제 #3
0
bool AmConfigReader::getMD5(const string& path, string& md5hash, bool lowercase) {
    std::ifstream data_file(path.c_str(), std::ios::in | std::ios::binary);
    if (!data_file) {
      DBG("could not read file '%s'\n", path.c_str());
      return false;
    }
    // that one is clever...
    // (see http://www.gamedev.net/community/forums/topic.asp?topic_id=353162 )
    string file_data((std::istreambuf_iterator<char>(data_file)),
		     std::istreambuf_iterator<char>());

    if (file_data.empty()) {
      return false;
    }

    MD5_CTX md5ctx;
    MD5Init(&md5ctx);
    MD5Update(&md5ctx, (unsigned char*)file_data.c_str(), file_data.length());
    unsigned char _md5hash[16];
    MD5Final(_md5hash, &md5ctx);
    md5hash = "";
    for (size_t i=0;i<16;i++) {
      md5hash+=char2hex(_md5hash[i], lowercase);
    }
    return true;
}
예제 #4
0
/** Add all files in a sub-directory to files. File name will be "sub_dir/filename".
 *  
 *  \param [in,out] files All files will be added in this list
 *  \param [in] dir Root directory
 *  \param [in] sub_dir Sub-directory containing the wanted files
 */
static void append_all_files( QList<std::pair<QString,QByteArray>>& files, QDir dir, QString sub_dir ){
	auto data = QDir( dir.absolutePath() + "/" + sub_dir ).entryInfoList( QStringList() << "*.*", QDir::Files );
	for( auto file : data ){
		QFile file_data( file.absoluteFilePath() );
		if( file_data.open( QIODevice::ReadOnly ) )
			files.append( { sub_dir + "/" + file.fileName(), file_data.readAll() });
		else
			qWarning() << "Could not read file!" << file.filePath();
	}
}
예제 #5
0
  bool parse_file(rapidjson::Document & doc, std::string const& file_name)
  {
    file_string file_data(file_name);
    if(file_data.is_valid() == false)
    {
      log_error(log_scope::ENGINE,
        "Unable to open json file \"{}\".", file_name);

      return false;
    }

    doc.Parse<0>(file_data.get_str().c_str());
    if(doc.HasParseError())
    {
      // rapidjson does not provide line/column, only character offset
      //   hacking it here until (if) rapidjson implements it
      std::string const& file_data_str = file_data.get_str();
      size_t const error_char_offset = doc.GetErrorOffset();
      std::string::const_iterator error_it =
        file_data_str.cbegin() + error_char_offset;

      // Compute line number, using 1 as base line
      size_t const error_line_num = 1 + std::count_if(
        file_data_str.cbegin(),
        error_it,
        std::bind2nd(std::equal_to<char>(), '\n'));

      // Compute column (char offset into line), using 1 as base column
      std::string::const_reverse_iterator reverse_error_it{error_it};
      auto error_line_begin_it = std::find(
        reverse_error_it,
        file_data_str.crend(),
        '\n');

        // If this is the first line we can
      size_t const error_column_num =
        error_line_begin_it != file_data_str.crend()
          ? std::distance(reverse_error_it, error_line_begin_it) + 1
          : error_char_offset + 1;

      // Log error
      log_error(log_scope::ENGINE, "Error parsing json file {}", file_name);
      log_error_no_prefix(log_line_seperator);
      log_error_no_prefix("== JSON ERRORS ==========");
      log_error_no_prefix("Line {}, Column {} - {}",
        error_line_num,
        error_column_num,
        doc.GetParseError());
      log_error_no_prefix(log_line_seperator);

      return false;
    }

    return true;
  }
예제 #6
0
int ZCE_XML_Implement::read(const char *file_name, ZCE_Conf_PropertyTree *propertytree)
{
    int ret = 0;
    size_t file_size = 0;
    ret = ZCE_LIB::filelen(file_name, &file_size);
    if (0 != ret)
    {
        ZCE_LOG(RS_ERROR, "[zcelib]: ZCE_XML_Implement::read fail,ZCE_LIB::filelen."
                "path=[%s],last error [%d]",
                file_name,
                ZCE_LIB::last_error());
        return ret;
    }
    size_t buf_len = file_size + 16, read_len = 0;
    //只有unique_ptr 才能默认直接使用数组,
    std::unique_ptr<char[]> file_data(new char[buf_len]);
    ret = ZCE_LIB::read_file_data(file_name, file_data.get(), buf_len, &read_len);
    if (0 != ret)
    {
        ZCE_LOG(RS_ERROR, "[zcelib]: ZCE_XML_Implement::read fail,ZCE_LIB::read_file_data."
                "path=[%s],last error [%d]",
                file_name,
                ZCE_LIB::last_error());
        return ret;
    }

    try
    {
        // character type defaults to char
        rapidxml::xml_document<char> doc;
        //parse_non_destructive
        doc.parse<rapidxml::parse_default>(file_data.get());

        const rapidxml::xml_node<char> *root = doc.first_node();
        //广度遍历dom tree
        read_dfs(root, propertytree);
    }
    catch (rapidxml::parse_error &e)
    {
        ZCE_LOG(RS_ERROR, "[ZCELIB]file [%s] don't parse error what[%s] where[%s].",
                e.what(),
                e.where<char>());
        return -1;
    }


    return 0;
}
예제 #7
0
Loader::ResultStatus TitleMetadata::Load(const std::string& file_path) {
    FileUtil::IOFile file(file_path, "rb");
    if (!file.IsOpen())
        return Loader::ResultStatus::Error;

    std::vector<u8> file_data(file.GetSize());

    if (!file.ReadBytes(file_data.data(), file.GetSize()))
        return Loader::ResultStatus::Error;

    Loader::ResultStatus result = Load(file_data);
    if (result != Loader::ResultStatus::Success)
        LOG_ERROR(Service_FS, "Failed to load TMD from file %s!", file_path.c_str());

    return result;
}
예제 #8
0
void CSSDocument::add_sheet(CSSSheetOrigin origin, const std::string &filename, const FileSystem &fs)
{
	// Load the css document:
	IODevice file = fs.open_file(filename);
	DataBuffer file_data(file.get_size());
	file.read(file_data.get_data(), file_data.get_size());
	std::string css_text(file_data.get_data(), file_data.get_size());

	// Find the base URI for this css document:
	std::string base_uri = PathHelp::get_fullpath(filename);

	// Find import directives and load those first:
	std::vector<std::string> import_urls = CSSTokenizer(css_text).read_import_urls();
	for (size_t i = 0; i < import_urls.size(); i++)
	{
		add_sheet(origin, PathHelp::combine(base_uri, import_urls[i]), fs);
	}

	// Add the css sheet:
	CSSTokenizer tokenizer(css_text);
	impl->sheets.push_back(std::shared_ptr<CSSDocumentSheet>(new CSSDocumentSheet(origin, tokenizer, base_uri)));
}
void FileDeleteHandler::_handle(HttpRequest &hmsg){
    Server_Logger* log = Server_Logger::getInstance();
    std::string username = hmsg.getUsername();
    log->Log("El campo recibido por username es : "+username,DEBUG);
    if(username == ""){
        hmsg.setResponse(Status::InvalidArgument());
        return;
    }
    std::string filename = hmsg.getFilename();
    log->Log("El campo recibido por filename es : "+filename,DEBUG);
    if(filename == ""){
        hmsg.setResponse(Status::InvalidArgument());
        return;
    }

    UserMetadata user_metadata(db);
    user_metadata.setUsername(username);

    log->Log("Verifica a quien le pertenece el arcivo buscado",INFO);
    if(user_metadata.DBisSharedFile(filename).first != ""){
        log->Log("No puedo borrar un archivo compartido",WARNING);
        hmsg.setResponse(Status::Corruption(), "Permission denied");
        return;
    }

    FileData file_data(db);
    file_data.setOwnerUsername(username);
    file_data.setFilename(filename);
    Status s = file_data.DBerase();

    // devolver mensaje de error
    if(s.ok()){
        hmsg.setResponse(s, "File deleted");
    } else {
        hmsg.setResponse(s);
    }
}
예제 #10
0
파일: tox.c 프로젝트: askielboe/toxcore
/* Send file data.
 *
 *  return 0 on success
 *  return -1 on failure
 */
int tox_file_send_data(Tox *tox, int32_t friendnumber, uint8_t filenumber, const uint8_t *data, uint16_t length)
{
    Messenger *m = tox;
    return file_data(m, friendnumber, filenumber, data, length);
}
예제 #11
0
bool GLShaderImpl::CompileSourceFile(const string &filename) {
  readfile::ScopedFileData file_data(readfile::ReadFile(filename, true));
  const char *data = reinterpret_cast<char*>(file_data.data);
  m_need_recompile = false;
  return CompileFromSourceImpl(data);
}
예제 #12
0
void FileAddHandler::_handle(HttpRequest &hmsg){
    Status s;

    Server_Logger* log = Server_Logger::getInstance();
    std::string filename = hmsg.getCampo("filename");
    log->Log("El campo recibido por filename es : "+filename,DEBUG);
    if(filename == ""){
        hmsg.setResponse(Status::InvalidArgument());
        return;
    }
    std::string owner_username = hmsg.getUsername();
    log->Log("El campo recibido por owner username es : "+owner_username,DEBUG);
    if(owner_username == ""){
        hmsg.setResponse(Status::InvalidArgument());
        return;
    }
    std::string ubicacion = hmsg.getCampo("ubicacion");
    std::string content = hmsg.getCampo("content");
    log->Log("El campo recibido por content es : "+content,DEBUG);
    if(content == "") return;

    FileData file_data(db);
    file_data.setFilename(filename);
    file_data.setOwnerUsername(owner_username);

    s = file_data.DBcreate(content, ubicacion);
    if(!s.ok()){
        hmsg.setResponse(s);
        return;
    }

    // esto va aca, o directo cuando creas un archivo no tiene nada de esto y se agrega con modificaciones?

    std::string tag = "tags";
    std::vector<std::string> tags;
    for(int i = 0;; ++i){
        tag = hmsg.getCampoDeArray("tags", i);
        if(tag == "")
            break;
        //s = file_data.DBaddTag(tag);
        // ver status
        tags.push_back(tag);
    }

    std::string user_with_read_perm = "user_read_perm";
    std::vector<std::string> users_with_read_perm;
    for(int i = 0;; ++i){
        user_with_read_perm = hmsg.getCampoDeArray("users_with_read_permission", i);
        if(user_with_read_perm == "")
            break;
        //s = file_data.DBaddUserWithReadPermission(user_with_read_perm);
        // ver status
        users_with_read_perm.push_back(user_with_read_perm);
    }

    std::string user_with_write_perm = "user_write_perm";
    std::vector<std::string> users_with_write_perm;
    for(int i = 0;; ++i){
        user_with_write_perm = hmsg.getCampoDeArray("users_with_write_permission", i);
        if(user_with_write_perm == "")
            break;
        //s = file_data.DBaddUserWithWritePermission(user_with_write_perm);
        // ver status
        users_with_write_perm.push_back(user_with_write_perm);
    }

    std::vector<std::string> empty;
    std::vector<int> empty2;
    s = file_data.DBmodify(owner_username, "", "", "", users_with_read_perm, empty, users_with_write_perm, empty, tags, empty, empty2);

    if(s.ok()){
        hmsg.setResponse(s, "File uploaded successfully");
    } else {
        hmsg.setResponse(s);
    }
}
예제 #13
0
파일: tox.c 프로젝트: zan33/ProjectTox-Core
/* Send file data.
 *
 *  return 0 on success
 *  return -1 on failure
 */
int tox_file_send_data(Tox *tox, int friendnumber, size_t filenumber, size_t *data, size_t length)
{
    Messenger *m = tox;
    return file_data(m, friendnumber, filenumber, data, length);
}
예제 #14
0
void FileModifyHandler::_handle(HttpRequest &hmsg){
    Status s;

    Server_Logger* log = Server_Logger::getInstance();
    std::string filename = hmsg.getFilename();
    log->Log("El campo recibido por filename es : "+filename,DEBUG);
    if(filename == ""){
        hmsg.setResponse(Status::InvalidArgument());
        return;
    }
    std::string username = hmsg.getUsername();
    log->Log("El campo recibido por username es : "+username,DEBUG);
    if(username == ""){
        hmsg.setResponse(Status::InvalidArgument());
        return;
    }
    std::string owner_username = "";
    /*std::string owner_username = hmsg.getCampo("owner_username");
    log->Log("El campo recibido por owner username es : "+owner_username,DEBUG);
    if(owner_username == ""){
        hmsg.setResponse(Status::InvalidArgument());
        return;
    }*/

    UserMetadata user_metadata(db);
    user_metadata.setUsername(username);

    log->Log("Verifica a quien le pertenece el arcivo buscado",INFO);
    if(user_metadata.DBisMyFile(filename)){
        owner_username = username;
    } else {
        owner_username = user_metadata.DBisSharedFile(filename).first;

        if(owner_username == ""){
            log->Log("No se encontro el archivo buscado",WARNING);
            hmsg.setResponse(Status::NotFound("File not found"));
            return;
        }
    }

    std::string ubicacion = hmsg.getCampo("ubicacion");
    std::string filename_new = hmsg.getCampo("filename_change");
    std::string content_new = hmsg.getCampo("content_change");

    std::vector<int> delete_versions;
    for(int i = 0;; ++i){
        std::string v_str = hmsg.getCampoDeArray("delete_versions", i);
        if(v_str == "")
            break;
        delete_versions.push_back(atoi(v_str.c_str()));
    }

    std::vector<std::string> users_read_add;
    for(int i = 0;; ++i){
        std::string user = hmsg.getCampoDeArray("users_with_read_permission_add", i);
        if(user == "")
            break;
        //file_data.DBaddUserWithReadPermission(user);
        users_read_add.push_back(user);
    }

    std::vector<std::string> users_read_remove;
    for(int i = 0;; ++i){
        std::string user = hmsg.getCampoDeArray("users_with_read_permission_remove", i);
        if(user == "")
            break;
        //file_data.DBremoveUserWithReadPermission(user);
        users_read_remove.push_back(user);
    }

    std::vector<std::string> users_write_add;
    for(int i = 0;; ++i){
        std::string user = hmsg.getCampoDeArray("users_with_write_permission_add", i);
        if(user == "")
            break;
        //file_data.DBaddUserWithWritePermission(user);
        users_write_add.push_back(user);
    }

    std::vector<std::string> users_write_remove;
    for(int i = 0;; ++i){
        std::string user = hmsg.getCampoDeArray("users_with_write_permission_remove", i);
        if(user == "")
            break;
        //file_data.DBremoveUserWithWritePermission(user);
        users_write_remove.push_back(user);
    }

    std::vector<std::string> tags_add;
    for(int i = 0;; ++i){
        std::string tag = hmsg.getCampoDeArray("tags_add", i);
        if(tag == "")
            break;
        //file_data.DBaddTag(tag);
        tags_add.push_back(tag);
    }

    std::vector<std::string> tags_remove;
    for(int i = 0;; ++i){
        std::string tag = hmsg.getCampoDeArray("tags_delete", i);
        if(tag == "")
            break;
        //file_data.DBremoveTag(tag);
        tags_remove.push_back(tag);
    }

    FileData file_data(db);
    file_data.setFilename(filename);
    file_data.setOwnerUsername(owner_username);
    s = file_data.DBmodify(username, filename_new, ubicacion, content_new, users_read_add, users_read_remove, users_write_add, users_write_remove, tags_add, tags_remove, delete_versions);
    hmsg.setResponse(s);
}