BOOL CCheckRuleXMLParse::Load(CheckRuleArray &arrCheckRuleList)
{
	BOOL bRet = FALSE;
	// 检查旧版本生成的未加密xml文件是否存在
	CString strOldXmlPath = m_strRuleFilePath;
	strOldXmlPath.Replace(L".bpxml", L"xml");
	if (IsFileExist(strOldXmlPath))
	{
		// 读取老版本生成的未加密xml
		if (CheckVersion(m_strRuleFilePath).CompareNoCase(L"1.0") == 0)
			bRet = Load(m_strRuleFilePath, arrCheckRuleList);
		if (CheckVersion(m_strRuleFilePath).CompareNoCase(L"1.1") == 0)
			bRet = LoadNew(m_strRuleFilePath, arrCheckRuleList);
	}
	else
	{
		if (IsFileExist(m_strRuleFilePath))
		{
			// 先解密再读取
			CString strTempXmlFile;
			GetTempFile(strTempXmlFile, L"xml");
			DecodeFileEx(m_strRuleFilePath, strTempXmlFile);
			if (CheckVersion(strTempXmlFile).CompareNoCase(L"1.0") == 0)
				bRet = Load(strTempXmlFile, arrCheckRuleList);
			if (CheckVersion(strTempXmlFile).CompareNoCase(L"1.1") == 0)
				bRet = LoadNew(strTempXmlFile, arrCheckRuleList);

			// 结束后删除临时xml文件
			SafeDeleteFile(strTempXmlFile);
		}
	}

	return bRet;
}
Example #2
0
HRESULT CFGFilterLAVAudio::Create(IBaseFilter** ppBF, CInterfaceList<IUnknown, &IID_IUnknown>& pUnks)
{
    HRESULT hr = __super::Create(ppBF, pUnks);

    if (SUCCEEDED(hr)) {
        if (!CheckVersion(m_path)) {
            hr = E_FAIL;
        } else if (CComQIPtr<ILAVAudioSettings> pLAVFSettings = *ppBF) {
            // Take control over LAVAudio's settings, the settings are reseted to default values
            hr = pLAVFSettings->SetRuntimeConfig(TRUE);

            if (SUCCEEDED(hr)) {
                Settings settings;
                if (settings.GetSettings(pLAVFSettings)) { // Get default settings from LAVAudio
                    settings.LoadSettings(); // Load our current settings from registry/ini
                    settings.SetSettings(pLAVFSettings); // Set our settings in LAVAudio
                }

                // Keep track of LAVFilters instances in runtime mode
                s_instances.AddTail(*ppBF);
            }
        } else {
            hr = E_NOINTERFACE;
        }
    }

    return hr;
}
bool ClientVersionManage::CompareVersion(const std::string& PduId, const std::string& LocalVer, std::string& DownloadUrl, std::string& ForceUpdate)const
{
	if ((0 == PduId.size()) || (0 == LocalVer.size()))
	{
		ERROR_LOG() << "Invalid parameter, string is empty!!!";
		return false;
	}
	
	std::string ServerUrl = UpdateServerConfig::GetServerUrl();

	const int LENGTH = 128;
	char acServer[LENGTH] = {0};
	char acDownloadUrl[LENGTH] = {0};
	char acForceUpdate[LENGTH] = {0};
	
	int iRet = GetLatestVersion(PduId.c_str(), ServerUrl.c_str(), acServer, acDownloadUrl, acForceUpdate, LENGTH);	
	if (UPDATEADAPTER_SUCCESS != iRet)
	{
		ERROR_LOG() << "Not have the update job for product Id = " << PduId;
		return false;
	}

	std::string ServerVer = acServer;
	DownloadUrl = acDownloadUrl;
	ForceUpdate = acForceUpdate;

	bool bRet = CheckVersion(LocalVer, ServerVer);
	
	return bRet;
}
Example #4
0
bool CPlugIn::Load()
{
	if(m_Filename == "")
	{
		return false;
	}

	if(!OpenLib())
	{
		return false;
	}

	if(!CheckVersion())
	{
		Close();
		return false;
	}

	if(!LoadSymbols())
	{
		Close();
		return false;
	}

	m_Initialized = true;

	return true;
}
Example #5
0
PRBool
GRE_FindGREFramework(const char* rootPath,
                     const GREVersionRange *versions,
                     PRUint32 versionsLength,
                     const GREProperty *properties,
                     PRUint32 propertiesLength,
                     char* buffer, PRUint32 buflen)
{
  PRBool found = PR_FALSE;

  snprintf(buffer, buflen,
           "%s/Library/Frameworks/" GRE_FRAMEWORK_NAME "/Versions", rootPath);
  DIR *dir = opendir(buffer);
  if (dir) {
    struct dirent *entry;
    while (!found && (entry = readdir(dir))) {
      if (CheckVersion(entry->d_name, versions, versionsLength)) {
        snprintf(buffer, buflen,
                 "%s/Library/Frameworks/" GRE_FRAMEWORK_NAME
                 "/Versions/%s/" XPCOM_DLL, rootPath, entry->d_name);
        if (access(buffer, R_OK | X_OK) == 0)
          found = PR_TRUE;
      }
    }

    closedir(dir);
  }
  
  if (found)
    return PR_TRUE;

  buffer[0] = '\0';
  return PR_FALSE;
}
Example #6
0
static PRBool
CheckINIHeader(const char *aHeader, void *aClosure)
{
  nsresult rv;

  INIClosure *c = reinterpret_cast<INIClosure *>(aClosure);

  if (!CheckVersion(aHeader, c->versions, c->versionsLength))
    return PR_TRUE;

  const GREProperty *properties = c->properties;
  const GREProperty *endProperties = properties + c->propertiesLength;
  for (; properties < endProperties; ++properties) {
    char buffer[MAXPATHLEN];
    rv = c->parser->GetString(aHeader, properties->property,
                             buffer, sizeof(buffer));
    if (NS_FAILED(rv))
      return PR_TRUE;

    if (strcmp(buffer, properties->value))
      return PR_TRUE;
  }

  rv = c->parser->GetString(aHeader, "GRE_PATH", c->pathBuffer, c->buflen);
  if (NS_FAILED(rv))
    return PR_TRUE;

  if (!safe_strncat(c->pathBuffer, "/" XPCOM_DLL, c->buflen) ||
      access(c->pathBuffer, R_OK))
    return PR_TRUE;

  // We found a good GRE! Stop looking.
  c->found = PR_TRUE;
  return PR_FALSE;
}
Example #7
0
void Entity::SetFilename( const char* filename )
{
	Reset();
	sqlite3_close(m_db); m_db = 0;

	if( sqlite3_open(filename, &m_db) == SQLITE_OK)
	{
		sqlite3_int64 version = 0;
		if(CheckVersion(&version))
		{
			// TODO: check to see if I can load and convert an older version.
			Query enable_fk(m_db, "PRAGMA foreign_keys = ON");
			enable_fk.Step();
		
			sqlite3_busy_timeout(m_db, 1000);

			CreateMissingTables();
			sqlite3_int64 skelid;
			if(FindFirstSkeleton(&skelid)) {
				SetCurrentSkeleton(skelid);
			}
		
			EnsureVersion();
		}
		else
		{
			sqlite3_close(m_db); m_db = 0;

			Events::WrongFileVersion ev;
			ev.FileVersion = version;
			ev.RequiredVersion = kCurrentVersion;
			m_evsys->Send(&ev);
		}
	}
}
Example #8
0
    /**
     * @brief Construct with filename and left hand side
     */
    VXFile (const std::string& fname, const IOMode mode = READ,
			  const Params& params = Params(), const bool verbosity = false) : _context(0) {
        CheckVersion (fname);
        if (_version == IDEA_VD)
        	_context = (SyngoFile*) new VD::VDFile(fname, mode, params, verbosity);
        else
        	_context = (SyngoFile*) new VB::VBFile(fname, mode, params, verbosity);
    }
