bool SetCheckpointPrivKey(std::string strPrivKey) { // Test signing a sync-checkpoint with genesis block CSyncCheckpoint checkpoint; checkpoint.hashCheckpoint = !fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet; CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION); sMsg << (CUnsignedSyncCheckpoint)checkpoint; checkpoint.vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end()); std::vector<unsigned char> vchPrivKey = ParseHex(strPrivKey); CKey key; key.SetPrivKey(CPrivKey(vchPrivKey.begin(), vchPrivKey.end())); // if key is not correct openssl may crash if (!key.Sign(Hash(checkpoint.vchMsg.begin(), checkpoint.vchMsg.end()), checkpoint.vchSig)) return false; // Test signing successful, proceed CSyncCheckpoint::strMasterPrivKey = strPrivKey; return true; }
int CMDIfileManager::_RemoveWindowFromAList(CMDI_LIST *pList,CMDIFrame *p) { CMDI_LIST::iterator itr; CMDI_LIST::iterator itrEnd = pList->end(); int nRtn = 0; for(itr = pList->begin(); (itr != itrEnd) && (p != *itr); ++itr) {;} if(itr != itrEnd) { pList->erase(itr); nRtn = 1; } else { wxString sMsg(wxS("CMDIfileManager::_RemoveWindowFromAList - did not find window")); wxASSERT_MSG(0,sMsg); } return nRtn; }
void CUse3Dlg::OnBnClickedButton6() // 智能指针的释放 { ::CoInitialize( NULL ); // 如果在这里进行 COM 初始化,要注意智能指针的释放 CComQIPtr < IFun, &IID_IFun > spFun; HRESULT hr = spFun.CoCreateInstance( CLSID_Fun ); ASSERT( SUCCEEDED( hr ) ); // 为了简单起见,不再使用 if 判断 HRESULT 了。IFun::Add() 也没有调用 CComBSTR s1( "Hello" ), s2( " world" ), s3; hr = spFun->Cat( s1, s2, &s3 ); ASSERT( SUCCEEDED( hr ) ); CString sMsg( s3 ); AfxMessageBox( sMsg ); // spFun->Release(); // 大错特错!!! spFun.Release(); // 正解 ::CoUninitialize(); }
bool Registrar::CreateEventHandlerKey() { CRegKey reg; CStdString sKey = GetDM5RegistryKey(); LONG lRes = reg.Create(HKEY_LOCAL_MACHINE, sKey.c_str()); if (lRes == ERROR_SUCCESS) { reg.Close(); return true; } else { CStdString sMsg(_T("Unable to Create registry key with the following information")); sMsg += _T(" KEY: ") + sKey; sMsg += _T(" Error: ") + DecodeError(lRes); LOG_WS_ERROR(sMsg.c_str()); } return false; }
bool SetCheckpointPrivKey(std::string strPrivKey) { // Test signing a sync-checkpoint with genesis block CSyncCheckpoint checkpoint; checkpoint.hashCheckpoint = hashGenesisBlock; CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION); sMsg << (CUnsignedSyncCheckpoint)checkpoint; checkpoint.vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end()); CBitcoinSecret vchSecret; if (!vchSecret.SetString(strPrivKey)) return error("SendSyncCheckpoint: Checkpoint master key invalid"); CKey key; bool fCompressed; CSecret secret = vchSecret.GetSecret(fCompressed); key.SetSecret(secret, fCompressed); // if key is not correct openssl may crash if (!key.Sign(Hash2(checkpoint.vchMsg.begin(), checkpoint.vchMsg.end()), checkpoint.vchSig)) return false; // Test signing successful, proceed CSyncCheckpoint::strMasterPrivKey = strPrivKey; return true; }
bool nwxLockFile::Unlock(const wxString &sFileName) { set<wxString>::iterator itr = m_setFileName.find(sFileName); bool bRtn = false; if(itr != m_setFileName.end()) { wxString sFileLockName = GetLockFileName(sFileName); bRtn = true; // file was locked by this instance if(!wxFileExists(sFileLockName)) {;} // OK else if(!wxRemoveFile(sFileLockName)) { // have a problem removing this file, log the error and still return true time_t t; time(&t); wxString sMsg(_T("Cannot remove lock file: ")); sMsg.Append(sFileLockName); wxLog::OnLog(wxLOG_Message,(const wxChar *)sMsg,t); wxASSERT_MSG(false,sMsg); } m_setFileName.erase(itr); } return bRtn; }
bool cGameCell::ContainsObject( cGameEnt* pObj ) { int i; point3 loc = MRetToPoint( pObj->ProcMsg( sMsg( msgGetLoc ) ) ); float radius = 2.f; // FIXME: not checking to see if we're inside a portal. for( i=0; i<m_polyList.size(); i++ ) { if( ptBack == m_polyList[i].m_plane.TestPoint(loc) ) { return false; } } for( i=0; i<m_portalList.size(); i++ ) { if( ptBack == m_portalList[i].m_plane.TestPoint(loc) ) { return false; } } return true; }
bool SendSyncCheckpoint(uint256 hashCheckpoint) { CSyncCheckpoint checkpoint; checkpoint.hashCheckpoint = hashCheckpoint; CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION); sMsg << (CUnsignedSyncCheckpoint)checkpoint; checkpoint.vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end()); if (CSyncCheckpoint::strMasterPrivKey.empty()) return error("SendSyncCheckpoint: Checkpoint master private key unavailable."); std::vector<unsigned char> vchPrivKey = ParseHex(CSyncCheckpoint::strMasterPrivKey); CKey key; // if key is not correct openssl may crash key.Set(vchPrivKey.begin(), vchPrivKey.end(), false); if (!key.IsValid()) return error("SendSyncCheckpoint: failed to set private key."); if (!key.Sign(Hash(checkpoint.vchMsg.begin(), checkpoint.vchMsg.end()), checkpoint.vchSig)) return error("SendSyncCheckpoint: Unable to sign checkpoint, check private key?"); if(!checkpoint.ProcessSyncCheckpoint(NULL)) { printf("WARNING: SendSyncCheckpoint: Failed to process checkpoint.\n"); return false; } printf("SendSyncCheckpoint: about to relay checkpoint.\n"); // Relay checkpoint { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) checkpoint.RelayTo(pnode); } return true; }
bool SendSyncCheckpoint(uint256 hashCheckpoint) { LogPrintf("SendSyncCheckpoint: hashCheckpoint=%s\n", hashCheckpoint.ToString().c_str()); CSyncCheckpoint checkpoint; checkpoint.hashCheckpoint = hashCheckpoint; CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION); sMsg << (CUnsignedSyncCheckpoint)checkpoint; checkpoint.vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end()); if (CSyncCheckpoint::strMasterPrivKey.empty()) return error("SendSyncCheckpoint: Checkpoint master key unavailable."); CBitcoinSecret vchSecret; if (!vchSecret.SetString(CSyncCheckpoint::strMasterPrivKey)) return error("SendSyncCheckpoint: Checkpoint master key invalid"); // bool fCompressed; // CSecret secret = vchSecret.GetSecret(fCompressed); CKey secret = vchSecret.GetKey(); // key.SetSecret(secret, fCompressed); // if key is not correct openssl may crash CKey key(secret); if (!key.Sign(Hash(checkpoint.vchMsg.begin(), checkpoint.vchMsg.end()), checkpoint.vchSig)) return error("SendSyncCheckpoint: Unable to sign checkpoint, check private key?"); if(!checkpoint.ProcessSyncCheckpoint(NULL)) { LogPrintf("WARNING: SendSyncCheckpoint: Failed to process checkpoint.\n"); return false; } // Relay checkpoint { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) checkpoint.RelayTo(pnode); } return true; }
DWORD CSage::Start() { USES_CONVERSION; //CEgRegKey key; TCHAR pModName [1024] = { 0 }; //detecting the module version ::GetModuleFileName( NULL, pModName, sizeof(pModName) ); CModuleVersion ver; ver.GetModuleVersionInfo(pModName); std::string sMsg("Fail to Setup user groups."); UserGroups clParams; m_nGroupsCount = GetCommandLineParams(clParams); if (m_SageConnector.SetGroups(clParams) == E_FAIL) { CTracer::TraceError(E_FAIL, sMsg.c_str()); return E_FAIL; } TCHAR pVer[100] = { 0 }; ver.GetValue(_T("ProductVersion"), pVer); CTracer::Trace(_T("------------------------------------")); CTracer::Trace(_T("FIX Interface Connector v.%s"), pVer ); CTracer::Trace(_T("Press Ctrl + C to stop the server...")); CTracer::Trace(_T("------------------------------------")); DWORD dwFlags; if(GetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), &dwFlags)) { dwFlags &= ~(ENABLE_QUICK_EDIT | ENABLE_INSERT_MODE); SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), dwFlags); } m_hStopApplication = CreateEvent(NULL, TRUE, FALSE, _T("E53B916B-95BA-4e1f-917A-338580A74D91")); if (m_hStopApplication == NULL) { return CTracer::TraceError(); } BOOL bRes = SetConsoleCtrlHandler(HandlerRoutine, TRUE); if (bRes == FALSE) return CTracer::TraceError(); CTracer::Trace(_T("Starting Sage connector...")); DWORD dwRes = m_SageConnector.Start(); if (dwRes) { CTracer::Trace(_T("Failed to start Sage connector.")); return dwRes; } CTracer::Trace(_T("FIX Interface connector started.")); CTracer::Trace(_T("Server started.")); return 0; }
wxWindow* wxWindow::CreateWindowFromHWND ( wxWindow* pParent , WXHWND hWnd ) { wxString sStr(wxGetWindowClass(hWnd)); long lId = wxGetWindowId(hWnd); long lStyle = ::WinQueryWindowULong((HWND)hWnd ,QWL_STYLE ); wxWindow* pWin = NULL; sStr.UpperCase(); if (sStr == wxT("BUTTON")) { if (lStyle == BS_AUTOCHECKBOX) { pWin = new wxCheckBox; } else if (lStyle == BS_AUTORADIOBUTTON) { pWin = new wxRadioButton; } else if (lStyle & BS_BITMAP || lStyle == BS_USERBUTTON) { pWin = new wxBitmapButton; } else if (lStyle == BS_PUSHBUTTON) { pWin = new wxButton; } else if (lStyle == SS_GROUPBOX) { pWin = new wxStaticBox; } else { wxLogError(wxT("Don't know what kind of button this is: id = %ld"), lId); } } else if (sStr == wxT("COMBOBOX")) { pWin = new wxComboBox; } else if (sStr == wxT("EDIT")) { pWin = new wxTextCtrl; } else if (sStr == wxT("LISTBOX")) { pWin = new wxListBox; } else if (sStr == wxT("SCROLLBAR")) { pWin = new wxScrollBar; } else if (sStr == wxT("MSCTLS_UPDOWN32")) { pWin = new wxSpinButton; } else if (sStr == wxT("MSCTLS_TRACKBAR32")) { pWin = new wxSlider; } else if (sStr == wxT("STATIC")) { if (lStyle == SS_TEXT) pWin = new wxStaticText; else if (lStyle == SS_ICON) { pWin = new wxStaticBitmap; } } else { wxString sMsg(wxT("Don't know how to convert from Windows class ")); sMsg += sStr; wxLogError(sMsg); } if (pWin) { pParent->AddChild(pWin); pWin->SetEventHandler(pWin); pWin->SetHWND(hWnd); pWin->SetId(lId); pWin->SubclassWin(hWnd); pWin->AdoptAttributesFromHWND(); pWin->SetupColours(); return pWin; } else return NULL; } // end of wxWindow::CreateWindowFromHWND
void AdviceManager::HandleAdviceResponse( Client *advisor, csString sAdvisee, csString message) { if ( !advisor->GetAdvisor() ) { psserver->SendSystemInfo(advisor->GetClientNum(),"You need to be an advisor to use this command."); return; } csString buf; // Source Client Name, Target Client Name, Message buf.Format("%s, %s, \"%s\"", advisor->GetName(), sAdvisee.GetData() , message.GetData()); psserver->GetLogCSV()->Write(CSV_ADVICE, buf); // Find Advisee Client by name if (sAdvisee.Length()) { sAdvisee = NormalizeCharacterName(sAdvisee); } Client *advisee = psserver->GetConnections()->Find(sAdvisee); if (!advisee) { // Create a new message to report TELL error and send // back to original person. csString sMsg("No player named "); sMsg += sAdvisee; sMsg += " is logged on to the system currently."; psserver->SendSystemError(advisor->GetClientNum(), sMsg); return; } // Can't allow you to advise yourself if ( advisee == advisor ) { psserver->SendSystemError(advisor->GetClientNum(), "You are not allowed to advise yourself. Please wait for another advisor."); return; } // find existing Advicee in the List AdviceSession key; key.AdviseeClientNum = advisee->GetClientNum(); AdviceSession *activeSession = AdviseeList.Get(advisee->GetClientNum(), NULL); if (!activeSession || (activeSession && ( !activeSession->requestEvent ) && ( activeSession->GetAdvisor() == NULL ) ) ) { psserver->SendSystemError(advisor->GetClientNum(), "%s has not requested help.", advisee->GetName()); return; } if (activeSession && ( activeSession->AdviseeClientNum != advisee->GetClientNum() ) ) { Debug2( LOG_ANY, advisee->GetClientNum(), "Grabbed wrong advisor session: %d", activeSession->AdviseeClientNum ); } if ( ( activeSession->GetAdvisor() != NULL ) && ( activeSession->AdvisorClientNum != advisor->GetClientNum() ) ) { psserver->SendSystemError(advisor->GetClientNum(), "%s is being advised already, thank you.", advisee->GetName()); return; } if ( message.Length() == 0 && activeSession->status == SESSION_STATUS_UNKNOWN ) // advisor is claiming a session { // check to make sure advisor has only one claimed session. AdviceSession *loopSession; csHash< AdviceSession* >::GlobalIterator loop( AdviseeList.GetIterator() ); while(loop.HasNext()) { loopSession = loop.Next(); if (activeSession->status == SESSION_STATUS_CLAIMED && loopSession->GetAdvisor() == advisor ) { psserver->SendSystemInfo(advisor->GetClientNum(), "You cannot have two messengers waiting for you at the same time, please answer %s's request first." , loopSession->adviseeName.GetData() ); return; } } activeSession->SetAdvisor( advisor ); psserver->SendSystemInfo(advisee->GetClientNum(), "An advisor is preparing an answer to your question, please be patient."); psserver->SendSystemInfo(advisor->GetClientNum(), "You have claimed the session with %s. Please provide an answer." , advisee->GetName() ); for (size_t i = 0; i < advisors.GetSize(); i++) { if ( advisors[i].id != activeSession->AdvisorClientNum ) { psserver->SendSystemInfo(advisors[i].id, "%s has proclaimed they know the answer to %s's question.", advisor->GetName(), advisee->GetName() ); } } activeSession->status = SESSION_STATUS_CLAIMED; } else { if (message.IsEmpty()) { psserver->SendSystemInfo(advisor->GetClientNum(), "Please enter the advice you wish to give."); return; } psChatMessage msgChat(activeSession->AdviseeClientNum, 0, advisor->GetName(), advisee->GetName(), message ,CHAT_ADVISOR,false); if ( activeSession->GetAdvisor() == NULL || activeSession->status != SESSION_STATUS_OWNED ) { // Check to make sure the advice is 'good' // if ( message.Length() < 20 ) // { // psserver->SendSystemInfo(advisor->GetClientNum(), "Please be more specific when answering questions. Your advice has been ignored."); // return; // } //activeSession->AdvisorClientNum = me->clientnum; activeSession->SetAdvisor( advisor ); advisor->IncrementAdvisorPoints(activeSession->advisorPoints); psserver->CharacterLoader.SaveCharacterData( advisor->GetCharacterData(), advisor->GetActor(), true ); // Send Confirmation to advisor psserver->SendSystemInfo( advisor->GetClientNum(), "You are now advising %s.",advisee->GetName()); // Send Confirmation to all other advisors so they know they lost this one. for (size_t i = 0; i < advisors.GetSize(); i++) { if ( advisors[i].id != activeSession->AdvisorClientNum ) { psserver->SendSystemInfo( advisors[i].id, "%s has been assigned to %s.", advisee->GetName(), advisor->GetName() ); if ( advisors[i].GM ) continue; msgChat.msg->clientnum = advisors[i].id; msgChat.SendMessage(); } } activeSession->status = SESSION_STATUS_OWNED; } if ( activeSession->requestEvent ) activeSession->requestEvent->valid = false; // This keeps the cancellation timeout from firing. activeSession->answered = true; // Send Message to Advisee msgChat.msg->clientnum = activeSession->AdviseeClientNum; msgChat.SendMessage(); // Send Message to advisor msgChat.msg->clientnum = activeSession->AdvisorClientNum; msgChat.SendMessage(); // Send message to GM chars as well for (size_t i = 0; i < advisors.GetSize(); i++) { if (!advisors[i].GM || advisors[i].id == activeSession->AdvisorClientNum) continue; msgChat.msg->clientnum = advisors[i].id; msgChat.SendMessage(); } } // Add timeout for Advisor-Advisee relationship // this will allow later questions by the same client to go to a different advisor // spreading the wealth and burden amongst all ;) if ( activeSession->timeoutEvent ) { activeSession->timeoutEvent->valid = false; } psAdviceSessionTimeoutGameEvent *ev = new psAdviceSessionTimeoutGameEvent( this, activeSession->answered?ADVICE_SESSION_TIMEOUT:ADVICE_SESSION_TIMEOUT/2, advisee->GetActor(), activeSession ); activeSession->timeoutEvent = ev; psserver->GetEventManager()->Push(ev); }
void ThreadSendAlert() { if (!mapArgs.count("-sendalert") && !mapArgs.count("-printalert")) return; MilliSleep(60*1000); // Wait a minute so we get connected // // Alerts are relayed around the network until nRelayUntil, flood // filling to every node. // After the relay time is past, new nodes are told about alerts // when they connect to peers, until either nExpiration or // the alert is cancelled by a newer alert. // Nodes never save alerts to disk, they are in-memory-only. // CAlert alert; alert.nRelayUntil = GetTime() + 15 * 60; alert.nExpiration = GetTime() + 365 * 60 * 60; alert.nID = 1000; // use https://github.com/zcash/zcash/wiki/specification#assigned-numbers to keep track of alert IDs alert.nCancel = 0; // cancels previous messages up to this ID number // These versions are protocol versions // 170002 : 1.0.0 alert.nMinVer = 170002; alert.nMaxVer = 170002; // // main.cpp: // 1000 for Misc warnings like out of disk space and clock is wrong // 2000 for longer invalid proof-of-work chain // Higher numbers mean higher priority // 4000 or higher will put the RPC into safe mode alert.nPriority = 5000; alert.strComment = ""; alert.strStatusBar = "URGENT: Upgrade required: see https://z.cash"; alert.strRPCError = "URGENT: Upgrade required: see https://z.cash"; // Set specific client version/versions here. If setSubVer is empty, no filtering on subver is done: // alert.setSubVer.insert(std::string("/MagicBean:0.7.2/")); // Sign const CChainParams& chainparams = Params(); std::string networkID = chainparams.NetworkIDString(); bool fIsTestNet = networkID.compare("test") == 0; std::vector<unsigned char> vchTmp(ParseHex(fIsTestNet ? pszTestNetPrivKey : pszPrivKey)); CPrivKey vchPrivKey(vchTmp.begin(), vchTmp.end()); CDataStream sMsg(SER_NETWORK, CLIENT_VERSION); sMsg << *(CUnsignedAlert*)&alert; alert.vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end()); CKey key; if (!key.SetPrivKey(vchPrivKey, false)) { printf("ThreadSendAlert() : key.SetPrivKey failed\n"); return; } if (!key.Sign(Hash(alert.vchMsg.begin(), alert.vchMsg.end()), alert.vchSig)) { printf("ThreadSendAlert() : key.Sign failed\n"); return; } // Test CDataStream sBuffer(SER_NETWORK, CLIENT_VERSION); sBuffer << alert; CAlert alert2; sBuffer >> alert2; if (!alert2.CheckSignature(chainparams.AlertKey())) { printf("ThreadSendAlert() : CheckSignature failed\n"); return; } assert(alert2.vchMsg == alert.vchMsg); assert(alert2.vchSig == alert.vchSig); alert.SetNull(); printf("\nThreadSendAlert:\n"); printf("hash=%s\n", alert2.GetHash().ToString().c_str()); printf("%s\n", alert2.ToString().c_str()); printf("vchMsg=%s\n", HexStr(alert2.vchMsg).c_str()); printf("vchSig=%s\n", HexStr(alert2.vchSig).c_str()); // Confirm if (!mapArgs.count("-sendalert")) return; while (vNodes.size() < 1 && !ShutdownRequested()) MilliSleep(500); if (ShutdownRequested()) return; // Send printf("ThreadSendAlert() : Sending alert\n"); int nSent = 0; { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) { if (alert2.RelayTo(pnode)) { printf("ThreadSendAlert() : Sent alert to %s\n", pnode->addr.ToString().c_str()); nSent++; } } } printf("ThreadSendAlert() : Alert sent to %d nodes\n", nSent); }
bool ServiceHost::ProcessRequest( HTTPRequest *pRequest ) { bool bHandled = false; Service *pService = nullptr; try { if (pRequest) { if (pRequest->m_sBaseUrl != m_sBaseUrl) return false; LOG(VB_HTTP, LOG_INFO, QString("ServiceHost::ProcessRequest: %1 : %2") .arg(pRequest->m_sMethod) .arg(pRequest->m_sRawRequest)); // -------------------------------------------------------------- // Check to see if they are requesting the WSDL service Definition // -------------------------------------------------------------- if (( pRequest->m_eType == RequestTypeGet ) && ( pRequest->m_sMethod == "wsdl" )) { pService = qobject_cast<Service*>(m_oMetaObject.newInstance()); Wsdl wsdl( this ); wsdl.GetWSDL( pRequest ); delete pService; return true; } // -------------------------------------------------------------- // Check to see if they are requesting XSD - Type Definition // -------------------------------------------------------------- if (( pRequest->m_eType == RequestTypeGet ) && ( pRequest->m_sMethod == "xsd" )) { bool bHandled2 = false; if ( pRequest->m_mapParams.count() > 0) { pService = qobject_cast<Service*>(m_oMetaObject.newInstance()); Xsd xsd; if (pRequest->m_mapParams.contains( "type" )) bHandled2 = xsd.GetXSD( pRequest, pRequest->m_mapParams[ "type" ] ); else bHandled2 = xsd.GetEnumXSD( pRequest, pRequest->m_mapParams[ "enum" ] ); delete pService; pService = nullptr; } if (!bHandled2) throw QString("Invalid arguments to xsd query: %1") .arg(pRequest->m_sRequestUrl.section('?', 1)); return true; } // -------------------------------------------------------------- if (( pRequest->m_eType == RequestTypeGet ) && ( pRequest->m_sMethod == "version" )) { int nClassIdx = m_oMetaObject.indexOfClassInfo( "version" ); if (nClassIdx >=0) { QString sVersion = m_oMetaObject.classInfo(nClassIdx).value(); return FormatResponse( pRequest, QVariant( sVersion )); } } // -------------------------------------------------------------- // Allow a more REST like calling convention. If the Method // Name isn't found, search for one with the request method // appended to the name ( "Get" or "Put" for POST) // -------------------------------------------------------------- QString sMethodName = pRequest->m_sMethod; bool bMethodFound = false; if (m_Methods.contains(sMethodName)) bMethodFound = true; else { switch( pRequest->m_eType ) { case RequestTypeHead: case RequestTypeGet : sMethodName = "Get" + sMethodName; break; case RequestTypePost: sMethodName = "Put" + sMethodName; break; case RequestTypeUnknown: case RequestTypeOptions: case RequestTypeMSearch: case RequestTypeSubscribe: case RequestTypeUnsubscribe: case RequestTypeNotify: case RequestTypeResponse: // silence compiler break; } if (m_Methods.contains(sMethodName)) bMethodFound = true; } if (bMethodFound) { MethodInfo oInfo = m_Methods.value( sMethodName ); if (( pRequest->m_eType & oInfo.m_eRequestType ) != 0) { // ------------------------------------------------------ // Create new Instance of the Service Class so // it's guaranteed to be on the same thread // since we are making direct calls into it. // ------------------------------------------------------ pService = qobject_cast<Service*>(m_oMetaObject.newInstance()); QVariant vResult = oInfo.Invoke(pService, pRequest->m_mapParams); bHandled = FormatResponse( pRequest, vResult ); } } if (!bHandled) UPnp::FormatErrorResponse( pRequest, UPnPResult_InvalidAction ); } } catch (HttpRedirectException &ex) { UPnp::FormatRedirectResponse( pRequest, ex.hostName ); bHandled = true; } catch (HttpException &ex) { LOG(VB_GENERAL, LOG_ERR, ex.msg); UPnp::FormatErrorResponse( pRequest, UPnPResult_ActionFailed, ex.msg ); bHandled = true; } catch (QString &sMsg) { LOG(VB_GENERAL, LOG_ERR, sMsg); UPnp::FormatErrorResponse( pRequest, UPnPResult_ActionFailed, sMsg ); bHandled = true; } catch ( ...) { QString sMsg( "ServiceHost::ProcessRequest - Unexpected Exception" ); LOG(VB_GENERAL, LOG_ERR, sMsg); UPnp::FormatErrorResponse( pRequest, UPnPResult_ActionFailed, sMsg ); bHandled = true; } if (pService != nullptr) delete pService; return bHandled; }
void frmMain::readReply(QNetworkReply * replyIn) { // Проверяем, не произошло ли ошибки при выполнении запроса: if (replyIn->error() != QNetworkReply::NoError) { // Ошибка произошла - сообщаем о ней. Если поднят флаг выхода - // предлагаем пользователю настроить параметры соединения. Если флаг // выхода не поднять - значит, пользовательский интерфейс уже открыт, // и смысла предлагать пользователю его открыть нет. QString sMsg(tr("Failed to get version info from site.")); QString sErr(replyIn->errorString()); if (bExitOnReply) { sMsg.append(tr(" Open connection settings?")); if (MsgUtilsMy::showQuestion(this, false, sMsg, QString(), sErr)) bExitOnReply = false; } else MsgUtilsMy::showErrorMsg(this, sMsg, QString(), sErr); // Если установлен флаг выхода - выходим из программы, иначе показываем // основную форму: if (bExitOnReply) qApp->exit(0); else this->show(); // Завершаем функцию: return; } // Получаем текст полученного ответа на запрос: QString sVer(replyIn->readAll()); // Маркер начала версии программы: QString sVerStartMark(VERSION_START); // Маркер окончания версии программы: QString sVerEndMark(VERSION_END); // Проверка наличия версии программы в нужном формате. // Ищем маркер начала строки версии: int iVStart = sVer.indexOf(sVerStartMark, 0, Qt::CaseInsensitive); // Позиция маркера окончания строки версии: int iVEnd = -1; // В случае, если маркер начала версии найден - ищем маркер окончания версии: if (iVStart > -1) iVEnd = sVer.indexOf(sVerEndMark, iVStart, Qt::CaseInsensitive); // В случае, если маркер начала или маркер окончания строки версии не найден - // сообщаем об ошибке и завершаем функцию: if (iVStart == -1 || iVEnd == -1) { // Ошибка произошла - сообщаем о ней: MsgUtilsMy::showErrorMsg(this, tr("Error while readin version from site."), QString(), tr("Version start or version end marker is not found.")); // Если установлен флаг выхода - выходим из программы, иначе показываем // основную форму: if (bExitOnReply) qApp->exit(0); else this->show(); // Завершаем функцию: return; } // Убираем окончание строки, начиная с первого символа маркера окончания строки версии: sVer.remove(iVEnd, sVer.length() - iVEnd); // Убираем начало строки до версии, включая маркер начала версии: sVer.remove(0, iVStart + sVerStartMark.length()); // Создаём объекты версий: LWVersion verCurrent(sCurVer); LWVersion verSite(sVer); // Если версия на сайте больше - сообщаем об этом и предлагаем перейти на сайт: if (verSite.isHigherThan(verCurrent)) { if (MsgUtilsMy::showQuestion(this, false, tr("New %1 version is available. Open download page?").arg(sProg))) QDesktopServices::openUrl(QUrl(sPageGoTo)); } // Установлена последняя версия. В случае, если поднят флаг выхода // после проверки - сообщать о наличии последней версии пользователю // не нужно. В случае, если флаг выхода не поднят - значит, проверка // запущена пользователем, и надо сообщить ему, что у него самая // последняя версия: else { // Сообщаем об отстутствии обновлений в случае, если вывод // таких сообщений явно включен, и в случае, если вывод // не выключен и не поднят флаг выхода после проверки: if ((iNupMsg == 2) || ((iNupMsg != 1) && !bExitOnReply)) // Сообщаем, что установлена последняя версия: MsgUtilsMy::showInfoMsg(this, tr("Latest %1 version is installed.").arg(sProg)); } // Если поднят флаг завершения работы приложения после получения ответа - // завершаем работу приложения, иначе показываем главное окно: if (bExitOnReply) qApp->exit(0); else this->show(); }