Example #9
0
sPATCHDialog::sPATCHDialog(wxWindow* parent,wxWindowID id)
{
    //(*Initialize(sPATCHDialog)
    wxFlexGridSizer* FlexGridSizer_Main;
    wxGridSizer* GridSizer_Buttons;

    Create(parent, wxID_ANY, _("Perfect World Patcher"), wxDefaultPosition, wxDefaultSize, 0, _T("wxID_ANY"));
    FlexGridSizer_Main = new wxFlexGridSizer(5, 1, 0, 0);
    BitmapButton_Close = new wxBitmapButton(this, ID_BITMAPBUTTON4, wxBitmap(wxImage(_T("skin/btn_close.png"))), wxDefaultPosition, wxSize(16,14), 0, wxDefaultValidator, _T("ID_BITMAPBUTTON4"));
    BitmapButton_Close->SetBitmapDisabled(wxBitmap(wxImage(_T("skin/btn_close_bw.png"))));
    BitmapButton_Close->SetBitmapSelected(wxBitmap(wxImage(_T("skin/btn_close_ck.png"))));
    BitmapButton_Close->SetDefault();
    BitmapButton_Close->Disable();
    FlexGridSizer_Main->Add(BitmapButton_Close, 1, wxTOP|wxBOTTOM|wxRIGHT|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL, 5);
    HtmlWindow_Notes = new wxHtmlWindow(this, ID_HTMLWINDOW1, wxDefaultPosition, wxSize(384,216), 0, _T("ID_HTMLWINDOW1"));
    HtmlWindow_Notes->Hide();
    FlexGridSizer_Main->Add(HtmlWindow_Notes, 1, wxLEFT|wxRIGHT|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL, 5);
    GridSizer_Buttons = new wxGridSizer(2, 0, 0, 0);
    BitmapButton_Update = new wxBitmapButton(this, ID_BITMAPBUTTON1, wxBitmap(wxImage(_T("skin/btn_update.png"))), wxDefaultPosition, wxSize(95,27), 0, wxDefaultValidator, _T("ID_BITMAPBUTTON1"));
    BitmapButton_Update->SetBitmapDisabled(wxBitmap(wxImage(_T("skin/btn_update_bw.png"))));
    BitmapButton_Update->SetBitmapSelected(wxBitmap(wxImage(_T("skin/btn_update_ck.png"))));
    BitmapButton_Update->SetDefault();
    BitmapButton_Update->Disable();
    GridSizer_Buttons->Add(BitmapButton_Update, 1, wxTOP|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
    BitmapButton_Play = new wxBitmapButton(this, ID_BITMAPBUTTON3, wxBitmap(wxImage(_T("skin/btn_play.png"))), wxDefaultPosition, wxSize(95,27), 0, wxDefaultValidator, _T("ID_BITMAPBUTTON3"));
    BitmapButton_Play->SetBitmapDisabled(wxBitmap(wxImage(_T("skin/btn_play_bw.png"))));
    BitmapButton_Play->SetBitmapSelected(wxBitmap(wxImage(_T("skin/btn_play_ck.png"))));
    BitmapButton_Play->SetDefault();
    BitmapButton_Play->Disable();
    GridSizer_Buttons->Add(BitmapButton_Play, 1, wxTOP|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 4);
    FlexGridSizer_Main->Add(GridSizer_Buttons, 1, wxRIGHT|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL, 5);
    Gauge_Progress = new wxGauge(this, ID_GAUGE1, 100, wxDefaultPosition, wxSize(300,8), 0, wxDefaultValidator, _T("ID_GAUGE1"));
    Gauge_Progress->SetForegroundColour(wxColour(0,255,0));
    Gauge_Progress->SetBackgroundColour(wxColour(0,0,64));
    FlexGridSizer_Main->Add(Gauge_Progress, 1, wxALL|wxEXPAND|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
    SetSizer(FlexGridSizer_Main);
    Timer_Progress.SetOwner(this, ID_TIMER1);
    Timer_Progress.Start(100, true);
    FlexGridSizer_Main->Fit(this);
    FlexGridSizer_Main->SetSizeHints(this);
    Center();

    Connect(ID_BITMAPBUTTON4,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&sPATCHDialog::OnBitmapButton_CloseClick);
    Connect(ID_BITMAPBUTTON1,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&sPATCHDialog::OnBitmapButton_UpdateClick);
    Connect(ID_BITMAPBUTTON3,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&sPATCHDialog::OnBitmapButton_PlayClick);
    Connect(ID_TIMER1,wxEVT_TIMER,(wxObjectEventFunction)&sPATCHDialog::OnTimer_ProgressTrigger);
    Connect(wxID_ANY,wxEVT_PAINT,(wxObjectEventFunction)&sPATCHDialog::OnPaint);
    //*)

    BackgroundImage = wxBitmap(wxT("skin/window.png"), wxBITMAP_TYPE_PNG);
    //HtmlWindow_Notes->SetBackgroundImage(wxBitmap(wxT("skin/index/background.jpg", wxBITMAP_TYPE_JPEG));
    SetIcon(wxIcon(wxT("skin/window.ico"), wxBITMAP_TYPE_ICO));

    // Add support for handling files starting with http: or ftp:
    wxFileSystem::AddHandler(new wxInternetFSHandler);

    CheckVersion();
}
Example #10
0
void Realm::SetVersion(QString version)
{
    if (!CheckVersion(version))
    {
        Log::Write(LOG_TYPE_ERROR, "Try to set invalid version for the realm %s", GetName().toLatin1().data());
        return;
    }

    m_version = version;
}
Example #11
0
CString CFGFilterLAV::GetFilterPath(LAVFILTER_TYPE filterType)
{
    // Default path
    CString filterPath = PathUtils::CombinePaths(PathUtils::GetProgramPath(), LAVFILTERS_DIR);
    CLSID filterCLSID;

    switch (filterType) {
        case SPLITTER:
        case SPLITTER_SOURCE:
            filterPath  = PathUtils::CombinePaths(filterPath, CFGFilterLAVSplitterBase::filename);
            filterCLSID = GUID_LAVSplitter;
            break;
        case VIDEO_DECODER:
            filterPath  = PathUtils::CombinePaths(filterPath, CFGFilterLAVVideo::filename);
            filterCLSID = GUID_LAVVideo;
            break;
        case AUDIO_DECODER:
            filterPath  = PathUtils::CombinePaths(filterPath, CFGFilterLAVAudio::filename);
            filterCLSID = GUID_LAVAudio;
            break;
        default:
            ASSERT(FALSE); // This should never happen
            break;
    }

#if ENABLE_LOAD_EXTERNAL_LAVF_AS_INTERNAL
    // Check that the filter's version is correct
    if (!CheckVersion(filterPath)) {
        // If not, check if a registered version of the filter is available.
        filterPath = ::GetFilterPath(filterCLSID);
        // and if it can be used
        if (!CheckVersion(filterPath)) {
            filterPath = _T("");
        }
    }
#endif

    return filterPath;
}
Example #12
0
 TestDatabase::TestDatabase(std::shared_ptr<DatabaseDriver> & driver, int target_version): books(new TestTableBooks), authors(new TestTableAuthors) {
     
     // set the driver (currently just SQLite)
     SetDriver(driver);
     
     // set up our tables
     AddTable(books);
     AddTable(authors);
     
     // handle migrations after setting the driver
     CheckVersion(target_version);
     
 }
    bool BitArray::BitArrayEnumerator::MoveNext()
      {
      CheckVersion();

      if(_index < (_bitArray.Count() - 1)) 
        {
        _current.Reset(new Boolean(_bitArray[++_index]));
        return true;
        }

      _index = _bitArray.Count();
      return false;
      }
Example #14
0
void Crypt::String::Encrypt (std::string const & description)
{
	Assert (description.size () != 0);
	CheckVersion ();
	DATA_BLOB blobIn;
	blobIn.cbData = _plainText.size (); // if string, includes final null
	blobIn.pbData = &_plainText [0];
	::CryptProtectData (&blobIn, 
					ToWString (description).c_str (), // description
					0, // entropy
					0, // reserved
					0, // prompt
					0, // flags (only currently logged user can decrypt)
					&_blob);
}
Example #15
0
    bool SecFile::DoVerify()
    {
        assert(!(crash_b_));
        char content[1024 * 64];

        if (!IsOpen())
        {
            return false;
        }
        boost::uint32_t readnum = Read(&head_, sizeof(SecFileHead));
        if (readnum != sizeof(SecFileHead))
        {
            return false;
        }

        if (false == CheckVersion(head_.verison_))
        {
            LOG4CPLUS_ERROR_LOG(logger_cfg_file, "CheckVersion failed!");
            return false;
        }

        // 2011.1.5 modified by jeffrey:采用写入校验的DoSign函数中的算法来进行读取的时候校验
        // 与2.0.1.584兼容,与1554不兼容
        MD5 file_hash = head_.sec_md5_;
        head_.sec_md5_.clear();

        md5_.Add((char*)&head_, sizeof(head_));

        while (readnum = Read(content, sizeof(content)))
        {
            md5_.Add(content, readnum);
        }

        md5_.Finish();

        SMD5 hash;
        md5_.GetHash(&hash);

        if (memcmp((void*)&hash, (void*)&(file_hash), sizeof(hash)))
        {
            return false;
        }

        Seek(sizeof(head_), SEEK_SET);
        return true;
    }
Example #16
0
/* virtual */
bool
WMAPResource::Load(Archive* archive, uint32 key)
{
	if (!Resource::Load(archive, key))
		return false;

	if (!CheckSignature(WMAP_SIGNATURE))
		return false;

	if (!CheckVersion(WMAP_VERSION_1))
		return false;

	fData->ReadAt(8, fCount);
	fData->ReadAt(12, fOffset);

	// TODO: Handle the case where there are more than one.
	fData->ReadAt(fOffset, fWorldMapEntry);

	fIcons = gResManager->GetBAM(fWorldMapEntry.map_icons_bam);

	for (uint32 c = 0; c < fWorldMapEntry.areaentries_count; c++) {
		area_entry areaEntry;
		if (GetAreaEntry(c, areaEntry)) {
			fData->ReadAt(
					fWorldMapEntry.areaentries_offset
					+ c * sizeof(area_entry),
					areaEntry);
			AreaEntry* entry = new AreaEntry(areaEntry);
			/*std::cout << "Area " << areaEntry.area;
			std::cout << ", short: " << areaEntry.shortname;
			std::cout << ", long: " <<  areaEntry.name;
			std::cout << ", tooltip: " << areaEntry.tooltip_ref;
			std::cout << ", loading " << areaEntry.loading_mos;
			std::cout << std::endl;
			*/

			entry->fIcon = const_cast<Bitmap*>(fIcons->FrameForCycle(areaEntry.icons_bam_sequence, 0));
			entry->fPosition.x = (int16)areaEntry.x;
			entry->fPosition.y = (int16)areaEntry.y;
			fAreaEntries.push_back(entry);
		}
	}

	return true;
}
Example #17
0
void
WEDResource::_Load()
{
	if (!CheckSignature("WED "))
		throw -1;

	if (!CheckVersion("V1.3"))
		throw -1;
	
	fData->ReadAt(8, fNumOverlays);
	fData->ReadAt(12, fNumTiledObjects);
	fData->ReadAt(16, fOverlaysOffset);
	fData->ReadAt(20, f2ndHeaderOffset);
	fData->ReadAt(24, fTiledObjectsOffset);
	fData->ReadAt(28, fTiledObjectsTileCellsOffset);

	_LoadPolygons();
}
Example #18
0
/* virtual */
bool
ITMResource::Load(Archive *archive, uint32 key)
{
	if (!Resource::Load(archive, key))
		return false;

	if (!CheckSignature(ITM_SIGNATURE))
		return false;

	if (!CheckVersion(ITM_VERSION_1))
		return false;

	fData->ReadAt(8, fHeader);

	std::cout << "Name: " << IDTable::ObjectAt(fHeader.name_identified) << std::endl;

	return true;
}
Example #19
0
int CUpdator::Check()
{
	//get local version
	CVersion local = GetLocalVersion();
	//get remote version
	CVersion remote=GetRemoteVersion();
	//remote is empty,so return
	if (remote ==CVersion())
	{
		LOG(_T("remote version error."));
		//notify l
		DWORD res = 4;
		Event loading(E_UPDATE_OVER,(void*)this,0,res);
		Notify(loading);
		return false;
	}
	//check version
	bool need_update = CheckVersion(local,remote);
	return need_update;
}
Example #20
0
void Crypt::String::Decrypt ()
{
	CheckVersion ();
	DATA_BLOB blobOut;
	Assert (_blob.pbData != 0);
	if (::CryptUnprotectData (&_blob, 
					0, // description
					0, // entropy
					0, // reserved
					0, // prompt
					0, // flags (only currently logged user can decrypt)
					&blobOut) == FALSE)
	{
		throw Win::Exception ("Decryption of local data failed");
	}
	Assume (blobOut.cbData > 0, "If string, includes final null"); // if string, includes final null
	_plainText.resize (blobOut.cbData);
	std::copy (blobOut.pbData, blobOut.pbData + blobOut.cbData, &_plainText [0]);
	::LocalFree (blobOut.pbData);
}
Example #21
0
void CommandProcess()
{
	// Read incoming control messages
	if (Serial_available() >= 2)
	{
		char start=Serial_read();
		if (start == '@') {// Start of new control message
			int command = Serial_read(); // Commands
			if (command == 'h') {//Hook AHRS Stack Device
				// Read ID
				char id[2];
				id[0] = GetChar();
				id[1] = GetChar();
				// Reply with synch message
				printf("@HOOK");
				Serial_write(id, 2);
			}
			else if (command == 'v') {//Check Version
				CheckVersion();
			}
			else if (command == 'c') {// A 'c'calibration command
				SensorCalibration();
			}
			else if (command == 'b') {// 'b'lock erase flash
				FlashControl();
			}
			else if (command == 'p') {// Set 'p'id command
				SetPID();
			}
			else if (command == 'm') {// Set report 'm'ode
				char mode = GetChar();
				if (mode == 'e') {// Report AHRS by 'e'uler angle
					report_mode = REPORT_AHRS_EULER;
				}
				else if (mode == 'q') {// Report // Report AHRS by 'q'quaternion
					report_mode = REPORT_AHRS_QUATERNION;
				}
				else if (mode == 'r') {// Report sensor 'r'aw data
					report_mode = REPORT_SENSORS_RAW;
				}
				else if (mode == 'c') {// Report sensor 'c'alibrated data
					report_mode = REPORT_SENSORS_CALIBRATED;
				}
				else if (mode == 'm') {// Report 'm'otor power distribution
					report_mode = REPORT_MOTOR_POWER;
				}
				else if (mode == 'v') {// Report 'v'elocity
					report_mode = REPORT_VELOCITY;
				}
				else if (mode == 's') {// Report 's'tatus
					report_status();
				}
				else if (mode == 'p') {// Report controller 'p'id
					char type = GetChar();
					if (type == 'p') // 'p'id
						report_mode = REPORT_PID;
					else if (type == 'r') //'r'ate pid
						report_mode = REPORT_RATE_PID;
					else if (type == 'a') //'a'ltitude hold pid
						report_mode = REPORT_ALTHOLD_PID;
				}
			}
			else if (command == 'f') {// Set report 'f'ormat
				char format = GetChar();
				if (format == 'b') {// Report 'b'inary format
					report_format = REPORT_FORMAT_BINARY;
				}
				else if (format == 't') {// Report 't'ext format
					report_format = REPORT_FORMAT_TEXT;
				}
			}
			else if (command == 's') {// 's'tream output control
				char mode = GetChar();
				if (mode == 's') {// 's'tart stream
					stream_mode = STREAM_START;
				}
				else if (mode == 'p') {// 'p'ause stream
					stream_mode = STREAM_PAUSE;
				}
				else if (mode == 't') {// 't'oggle stream
					if(stream_mode==STREAM_START)
						stream_mode = STREAM_PAUSE;
					else
						stream_mode = STREAM_START;
				}
			}
		}
		else { 
			if (report_format == REPORT_FORMAT_TEXT) {
			printf("Unknown command.\n");
			}
		} // Skip character
	}
}
Example #22
0
 VXFile (const std::string& fname, int nlhs = 0, mxArray *lhs[] = 0) {
     CheckVersion (fname);
     _context = (_version == IDEA_VD) ?
         (SyngoFile*) new VD::VDFile(fname, nlhs, lhs) :
         (SyngoFile*) new VB::VBFile(fname, nlhs, lhs);
 }
Example #23
0
int PrimeWorker::HandleRequest(zmq_pollitem_t *item) {
	
	proto::Request& req = mRequest;
	zmsg_t* msg = ReceiveRequest(req, item->socket);
	if(!msg)
		return 0;
	
	//req.PrintDebugString();
	
	proto::Request::Type rtype = req.type();
	proto::Reply::ErrType etype = proto::Reply::NONE;
	
	proto::Reply& rep = mReply;
	rep.Clear();
	rep.set_type(rtype);
	rep.set_reqid(req.reqid());
	
	if(!proto::Request::Type_IsValid(rtype)){
		printf("ERROR: !proto::Request::Type_IsValid.\n");
		rtype = proto::Request::NONE;
		etype = proto::Reply::INVALID;
	}
	
	while(etype == proto::Reply::NONE) {
		
		int vstatus = CheckVersion(req.version());
		if(vstatus <= 0){
			rep.set_errstr("Your miner version is no longer supported. Please upgrade.");
			etype = proto::Reply::VERSION;
			break;
		}
		
		if(rtype == proto::Request::CONNECT){
			
			rep.mutable_sinfo()->CopyFrom(mServerInfo);
				
			if(vstatus == 1){
				etype = proto::Reply::VERSION;
				rep.set_errstr("Your miner version will no longer be supported in the near future. Please upgrade.");
			}
			
		}else if(rtype == proto::Request::GETWORK){
			
			if(!mCurrBlock.has_height()){
				etype = proto::Reply::HEIGHT;
				break;
			}
			
			if(req.height() != mCurrHeight){
				etype = proto::Reply::HEIGHT;
				break;
			}
			
			CBlock *pblock = &mBlockTemplate->block;
			IncrementExtraNonce(pblock, mIndexPrev, mExtraNonce);
			pblock->nTime = std::max(pblock->nTime, (unsigned int)GetAdjustedTime());
			
			mNonceMap[pblock->hashMerkleRoot] = mExtraNonce;
			
			proto::Work* work = rep.mutable_work();
			work->set_height(mCurrHeight);
			work->set_merkle(pblock->hashMerkleRoot.GetHex());
			work->set_time(pblock->nTime);
			work->set_bits(pblock->nBits);
			
		}else if(rtype == proto::Request::SHARE){
			
			if(!mCurrBlock.has_height()){
				etype = proto::Reply::STALE;
				break;
			}
			
			if(!req.has_share()){
				printf("ERROR: !req.has_share().\n");
				etype = proto::Reply::INVALID;
				break;
			}
			
			const proto::Share& share = req.share();
			
			if(share.height() != mCurrHeight){
				etype = proto::Reply::STALE;
				break;
			}
			
			if(share.length() < mCurrBlock.minshare()){
				printf("ERROR: share.length too short.\n");
				etype = proto::Reply::INVALID;
				break;
			}
			
			uint256 merkleRoot;
			merkleRoot.SetHex(share.merkle());
			
			unsigned extraNonce = mNonceMap[merkleRoot];
			if(!extraNonce){
				etype = proto::Reply::STALE;
				break;
			}
			
			unsigned nCandidateType = share.chaintype();
			if(nCandidateType > 2){
				printf("ERROR: share.chaintype invalid.\n");
				etype = proto::Reply::INVALID;
				break;
			}
			
			CBlock *pblock = &mBlockTemplate->block;
			extraNonce--;
			IncrementExtraNonce(pblock, mIndexPrev, extraNonce);
			pblock->nTime = share.time();
			pblock->nBits = share.bits();
			pblock->nNonce = share.nonce();
			
			uint256 headerHash = pblock->GetHeaderHash();
			{
				uint256 headerHashClient;
				headerHashClient.SetHex(share.hash());
				if(headerHashClient != headerHash){
					printf("ERROR: headerHashClient != headerHash.\n");
					etype = proto::Reply::INVALID;
					break;
				}
			}
			
			pblock->bnPrimeChainMultiplier.SetHex(share.multi());
			uint256 blockhash = pblock->GetHash();
			
			if(!mShares.insert(blockhash).second){
				etype = proto::Reply::DUPLICATE;
				break;
			}
			
			CBigNum bnChainOrigin = CBigNum(headerHash) * pblock->bnPrimeChainMultiplier;
			unsigned int nChainLength = 0;
			bool isblock = ProbablePrimeChainTestForMiner(bnChainOrigin, pblock->nBits, nCandidateType+1, nChainLength);
			
			nChainLength = TargetGetLength(nChainLength);
			if(nChainLength >= mCurrBlock.minshare()){
				
				if(isblock)
					isblock = CheckWork(pblock, *mWallet, mReserveKey);
				
				if(share.length() != nChainLength){
					printf("ERROR: share.length() != nChainLength.\n");
					etype = proto::Reply::INVALID;
				}
				
				mData.Clear();
				proto::Share* mshare = mData.mutable_share();
				mshare->CopyFrom(share);
				mshare->set_blockhash(blockhash.GetHex());
				mshare->set_length(nChainLength);
				mshare->set_isblock(isblock);
				
				if(isblock){
					mshare->set_genvalue(pblock->vtx[0].vout[0].nValue);
				}
				
				SendData(mData, mBackend);
				
				CBitcoinAddress address(share.addr());
				if(!address.IsValid()){
					printf("ERROR: invalid address for share: %s\n", share.addr().c_str());
					etype = proto::Reply::INVALID;
					std::string errstr = "Your payment address '";
					errstr.append(share.addr());
					errstr.append("' is INVALID!!!");
					rep.set_errstr(errstr);
					break;
				}
				
			}else{
				
				printf("ERROR: share.length too short after test: %d/%d\n", nChainLength, share.length());
				etype = proto::Reply::INVALID;
				break;
				
			}
			
		}else if(rtype == proto::Request::STATS){
			
			if(!req.has_stats()){
				printf("ERROR: !req.has_stats().\n");
				etype = proto::Reply::INVALID;
				break;
			}
			
			const proto::ClientStats& stats = req.stats();
			std::pair<std::string,uint64> key = std::make_pair(stats.addr(), stats.clientid() * stats.instanceid());
			
			std::map<std::pair<std::string,uint64>, proto::Data>::iterator iter = mStats.find(key);
			if(iter != mStats.end()){
				
				proto::ClientStats* s = mStats[key].mutable_clientstats();
				s->set_version(std::min(s->version(), stats.version()));
				s->set_cpd(s->cpd() + stats.cpd());
				s->set_errors(s->errors() + stats.errors());
				s->set_temp(std::max(s->temp(), stats.temp()));
				s->set_latency(std::max(s->latency(), stats.latency()));
				s->set_ngpus(s->ngpus() + stats.ngpus());
				/*if(s->name() != stats.name()){
					s->mutable_name()->append("+");
					s->mutable_name()->append(stats.name());
				}*/
				
			}else if(mStats.size() < 100000){
				mStats[key].mutable_clientstats()->CopyFrom(stats);
			}
			
		}
		
		break;
	}
	
	if(req.height() < mCurrHeight){
		rep.mutable_block()->CopyFrom(mCurrBlock);
	}
	
	mReqStats[std::make_pair(rtype,etype)]++;
	
	rep.set_error(etype);
	
	SendReply(rep, &msg, item->socket);
	
	zmsg_destroy(&msg);
	return 0;
	
}
Example #24
0
zmsg_t* PrimeWorker::ReceiveRequest(proto::Request& req, void* socket) {
	
	zmsg_t* msg = zmsg_recv(socket);
	zframe_t* frame = zmsg_last(msg);
	zmsg_remove(msg, frame);
	size_t fsize = zframe_size(frame);
	const byte* fbytes = zframe_data(frame);
	
	bool ok = req.ParseFromArray(fbytes, fsize);
	zframe_destroy(&frame);
	
	bool valid = false;
	while(ok){
		
		if(!proto::Request::Type_IsValid(req.type()))
			break;
		
		if(!req.has_reqnonce())
			break;
		
		if(CheckVersion(req.version()) <= 0)
			break;
		
		uint256 reqnonce;
		{
			const std::string& nonce = req.reqnonce();
			if(nonce.length() != sizeof(uint256))
				break;
			memcpy(reqnonce.begin(), nonce.c_str(), sizeof(uint256));
		}
		
		if(!CheckReqNonce(reqnonce) || !mReqNonces.insert(reqnonce).second)
			break;
		
		if(req.has_stats()){
			
			const proto::ClientStats& stats = req.stats();
			if(!isValidUTF8(stats.addr()))
				break;
			if(!isValidUTF8(stats.name()))
				break;
			if(stats.cpd() < 0 || stats.cpd() > 150. || stats.cpd() != stats.cpd())
				break;
			
		}
		
		if(req.has_share()){
			
			const proto::Share& share = req.share();
			if(!isValidUTF8(share.addr()))
				break;
			if(!isValidUTF8(share.name()))
				break;
			if(!isValidUTF8(share.hash()))
				break;
			if(!isValidUTF8(share.merkle()))
				break;
			if(!isValidUTF8(share.multi()))
				break;
			if(share.has_blockhash() && !isValidUTF8(share.blockhash()))
				break;
			
		}
		
		valid = true;
		break;
	}
	
	if(valid)
		return msg;
	else{
		mInvCount++;
		zmsg_destroy(&msg);
		return 0;
	}
	
}
Example #25
0
PRBool
GRE_GetPathFromRegKey(HKEY aRegKey,
                      const GREVersionRange *versions,
                      PRUint32 versionsLength,
                      const GREProperty *properties,
                      PRUint32 propertiesLength,
                      char* aBuffer, PRUint32 aBufLen)
{
  // Formerly, GREs were registered at the registry key
  // HKLM/Software/mozilla.org/GRE/<version> valuepair GreHome=Path.
  // Nowadays, they are registered in any subkey of
  // Software/mozilla.org/GRE, with the following valuepairs:
  //   Version=<version> (REG_SZ)
  //   GreHome=<path>    (REG_SZ or REG_EXPAND_SZ)
  //   <Property>=<value> (REG_SZ)
  //
  // Additional meta-info may be available in the future, including
  // localization info and other information which might be pertinent
  // to selecting one GRE over another.
  //
  // When a GRE is being registered, it should try to register itself at
  // HKLM/Software/mozilla.org/GRE/<Version> first, to preserve compatibility
  // with older glue. If this key is already taken (i.e. there is more than
  // one GRE of that version installed), it should append a unique number to
  // the version, for example:
  //   1.1 (already in use), 1.1_1, 1.1_2, etc...

  DWORD i = 0;
  PRUnichar buffer[MAXPATHLEN + 1];

  while (PR_TRUE) {
    PRUnichar name[MAXPATHLEN + 1];
    DWORD nameLen = MAXPATHLEN;
    if (::RegEnumKeyExW(aRegKey, i, name, &nameLen, NULL, NULL, NULL, NULL) !=
          ERROR_SUCCESS) {
        break;
    }

    HKEY subKey = NULL;
    if (::RegOpenKeyExW(aRegKey, name, 0, KEY_QUERY_VALUE, &subKey) !=
          ERROR_SUCCESS) {
        continue;
    }

    PRUnichar version[40];
    DWORD versionlen = 40;
    PRUnichar pathbuf[MAXPATHLEN + 1];
    DWORD pathlen;
    DWORD pathtype;

    PRBool ok = PR_FALSE;

    if (::RegQueryValueExW(subKey, L"Version", NULL, NULL,
                           (BYTE*) version, &versionlen) == ERROR_SUCCESS &&
          CheckVersion(version, versions, versionsLength)) {

      ok = PR_TRUE;
      const GREProperty *props = properties;
      const GREProperty *propsEnd = properties + propertiesLength;
      for (; ok && props < propsEnd; ++props) {
        pathlen = MAXPATHLEN + 1;

        AutoWString wproperty(ConvertUTF8toNewUTF16(props->property));
        AutoWString wvalue(ConvertUTF8toNewUTF16(props->value));
        if (::RegQueryValueExW(subKey, wproperty, NULL, &pathtype,
                               (BYTE*) pathbuf, &pathlen) != ERROR_SUCCESS ||
            wcscmp(pathbuf,  wvalue))
            ok = PR_FALSE;
      }

      pathlen = sizeof(pathbuf);
      if (ok &&
          (!::RegQueryValueExW(subKey, L"GreHome", NULL, &pathtype,
                              (BYTE*) pathbuf, &pathlen) == ERROR_SUCCESS ||
           !*pathbuf ||
           !CopyWithEnvExpansion(buffer, pathbuf, MAXPATHLEN, pathtype))) {
        ok = PR_FALSE;
      }
      else if (!wcsncat(buffer, L"\\" LXPCOM_DLL, aBufLen) 
#ifdef WINCE
               || (GetFileAttributesW(buffer) == INVALID_FILE_ATTRIBUTES)
#else
               || _waccess(buffer, R_OK)
#endif
               ) {
        ok = PR_FALSE;
      }
    }

    RegCloseKey(subKey);

    if (ok) {
      WideCharToMultiByte(CP_UTF8, 0, buffer, -1, aBuffer, aBufLen, NULL, NULL);
      return PR_TRUE;
    }

    ++i;
  }

  aBuffer[0] = '\0';

  return PR_FALSE;
}
Example #26
0
int WINAPI _tWinMain (HINSTANCE hThisInstance,
                    UNUSED HINSTANCE hPrevInstance,
                    UNUSED LPTSTR lpszArgument,
                    UNUSED int nCmdShow)
{
  MSG messages;            /* Here messages to the application are saved */
  WNDCLASSEX wincl;        /* Data structure for the windowclass */
  DWORD shell32_version;

  /* Initialize handlers for manangement interface notifications */
  mgmt_rtmsg_handler handler[] = {
      { ready,    OnReady },
      { hold,     OnHold },
      { log,      OnLogLine },
      { state,    OnStateChange },
      { password, OnPassword },
      { proxy,    OnProxy },
      { stop,     OnStop },
      { 0,        NULL }
  };
  InitManagement(handler);

  /* initialize options to default state */
  InitOptions(&o);

#ifdef DEBUG
  /* Open debug file for output */
  if (!(o.debug_fp = fopen(DEBUG_FILE, "w")))
    {
      /* can't open debug file */
      ShowLocalizedMsg(IDS_ERR_OPEN_DEBUG_FILE, DEBUG_FILE);
      exit(1);
    }
  PrintDebug(_T("Starting OpenVPN GUI v%S"), PACKAGE_VERSION);
#endif


  o.hInstance = hThisInstance;

  if(!GetModuleHandle(_T("RICHED20.DLL")))
    {
      LoadLibrary(_T("RICHED20.DLL"));
    }
  else
    {
      /* can't load riched20.dll */
      ShowLocalizedMsg(IDS_ERR_LOAD_RICHED20);
      exit(1);
    }

  /* Check version of shell32.dll */
  shell32_version=GetDllVersion(_T("shell32.dll"));
  if (shell32_version < PACKVERSION(5,0))
    {
      /* shell32.dll version to low */
      ShowLocalizedMsg(IDS_ERR_SHELL_DLL_VERSION, shell32_version);
      exit(1);
    }
#ifdef DEBUG
  PrintDebug(_T("Shell32.dll version: 0x%lx"), shell32_version);
#endif


  /* Parse command-line options */
  ProcessCommandLine(&o, GetCommandLine());

  /* Check if a previous instance is already running. */
  if ((FindWindow (szClassName, NULL)) != NULL)
    {
        /* GUI already running */
        ShowLocalizedMsg(IDS_ERR_GUI_ALREADY_RUNNING);
        exit(1);
    }

  if (!GetRegistryKeys()) {
    exit(1);
  }
  if (!CheckVersion()) {
    exit(1);
  }

  if (!EnsureDirExists(o.log_dir))
  {
    ShowLocalizedMsg(IDS_ERR_CREATE_PATH, _T("log_dir"), o.log_dir);
    exit(1);
  }

  BuildFileList();
  if (!VerifyAutoConnections()) {
    exit(1);
  }
  GetProxyRegistrySettings();

#ifndef DISABLE_CHANGE_PASSWORD
  /* Initialize OpenSSL */
  OpenSSL_add_all_algorithms();
  ERR_load_crypto_strings();
#endif

  /* The Window structure */
  wincl.hInstance = hThisInstance;
  wincl.lpszClassName = szClassName;
  wincl.lpfnWndProc = WindowProcedure;      /* This function is called by windows */
  wincl.style = CS_DBLCLKS;                 /* Catch double-clicks */
  wincl.cbSize = sizeof (WNDCLASSEX);

  /* Use default icon and mouse-pointer */
  wincl.hIcon = LoadLocalizedIcon(ID_ICO_APP);
  wincl.hIconSm = LoadLocalizedIcon(ID_ICO_APP);
  wincl.hCursor = LoadCursor (NULL, IDC_ARROW);
  wincl.lpszMenuName = NULL;                 /* No menu */
  wincl.cbClsExtra = 0;                      /* No extra bytes after the window class */
  wincl.cbWndExtra = 0;                      /* structure or the window instance */
  /* Use Windows's default color as the background of the window */
  wincl.hbrBackground = (HBRUSH) COLOR_3DSHADOW; //COLOR_BACKGROUND;

  /* Register the window class, and if it fails quit the program */
  if (!RegisterClassEx (&wincl))
    return 1;

  /* The class is registered, let's create the program*/
  CreateWindowEx (
           0,                   /* Extended possibilites for variation */
           szClassName,         /* Classname */
           szTitleText,         /* Title Text */
           WS_OVERLAPPEDWINDOW, /* default window */
           (int)CW_USEDEFAULT,  /* Windows decides the position */
           (int)CW_USEDEFAULT,  /* where the window ends up on the screen */
           230,                 /* The programs width */
           200,                 /* and height in pixels */
           HWND_DESKTOP,        /* The window is a child-window to desktop */
           NULL,                /* No menu */
           hThisInstance,       /* Program Instance handler */
           NULL                 /* No Window Creation data */
           );


  /* Run the message loop. It will run until GetMessage() returns 0 */
  while (GetMessage (&messages, NULL, 0, 0))
  {
    TranslateMessage(&messages);
    DispatchMessage(&messages);
  }

  /* The program return-value is 0 - The value that PostQuitMessage() gave */
  return messages.wParam;
}
Example #27
0
/**
 * @brief Takes a JsonDocument object and parses it as a Jplace document into a PlacementMap object.
 *
 * Returns true iff successful.
 */
bool JplaceProcessor::FromDocument (const JsonDocument& doc, PlacementMap& placements)
{
    placements.clear();

    // check if the version is correct
    JsonValue* val = doc.Get("version");
    if (!val) {
        LOG_WARN << "Jplace document does not contain a valid version number at key 'version'."
                 << "Now continuing to parse in the hope that it still works.";
    }
    if (!CheckVersion(val->ToString())) {
        LOG_WARN << "Jplace document has version '" << val->ToString() << "', however this parser "
                 << "is written for version " << GetVersion() << " of the Jplace format. "
                 << "Now continuing to parse in the hope that it still works.";
    }

    // find and process the reference tree
    val = doc.Get("tree");
    if (!val || !val->IsString() || !NewickProcessor::FromString(val->ToString(), placements.tree)) {
        LOG_WARN << "Jplace document does not contain a valid Newick tree at key 'tree'.";
        return false;
    }

    // create a map from edge nums to the actual edge pointers, for later use when processing
    // the pqueries. we do not use PlacementMap::EdgeNumMap() here, because we need to do extra
    // checking for validity first!
    std::unordered_map<int, PlacementTree::EdgeType*> edge_num_map;
    for (
        PlacementTree::ConstIteratorEdges it = placements.tree.BeginEdges();
        it != placements.tree.EndEdges();
        ++it
    ) {
        PlacementTree::EdgeType* edge = *it;
        if (edge_num_map.count(edge->edge_num) > 0) {
            LOG_WARN << "Jplace document contains a tree where the edge num tag '"
                     << edge->edge_num << "' is used more than once.";
            return false;
        }
        edge_num_map.emplace(edge->edge_num, edge);
    }

    // get the field names and store them in array fields
    val = doc.Get("fields");
    if (!val || !val->IsArray()) {
        LOG_WARN << "Jplace document does not contain field names at key 'fields'.";
        return false;
    }
    JsonValueArray* fields_arr = JsonValueToArray(val);
    std::vector<std::string> fields;
    bool has_edge_num = false;
    for (JsonValue* fields_val : *fields_arr) {
        if (!fields_val->IsString()) {
            LOG_WARN << "Jplace document contains a value of type '" << fields_val->TypeToString()
                     << "' instead of a string with a field name at key 'fields'.";
            return false;
        }

        // check field validity
        std::string field = fields_val->ToString();
        if (field == "edge_num"      || field == "likelihood"     || field == "like_weight_ratio" ||
            field == "distal_length" || field == "pendant_length" || field == "parsimony"
        ) {
            for (std::string fn : fields) {
                if (fn == field) {
                    LOG_WARN << "Jplace document contains field name '" << field << "' more than "
                             << "once at key 'fields'.";
                    return false;
                }
            }
            fields.push_back(field);
        } else {
            LOG_WARN << "Jplace document contains a field name '" << field << "' "
                     << "at key 'fields', which is not used by this parser and thus skipped.";
        }
        has_edge_num |= (field == "edge_num");
    }
    if (!has_edge_num) {
        LOG_WARN << "Jplace document does not contain necessary field 'edge_num' at key 'fields'.";
        return false;
    }

    // find and process the pqueries
    val = doc.Get("placements");
    if (!val || !val->IsArray()) {
        LOG_WARN << "Jplace document does not contain pqueries at key 'placements'.";
        return false;
    }
    JsonValueArray* placements_arr = JsonValueToArray(val);
    for (JsonValue* pqry_val : *placements_arr) {
        if (!pqry_val->IsObject()) {
            LOG_WARN << "Jplace document contains a value of type '" << pqry_val->TypeToString()
                     << "' instead of an object with a pquery at key 'placements'.";
            return false;
        }
        JsonValueObject* pqry_obj = JsonValueToObject(pqry_val);
        if (!pqry_obj->Has("p") || !pqry_obj->Get("p")->IsArray()) {
            LOG_WARN << "Jplace document contains a pquery at key 'placements' that does not "
                     << "contain an array of placements at sub-key 'p'.";
            return false;
        }

        // create new pquery
        Pquery* pqry = new Pquery();

        // process the placements and store them in the pquery
        JsonValueArray* pqry_p_arr = JsonValueToArray(pqry_obj->Get("p"));
        for (JsonValue* pqry_p_val : *pqry_p_arr) {
            if (!pqry_p_val->IsArray()) {
                LOG_WARN << "Jplace document contains a pquery with invalid placement at key 'p'.";
                return false;
            }
            JsonValueArray* pqry_fields = JsonValueToArray(pqry_p_val);
            if (pqry_fields->size() != fields.size()) {
                LOG_WARN << "Jplace document contains a placement fields array with different size "
                         << "than the fields name array.";
                return false;
            }

            // process all fields of the placement
            PqueryPlacement* pqry_place = new PqueryPlacement();
            for (size_t i = 0; i < pqry_fields->size(); ++i) {
                // up to version 3 of the jplace specification, the p-fields in a jplace document
                // only contain numbers (float or int),so we can do this check here once for all
                // fields, instead of repetition for everyfield. if in the future there are fields
                // with non-number type, this check has to go into the single field assignments.
                if (!pqry_fields->at(i)->IsNumber()) {
                    LOG_WARN << "Jplace document contains pquery where field " << fields[i]
                             << " is of type '" << pqry_fields->at(i)->TypeToString()
                             << "' instead of a number.";
                    return false;
                }

                // switch on the field name to set the correct value
                double pqry_place_val = JsonValueToNumber(pqry_fields->at(i))->value;
                if        (fields[i] == "edge_num") {
                    pqry_place->edge_num          = pqry_place_val;
                    if (edge_num_map.count(pqry_place_val) == 0) {
                        LOG_WARN << "Jplace document contains a pquery where field 'edge_num' "
                                 << "has value '" << pqry_place_val << "', which is not marked "
                                 << "in the given tree as an edge num.";
                        return false;
                    }
                    pqry_place->edge = edge_num_map.at(pqry_place_val);
                    pqry_place->edge->placements.push_back(pqry_place);
                } else if (fields[i] == "likelihood") {
                    pqry_place->likelihood        = pqry_place_val;
                } else if (fields[i] == "like_weight_ratio") {
                    pqry_place->like_weight_ratio = pqry_place_val;
                } else if (fields[i] == "distal_length") {
                    // the jplace format uses distal length, but we use proximal,
                    // so we need to convert here.
                    pqry_place->proximal_length   = pqry_place->edge->branch_length - pqry_place_val;
                } else if (fields[i] == "pendant_length") {
                    pqry_place->pendant_length    = pqry_place_val;
                } else if (fields[i] == "parsimony") {
                    pqry_place->parsimony         = pqry_place_val;
                }
            }
            pqry_place->pquery = pqry;
            pqry->placements.push_back(pqry_place);
        }

        // check name/named multiplicity validity
        if (pqry_obj->Has("n") && pqry_obj->Has("nm")) {
            LOG_WARN << "Jplace document contains a pquery with both an 'n' and an 'nm' key.";
            return false;
        }
        if (!pqry_obj->Has("n") && !pqry_obj->Has("nm")) {
            LOG_WARN << "Jplace document contains a pquery with neither an 'n' nor an 'nm' key.";
            return false;
        }

        // process names
        if (pqry_obj->Has("n")) {
            if (!pqry_obj->Get("n")->IsArray()) {
                LOG_WARN << "Jplace document contains a pquery with key 'n' that is not array.";
                return false;
            }

            JsonValueArray* pqry_n_arr = JsonValueToArray(pqry_obj->Get("n"));
            for (JsonValue* pqry_n_val : *pqry_n_arr) {
                if (!pqry_n_val->IsString()) {
                    LOG_WARN << "Jplace document contains a pquery where key 'n' has a "
                             << "non-string field.";
                    return false;
                }

                PqueryName* pqry_name   = new PqueryName();
                pqry_name->name         = pqry_n_val->ToString();
                pqry_name->multiplicity = 0.0;
                pqry_name->pquery = pqry;
                pqry->names.push_back(pqry_name);
            }
        }

        // process named multiplicities
        if (pqry_obj->Has("nm")) {
            if (!pqry_obj->Get("nm")->IsArray()) {
                LOG_WARN << "Jplace document contains a pquery with key 'nm' that is not array.";
                return false;
            }

            JsonValueArray* pqry_nm_arr = JsonValueToArray(pqry_obj->Get("nm"));
            for (JsonValue* pqry_nm_val : *pqry_nm_arr) {
                if (!pqry_nm_val->IsArray()) {
                    LOG_WARN << "Jplace document contains a pquery where key 'nm' has a "
                             << "non-array field.";
                    return false;
                }

                JsonValueArray * pqry_nm_val_arr = JsonValueToArray(pqry_nm_val);
                if (pqry_nm_val_arr->size() != 2) {
                    LOG_WARN << "Jplace document contains a pquery where key 'nm' has an array "
                             << "field with size != 2 (one for the name, one for the multiplicity).";
                    return false;
                }
                if (!pqry_nm_val_arr->at(0)->IsString()) {
                    LOG_WARN << "Jplace document contains a pquery where key 'nm' has an array "
                             << "whose first value is not a string for the name.";
                    return false;
                }
                if (!pqry_nm_val_arr->at(1)->IsNumber()) {
                    LOG_WARN << "Jplace document contains a pquery where key 'nm' has an array "
                             << "whose second value is not a number for the multiplicity.";
                    return false;
                }

                PqueryName* pqry_name   = new PqueryName();
                pqry_name->name         = pqry_nm_val_arr->at(0)->ToString();
                pqry_name->multiplicity = JsonValueToNumber(pqry_nm_val_arr->at(1))->value;
                if (pqry_name->multiplicity < 0.0) {
                    LOG_WARN << "Jplace document contains pquery with negative multiplicity at "
                             << "name '" << pqry_name->name << "'.";
                }
                pqry_name->pquery = pqry;
                pqry->names.push_back(pqry_name);
            }
        }

        // finally, add the pquery to the placements object
        placements.pqueries.push_back(pqry);
    }

    // check if there is metadata
    val = doc.Get("metadata");
    if (val && val->IsObject()) {
        JsonValueObject* meta_obj = JsonValueToObject(val);
        for (JsonValueObject::ObjectPair meta_pair : *meta_obj) {
            placements.metadata[meta_pair.first] = meta_pair.second->ToString();
        }
    }

    return true;
}
bool CMusikLibrary::Load()
{
	wxString sFilename = MUSIK_DB_FILENAME;
		
	//--- look for database.. if need be, create it and create tables ---//
	static	const char *szCreateVersionQuery =
		"CREATE TABLE IF NOT EXISTS version ( " 	
		"name, major, majorsub ,minor, minorsub "
		" );";
	
	//--- create the tables ---//
	static const char *szCreateSongTableQuery  = 
			"CREATE TABLE IF NOT EXISTS songs ( "	
			"songid INTEGER PRIMARY KEY, "
			"format INTEGER, "		
			"vbr INTEGER, "			
			"filename TEXT NOT NULL UNIQUE, "	
			"artist TEXT, "	
			"title TEXT, "	
			"album TEXT, "	
			"tracknum INTEGER, "	
			"year INTEGER, "		
			"genre TEXT, "	
			"rating INTEGER, "		
			"bitrate INTEGER, "	
			"lastplayed REAL, "	
			"notes TEXT, "	
			"timesplayed INTEGER , "	
			"duration INTEGER, "	
			"timeadded REAL, "	
			"filesize INTEGER, "	
			"dirty INTEGER, "
            "modified REAL"
			" );";
	const char* szCreateSongTableIdxQuery =
			"CREATE INDEX IF NOT EXISTS songs_title_idx on songs (title);"
			"CREATE UNIQUE INDEX IF NOT EXISTS songs_filename_idx on songs (filename);"
			"CREATE INDEX IF NOT EXISTS songs_artist_idx on songs (artist);"
			"CREATE INDEX IF NOT EXISTS songs_album_idx on songs (album);"
			"CREATE INDEX IF NOT EXISTS songs_genre_idx on songs (genre);"
            "CREATE INDEX IF NOT EXISTS songs_year_idx on songs (year);"
//			"CREATE INDEX IF NOT EXISTS songs_tracknum_idx on songs (tracknum);"
			"CREATE INDEX IF NOT EXISTS songs_artist_album_tracknum_idx on songs (artist collate nocase,album collate nocase,tracknum);"
			"CREATE INDEX IF NOT EXISTS songs_timeadded_idx on songs (timeadded);"
			"CREATE INDEX IF NOT EXISTS songs_lastplayed_idx on songs (lastplayed);"
			;
	static	const char *szCreateSongHistoryQuery =
			"CREATE TABLE IF NOT EXISTS songhistory ( "	
				"songid number(10), "
				"date_played timestamp , "
				"percent_played number(10),"
				"selected_by_user number(1) "
				" );";

	static const char* szCreateSongHistoryTableIdxQuery =
		"CREATE INDEX IF NOT EXISTS songhistory_songid_idx on songhistory (songid);"
		"CREATE INDEX IF NOT EXISTS songhistory_date_played_idx on songhistory (date_played);"
		"CREATE INDEX IF NOT EXISTS songhistory_percent_played_idx on songhistory (percent_played);"
		;
	wxLogNull lognull;
    Shutdown();
    bool bConvertFromDB2 = !wxFileExists(sFilename) && wxFileExists(MUSIK_DB_FILENAME2);
    m_pDB.reset(new MusikDb_Sqlite3());
	if(m_pDB.get() && m_pDB->Open(sFilename))
	{
#ifdef __WXMSW__
        m_pDB->Exec("PRAGMA page_size=4096;");
#endif
		m_pDB->Exec("PRAGMA temp_store = \"memory\";");
		// always create table, if it exists an error will be returned by Exec(), but we dont care.
		m_pDB->Exec( szCreateVersionQuery);
		m_pDB->Exec( szCreateSongTableQuery);
		m_pDB->Exec( szCreateSongHistoryQuery);
        if(bConvertFromDB2)
            ConvertFromDB2();
        m_pDB->Exec( szCreateSongTableIdxQuery);
		m_pDB->Exec( szCreateSongHistoryTableIdxQuery);
		m_pDB->Exec( "CREATE TRIGGER song_deleted_trigger DELETE ON songs " 
							"BEGIN "
							"DELETE FROM songhistory WHERE songid = old.songid;"
							"END;");


		//m_pDB->Exec( "PRAGMA synchronous = OFF;");
		SetCacheSize(wxGetApp().Prefs.nDBCacheSize);
		CheckVersion();
		SetAutoDjFilter(wxGetApp().Prefs.sAutoDjFilter );
		m_pDB->Exec( "CREATE VIEW valid_albums as select album,artist,most_lastplayed from ("
			"select album,artist,sum(duration) as sum_duration,max(lastplayed+0) as most_lastplayed "  
			"from songs where album != '' group by album) where sum_duration > 1500000;"
			);	
		m_pDB->Exec("CREATE VIEW autodj_albums as select album,artist,most_lastplayed from ("
			"select album,artist,sum(duration) as sum_duration,max(lastplayed+0) as most_lastplayed "  
			"from autodj_songs where album != '' group by album) where sum_duration > 1500000;"
			);	
        if(m_pMasterLibrary == NULL)
            m_pDB->SetBusyHandler(m_pBusyHandler.get());
	    return true;
    }
	return false;
}
Example #29
0
UINT32 GetChunk(BYTE *buffer, UINT32 nLen)
{
	UINT8 *p, *pblock;
	UINT32 chunk_pos;
	struct sto_device *sto_dev = NULL;
	UINT8 sVer[16], hVer[16];
	INT32 i = 0;
	char strTmp[30];
#if (defined HDCP_IN_FLASH ||defined DIVX_CERT_ENABLE)
	INT32 temp_slave_blocks_number=0;
	CHUNK_HEADER *temp_pslave_list = NULL;
#endif
	
	switch((unsigned int)buffer[0])
	{
		case 1:
		case 2:
		case 7:
		case 10:
			slave_Flash_type = 0x80000;	//flash size
			break;
		case 3:
		case 4:
		case 8:
		case 9:
		case 11:
		case 13:
			slave_Flash_type = 0x100000;
			break;
		case 5:
		case 6:
		case 12:
		case 14:
		case 15:
		case 16:
		case 25:
		case 28:
		case 30:
			slave_Flash_type = 0x200000;
			break;
		case 17:
		case 18:
		case 19:
		case 33:
			slave_Flash_type = 0x400000;
			break;
		default:
			slave_Flash_type = 0x200000;/*For unkown flash type,default is 2M*/
			//return !SUCCESS;
	}

	slave_status = (unsigned int)buffer[1];
	if(slave_status==0)
		slave_blocks_number = (nLen -2)/CHUNK_HEADER_SIZE;
	else
		slave_blocks_number = 1;

	pslave_list= (CHUNK_HEADER *)MALLOC(sizeof(CHUNK_HEADER)*slave_blocks_number);
	if (pslave_list == NULL)
		return !SUCCESS;
	MEMSET((void *)pslave_list,0,sizeof(CHUNK_HEADER)*slave_blocks_number);

#if (defined HDCP_IN_FLASH ||defined DIVX_CERT_ENABLE)
#ifdef  HDCP_IN_FLASH
	if(m_allcode_include_bootloader==0)
#endif		
		{
			temp_pslave_list= (CHUNK_HEADER *)MALLOC(sizeof(CHUNK_HEADER)*slave_blocks_number);
			if (temp_pslave_list == NULL)
				return !SUCCESS;
			MEMSET((void *)temp_pslave_list,0,sizeof(CHUNK_HEADER)*slave_blocks_number);
		}
#endif

	pblock = &buffer[2];
	for(i=0; i<slave_blocks_number; i++)
	{
		p = pblock + CHUNK_ID;
		pslave_list[i].id = (*p<<24)+(*(p+1)<<16)+(*(p+2)<<8)+(*(p+3)<<0);

		p = pblock + CHUNK_LENGTH;
		pslave_list[i].len = (*p<<24)+(*(p+1)<<16)+(*(p+2)<<8)+(*(p+3)<<0);

		p = pblock + CHUNK_OFFSET;
		pslave_list[i].offset = (*p<<24)+(*(p+1)<<16)+(*(p+2)<<8)+(*(p+3)<<0);

		p = pblock + CHUNK_CRC;
		pslave_list[i].crc = (*p<<24)+(*(p+1)<<16)+(*(p+2)<<8)+(*(p+3)<<0);

		p = pblock + CHUNK_NAME;
		STRCPY((char *)pslave_list[i].name, (char *)p);

		p = pblock + CHUNK_VERSION;
		STRCPY((char *)pslave_list[i].version, (char *)p);

		p = pblock + CHUNK_TIME;
		STRCPY((char *)pslave_list[i].time, (char *)p);

#if (defined HDCP_IN_FLASH ||defined DIVX_CERT_ENABLE)
#ifdef HDCP_IN_FLASH
		if(m_allcode_include_bootloader==0)
#endif		
		{
			UINT32 special_type = 0;

#ifdef HDCP_IN_FLASH		
			if(pslave_list[i].id == HDCPKEY_CHUNK_ID)
			{
				special_type =1;
			}
#endif			
#ifdef DIVX_CERT_ENABLE		
			if(pslave_list[i].id == DIVX_CHUCK_ID)
			{
				special_type =1;
			}
#endif			
			if(special_type!=1)
			{
				MEMCPY((temp_pslave_list+temp_slave_blocks_number),(pslave_list+i),sizeof(CHUNK_HEADER));
				temp_slave_blocks_number++;			
			}
			else
			{ 
				if(i > 0)
				{
					temp_pslave_list[i-1].offset=(temp_pslave_list[i-1].offset+pslave_list[i].offset);
				}
			}
		}
#endif

		pblock += CHUNK_HEADER_SIZE;
	}

#if (defined HDCP_IN_FLASH ||defined DIVX_CERT_ENABLE)
#ifdef  HDCP_IN_FLASH
		if(m_allcode_include_bootloader==0)
#endif		
		{
			FREE(pslave_list);
			slave_blocks_number=temp_slave_blocks_number;
			pslave_list = (CHUNK_HEADER *)MALLOC(sizeof(CHUNK_HEADER)*slave_blocks_number);
			MEMCPY(pslave_list,temp_pslave_list,sizeof(CHUNK_HEADER)*slave_blocks_number);
			FREE(temp_pslave_list);
		}
#endif


	STRCPY(sVer, pslave_list[0].version);
	chunk_pos = sto_chunk_goto(&pblock_list[0].id, 0xFFFFFFFF, 1);
	sto_dev = (struct sto_device*)dev_get_by_id(HLD_DEV_TYPE_STO, 0);
	sto_open(sto_dev);
	sto_lseek(sto_dev, chunk_pos+CHUNK_VERSION, STO_LSEEK_SET);
	sto_read(sto_dev, hVer, 16);
	//sto_close(sto_dev);

#ifdef FORCE_UPGRADE_OLD_PROTOCOL_BOOTLOADER
	if(g_protocol_version < NEW_PROTOCOL_VERSION)
		return SUCCESS;
#endif
	if(CheckVersion(sVer, hVer) != SUCCESS)
	{
		ComUniStrToAsc((UINT8 *)OSD_GetUnicodeString(RS_STB_VERSION_NOT_COMPATIBLE),strTmp);
		callback_fun(2,0,strTmp);
		return !SUCCESS;
	}
}
Example #30
0
//----------------------------------------------------------------------------------
//设置游戏状态
bool CClientGameDlg::SetGameStation(void * pStationData, UINT uDataSize)
{
	m_iMyLogDesk = GetMeUserInfo()->bDeskStation;
	switch (GetStationParameter())
	{
	case GS_WAIT_SETGAME:	//游戏没有开始状态
	case GS_WAIT_AGREE:	//等待同意状态
	case GS_WAIT_NEXT:
		{	
			GameStation_2 * pGameStation=(GameStation_2 *)pStationData;
			//设置数据
			m_iThinkTime=pGameStation->iThinkTime;
			m_iBeginTime=pGameStation->iBeginTime;

			//函数调用
			CheckVersion(pGameStation->iVersion,pGameStation->iVersion2);	

			m_iBeginTime=pGameStation->iBeginTime;						//开始时间
			m_byBoBoTime=pGameStation->byBoBoTime;						//设置簸簸时间;
			m_iThinkTime=pGameStation->iThinkTime;						//思考时间
			m_bySeparateCardTime = pGameStation->bySeparateCardTime;	//分牌时间
			m_i64BoBase = pGameStation->i64BoBase;						//簸底
			m_i64SmallBobo = pGameStation->i64SmallBobo;				//最小簸簸
			m_i64TempBobo = m_i64SmallBobo;								//最小簸簸(临时变量)
			m_i64FrontNote = 0;
			memcpy(m_bUserReady , pGameStation->bUserReady ,sizeof(m_bUserReady)) ;
			SetGameTimer(GetMeUserInfo()->bDeskStation,MyRand()% 6 +2,ID_BEGIN_TIME);
			return TRUE;
		}
	case GS_SEND_CARD:	//发牌状态
		{
			GameStation_3 * pGameStation=(GameStation_3 *)pStationData;
			//函数调用
			CheckVersion(pGameStation->iVersion,pGameStation->iVersion2);
			BYTE	byTimeRest;
			m_iBeginTime=pGameStation->iBeginTime;						//开始时间
			m_byBoBoTime=pGameStation->byBoBoTime;						//设置簸簸时间;
			m_iThinkTime=pGameStation->iThinkTime;						//思考时间
			m_bySeparateCardTime = pGameStation->bySeparateCardTime;	//分牌时间
			m_i64BoBase = pGameStation->i64BoBase;						//簸底
			m_i64SmallBobo = pGameStation->i64SmallBobo;				//最小簸簸
			m_i64TempBobo = m_i64SmallBobo;								//最小簸簸(临时变量)
			m_bNtPeople = pGameStation->iUpGradePeople;					//庄家位置
			m_bGameStation = pGameStation->bGameStation;				//大步骤
			m_byGameStation = pGameStation->byGameStation;				//动作小分解
			byTimeRest = pGameStation->iTimeRest;
			m_i64FrontNote = 0;
			::CopyMemory(m_i64Bobo,pGameStation->i64Bobo,sizeof(m_i64Bobo));			//制簸簸数值
			::CopyMemory(m_bPlayer,pGameStation->bPlayer,sizeof(m_bPlayer));			//标记是否是开始时所进入的人
			if(pGameStation->byGameStation == GS_SEND_CARD_TIME)						//发牌时间
			{
				::CopyMemory(m_iDeskCardCount,pGameStation->byAlreadySendCardCount,sizeof(m_iDeskCardCount));	//已经发的牌张数
				::CopyMemory(m_iUserCardCount,pGameStation->iUserCardCount,sizeof(m_iUserCardCount));			//牌总张数
				::CopyMemory(m_bSendCardCount,pGameStation->byAlreadySendCardCount,sizeof(m_bSendCardCount));	//已经发的牌张数
				for(int i = 0x00;i < PLAY_COUNT;i ++)
				{
					memset(m_iDeskCard[i],0x00,sizeof(m_iDeskCard[i]));
					::memcpy(m_iDeskCard[i],pGameStation->iUserCard[i],sizeof(BYTE)*m_iDeskCardCount[i]);
				}
			}
			return TRUE;
		}
	case GS_PLAY_GAME:	//游戏进行中
		{
			GameStation_4 * pGameStation=(GameStation_4 *)pStationData;
			//函数调用
			CheckVersion(pGameStation->iVersion,pGameStation->iVersion2);
			//设置数据
			BYTE	byTimeRest;
			m_iBeginTime=pGameStation->iBeginTime;							//开始时间
			m_byBoBoTime=pGameStation->byBoBoTime;							//设置簸簸时间
			m_iThinkTime=pGameStation->iThinkTime;							//思考时间
			m_bySeparateCardTime = pGameStation->bySeparateCardTime;		//分牌时间
			m_i64BoBase = pGameStation->i64BoBase;							//簸底
			m_i64SmallBobo = pGameStation->i64SmallBobo;					//最小簸簸
			m_i64TempBobo = m_i64SmallBobo;									//最小簸簸(临时保存)
			m_bNtPeople = pGameStation->bNtPeople;							//庄家
			m_byGameStation = pGameStation->byGameStation;					//动作小分解
			m_iNowOutPeople=pGameStation->iOutCardPeople;					//现在出牌的用户
			m_i64FrontNote = pGameStation->iCurNote;						//前家所下的注
			m_iFirstOutPeople=pGameStation->iFirstOutPeople;				//第一家出的牌
			int iRestTime = pGameStation->iTimeRest;
			m_bSendCardPos = pGameStation->iFirstOutPeople;
			m_iFirstOutPeople=pGameStation->iFirstOutPeople;
			byTimeRest = pGameStation->iTimeRest;							//实际还有的时间
			//保存当前用户下注总额
			::CopyMemory(m_i64UseAllNote,pGameStation->iTotalGameNote,sizeof(m_i64UseAllNote));		//用户所下的总注
			::CopyMemory(m_i64Bobo,pGameStation->i64Bobo,sizeof(m_i64Bobo));						//设置的簸簸数
			::CopyMemory(m_bPlayer,pGameStation->bPlayer,sizeof(m_bPlayer));						//标记是否是开始时所进入的人
			::CopyMemory(m_i64NoteMoney,pGameStation->i64NoteMoney,sizeof(m_i64NoteMoney));			//用户所下注筹码信息
			::CopyMemory(m_i64UseAllNote,pGameStation->iTotalGameNote,sizeof(m_i64UseAllNote));		//各玩家所下的注
			::CopyMemory(m_bSendCardCount,pGameStation->byAlreadySendCardCount,sizeof(m_bSendCardCount));	//已经发牌的张数
			::CopyMemory(m_iDeskCardCount,pGameStation->byAlreadySendCardCount,sizeof(m_iDeskCardCount));	//桌面牌的张数
			::CopyMemory(m_iUserCard,pGameStation->iUserCard,sizeof(m_iUserCard));							//用户手中的牌
			::CopyMemory(m_iUserCardCount,pGameStation->iUserCardCount,sizeof(m_iUserCardCount));			//用户手中牌的数量
			::CopyMemory(m_byUserOperatorType,pGameStation->byOperationState,sizeof(m_byUserOperatorType));	//玩家的操作
			::CopyMemory(m_byNoteTime,pGameStation->byNoteTime,sizeof(m_byNoteTime));						//已经下注的次数
			for(int i = 0x00;i< PLAY_COUNT;i ++)							//复制牌数据
			{
				for(int j = 0x02;j < m_bSendCardCount[i];j++)
					m_iDeskCard[i][j] = m_iUserCard[i][j];
			}
			return TRUE;
		}
	}
	return false;
}