bool InitHTTPServer() { struct evhttp* http = 0; struct event_base* base = 0; if (!InitHTTPAllowList()) return false; if (GetBoolArg("-rpcssl", false)) { uiInterface.ThreadSafeMessageBox( "SSL mode for RPC (-rpcssl) is no longer supported.", "", CClientUIInterface::MSG_ERROR); return false; } // Redirect libevent's logging to our own log event_set_log_callback(&libevent_log_cb); // Update libevent's log handling. Returns false if our version of // libevent doesn't support debug logging, in which case we should // clear the BCLog::LIBEVENT flag. if (!UpdateHTTPServerLogging(logCategories & BCLog::LIBEVENT)) { logCategories &= ~BCLog::LIBEVENT; } #ifdef WIN32 evthread_use_windows_threads(); #else evthread_use_pthreads(); #endif base = event_base_new(); // XXX RAII if (!base) { LogPrintf("Couldn't create an event_base: exiting\n"); return false; } /* Create a new evhttp object to handle requests. */ http = evhttp_new(base); // XXX RAII if (!http) { LogPrintf("couldn't create evhttp. Exiting.\n"); event_base_free(base); return false; } evhttp_set_timeout(http, GetArg("-rpcservertimeout", DEFAULT_HTTP_SERVER_TIMEOUT)); evhttp_set_max_headers_size(http, MAX_HEADERS_SIZE); evhttp_set_max_body_size(http, MAX_SIZE); evhttp_set_gencb(http, http_request_cb, NULL); if (!HTTPBindAddresses(http)) { LogPrintf("Unable to bind any endpoint for RPC server\n"); evhttp_free(http); event_base_free(base); return false; } LogPrint(BCLog::HTTP, "Initialized HTTP server\n"); int workQueueDepth = std::max((long)GetArg("-rpcworkqueue", DEFAULT_HTTP_WORKQUEUE), 1L); LogPrintf("HTTP: creating work queue of depth %d\n", workQueueDepth); workQueue = new WorkQueue<HTTPClosure>(workQueueDepth); eventBase = base; eventHTTP = http; return true; }
// Writes all missing QSettings with their default values void OptionsModel::Init(bool resetSettings) { if (resetSettings) Reset(); this->resetSettings = resetSettings; QSettings settings; // Ensure restart flag is unset on client startup setRestartRequired(false); // These are Qt-only settings: // Window if (!settings.contains("fMinimizeToTray")) settings.setValue("fMinimizeToTray", false); fMinimizeToTray = settings.value("fMinimizeToTray").toBool(); if (!settings.contains("fMinimizeOnClose")) settings.setValue("fMinimizeOnClose", false); fMinimizeOnClose = settings.value("fMinimizeOnClose").toBool(); // Display if (!settings.contains("nDisplayUnit")) settings.setValue("nDisplayUnit", BitcoinUnits::ARC); nDisplayUnit = settings.value("nDisplayUnit").toInt(); if (!settings.contains("strThirdPartyTxUrls")) settings.setValue("strThirdPartyTxUrls", ""); strThirdPartyTxUrls = settings.value("strThirdPartyTxUrls", "").toString(); if (!settings.contains("fCoinControlFeatures")) settings.setValue("fCoinControlFeatures", false); fCoinControlFeatures = settings.value("fCoinControlFeatures", false).toBool(); if (!settings.contains("digits")) settings.setValue("digits", "2"); if (!settings.contains("theme")) settings.setValue("theme", ""); if (!settings.contains("fShowGoldminenodesTab")) settings.setValue("fShowGoldminenodesTab", goldminenodeConfig.getCount()); if (!settings.contains("fShowAdvancedPSUI")) settings.setValue("fShowAdvancedPSUI", false); fShowAdvancedPSUI = settings.value("fShowAdvancedPSUI", false).toBool(); if (!settings.contains("fLowKeysWarning")) settings.setValue("fLowKeysWarning", true); // These are shared with the core or have a command-line parameter // and we want command-line parameters to overwrite the GUI settings. // // If setting doesn't exist create it with defaults. // // If SoftSetArg() or SoftSetBoolArg() return false we were overridden // by command-line and show this in the UI. // Main if (!settings.contains("nDatabaseCache")) settings.setValue("nDatabaseCache", (qint64)nDefaultDbCache); if (!SoftSetArg("-dbcache", settings.value("nDatabaseCache").toString().toStdString())) addOverriddenOption("-dbcache"); if (!settings.contains("nThreadsScriptVerif")) settings.setValue("nThreadsScriptVerif", DEFAULT_SCRIPTCHECK_THREADS); if (!SoftSetArg("-par", settings.value("nThreadsScriptVerif").toString().toStdString())) addOverriddenOption("-par"); // Wallet #ifdef ENABLE_WALLET if (!settings.contains("bSpendZeroConfChange")) settings.setValue("bSpendZeroConfChange", true); if (!SoftSetBoolArg("-spendzeroconfchange", settings.value("bSpendZeroConfChange").toBool())) addOverriddenOption("-spendzeroconfchange"); // SpySend if (!settings.contains("nSpySendRounds")) settings.setValue("nSpySendRounds", DEFAULT_PRIVATESEND_ROUNDS); if (!SoftSetArg("-privatesendrounds", settings.value("nSpySendRounds").toString().toStdString())) addOverriddenOption("-privatesendrounds"); nSpySendRounds = settings.value("nSpySendRounds").toInt(); if (!settings.contains("nSpySendAmount")) { // for migration from old settings if (!settings.contains("nAnonymizeArcticAmount")) settings.setValue("nSpySendAmount", DEFAULT_PRIVATESEND_AMOUNT); else settings.setValue("nSpySendAmount", settings.value("nAnonymizeArcticAmount").toInt()); } if (!SoftSetArg("-privatesendamount", settings.value("nSpySendAmount").toString().toStdString())) addOverriddenOption("-privatesendamount"); nSpySendAmount = settings.value("nSpySendAmount").toInt(); if (!settings.contains("fSpySendMultiSession")) settings.setValue("fSpySendMultiSession", DEFAULT_PRIVATESEND_MULTISESSION); if (!SoftSetBoolArg("-privatesendmultisession", settings.value("fSpySendMultiSession").toBool())) addOverriddenOption("-privatesendmultisession"); fSpySendMultiSession = settings.value("fSpySendMultiSession").toBool(); #endif // Network if (!settings.contains("fUseUPnP")) settings.setValue("fUseUPnP", DEFAULT_UPNP); if (!SoftSetBoolArg("-upnp", settings.value("fUseUPnP").toBool())) addOverriddenOption("-upnp"); if (!settings.contains("fListen")) settings.setValue("fListen", DEFAULT_LISTEN); if (!SoftSetBoolArg("-listen", settings.value("fListen").toBool())) addOverriddenOption("-listen"); if (!settings.contains("fUseProxy")) settings.setValue("fUseProxy", false); if (!settings.contains("addrProxy")) settings.setValue("addrProxy", "127.0.0.1:9050"); // Only try to set -proxy, if user has enabled fUseProxy if (settings.value("fUseProxy").toBool() && !SoftSetArg("-proxy", settings.value("addrProxy").toString().toStdString())) addOverriddenOption("-proxy"); else if(!settings.value("fUseProxy").toBool() && !GetArg("-proxy", "").empty()) addOverriddenOption("-proxy"); if (!settings.contains("fUseSeparateProxyTor")) settings.setValue("fUseSeparateProxyTor", false); if (!settings.contains("addrSeparateProxyTor")) settings.setValue("addrSeparateProxyTor", "127.0.0.1:9050"); // Only try to set -onion, if user has enabled fUseSeparateProxyTor if (settings.value("fUseSeparateProxyTor").toBool() && !SoftSetArg("-onion", settings.value("addrSeparateProxyTor").toString().toStdString())) addOverriddenOption("-onion"); else if(!settings.value("fUseSeparateProxyTor").toBool() && !GetArg("-onion", "").empty()) addOverriddenOption("-onion"); // Display if (!settings.contains("language")) settings.setValue("language", ""); if (!SoftSetArg("-lang", settings.value("language").toString().toStdString())) addOverriddenOption("-lang"); language = settings.value("language").toString(); }
VOID BzSrchMe(PSPAWNINFO pChar, PCHAR szLine) { lockit lk(bzsrchhandle); CHAR szArg[MAX_STRING] = { 0 }; CHAR szItem[MAX_STRING] = { 0 }; PCHARINFO pCharInfo = GetCharInfo(); BOOL bArg = TRUE; bool first = true; if (CButtonWnd *ptr = (CButtonWnd *)pBazaarSearchWnd->GetChildItem("BZR_Default")) { SendWndClick2((CXWnd*)ptr, "leftmouseup"); } while (bArg) { GetArg(szArg, szLine, 1); szLine = GetNextArg(szLine, 1); if (szArg[0] == 0) { bArg = FALSE; } else if (!strcmp(szArg, "class")) { GetArg(szArg, szLine, 1); szLine = GetNextArg(szLine, 1); DoClass(szArg); } else if (!_stricmp(szArg, "race")) { GetArg(szArg, szLine, 1); szLine = GetNextArg(szLine, 1); DoRace(szArg); } else if (!_stricmp(szArg, "stat")) { GetArg(szArg, szLine, 1); szLine = GetNextArg(szLine, 1); DoCombo(szArg, "Stat", "BZR_StatSlotCombobox"); } else if (!_stricmp(szArg, "slot")) { GetArg(szArg, szLine, 1); szLine = GetNextArg(szLine, 1); DoCombo(szArg, "Slot", "BZR_ItemSlotCombobox"); } else if (!_stricmp(szArg, "type")) { GetArg(szArg, szLine, 1); szLine = GetNextArg(szLine, 1); DoCombo(szArg, "Type", "BZR_ItemTypeCombobox"); } else if (!strcmp(szArg, "price")) { GetArg(szArg, szLine, 1); szLine = GetNextArg(szLine, 1); if (szArg[0] == 0) { MacroError("Bad price low."); goto error_out; } if (CXWnd *pEdit = (CXWnd *)pBazaarSearchWnd->GetChildItem("BZR_MinPriceInput")) { pEdit->SetWindowTextA(CXStr(szArg)); } GetArg(szArg, szLine, 1); szLine = GetNextArg(szLine, 1); if (szArg[0] == 0) { MacroError("Bad price high."); goto error_out; } if (CXWnd *pEdit = (CXWnd *)pBazaarSearchWnd->GetChildItem("BZR_MaxPriceInput")) { pEdit->SetWindowTextA(CXStr(szArg)); } } else if (!_stricmp(szArg, "trader")) { GetArg(szArg, szLine, 1); szLine = GetNextArg(szLine, 1); DoCombo(szArg, "Trader", "BZR_PlayersCombobox"); } else if (!_stricmp(szArg, "prestige")) { GetArg(szArg, szLine, 1); szLine = GetNextArg(szLine, 1); DoCombo(szArg, "Prestige", "BZR_ItemPrestigeCombobox"); } else if (!_stricmp(szArg, "augment")) { GetArg(szArg, szLine, 1); szLine = GetNextArg(szLine, 1); DoCombo(szArg, "Augment", "BZR_ItemAugmentCombobox"); } else { if (first) { first = false; } else { strcat(szItem, " "); } strcat(szItem, szArg); } } if (CXWnd *pEdit = (CXWnd *)pBazaarSearchWnd->GetChildItem("BZR_ItemNameInput")) { pEdit->SetWindowTextA(CXStr(szItem)); DWORD nThreadID = 0; CreateThread(NULL, NULL, searchthread, 0, 0, &nThreadID); } error_out: return; }
// *************************************************************************** // Function: MapFilters // Description: Our '/mapfilter' command // Sets map filters // Usage: /mapfilter [options|help] // *************************************************************************** VOID MapFilterSetting(PSPAWNINFO pChar, DWORD nMapFilter, PCHAR szValue) { CHAR szBuffer[MAX_STRING] = { 0 }; CHAR Buff[MAX_STRING] = { 0 }; DWORD dwValue = 0; PCHAR szFilterMap[] = { "hide", "show", NULL }; if (!pChar) return; PMAPFILTER pMapFilter = &MapFilterOptions[nMapFilter]; if (!RequirementsMet(nMapFilter)) { sprintf_s(szBuffer, "'%s' requires '%s' option. Please enable this option first.", pMapFilter->szName, MapFilterOptions[pMapFilter->RequiresOption].szName); WriteChatColor(szBuffer, USERCOLOR_DEFAULT); return; } if (!szValue) { if (pMapFilter->bIsToggle) { sprintf_s(szBuffer, "%s: %s", pMapFilter->szName, szFilterMap[pMapFilter->Enabled]); } else if (nMapFilter == MAPFILTER_Custom) { if (IsOptionEnabled(nMapFilter) == 0) { sprintf_s(szBuffer, "%s: Off", pMapFilter->szName); } else { sprintf_s(szBuffer, "%s: %s", pMapFilter->szName, FormatSearchSpawn(Buff, sizeof(Buff), &MapFilterCustom)); } } else { sprintf_s(szBuffer, "%s: %d", pMapFilter->szName, pMapFilter->Enabled); } if (pMapFilter->DefaultColor != -1) { CHAR szBuffer2[MAX_STRING] = { 0 }; DWORD R, G, B; R = (pMapFilter->Color & 0xFF0000) / 0x10000; G = (pMapFilter->Color & 0xFF00) / 0x100; B = pMapFilter->Color & 0xFF; sprintf_s(szBuffer2, "%s (Color: %d %d %d)", szBuffer, R, G, B); strcpy_s(szBuffer, szBuffer2); } } else { if (pMapFilter->bIsToggle) { if (!_stricmp(szFilterMap[0], szValue)) { pMapFilter->Enabled = 0; } else if (!_stricmp(szFilterMap[1], szValue)) { pMapFilter->Enabled = 1; } else { pMapFilter->Enabled = 1 - pMapFilter->Enabled; } sprintf_s(szBuffer, "%s is now set to: %s", pMapFilter->szName, szFilterMap[IsOptionEnabled(nMapFilter)]); } else if (nMapFilter == MAPFILTER_Custom) { ClearSearchSpawn(&MapFilterCustom); if (szValue[0] == 0) { pMapFilter->Enabled = 0; sprintf_s(szBuffer, "%s is now set to: Off", pMapFilter->szName); } else { pMapFilter->Enabled = 1; ParseSearchSpawn(szValue, &MapFilterCustom); sprintf_s(szBuffer, "%s is now set to: %s", pMapFilter->szName, FormatSearchSpawn(Buff, sizeof(Buff), &MapFilterCustom)); } } else if (nMapFilter == MAPFILTER_Marker) { CHAR szBuffer2[MAX_STRING] = { 0 }; GetArg(szBuffer2, szValue, 1); if (!_stricmp(szFilterMap[0], szValue)) { pMapFilter->Enabled = 0; sprintf_s(szBuffer, "%s is now set to: %s", pMapFilter->szName, szFilterMap[IsOptionEnabled(nMapFilter)]); } else if (!_stricmp(szFilterMap[1], szValue)) { pMapFilter->Enabled = 1; sprintf_s(szBuffer, "%s is now set to: %s", pMapFilter->szName, szFilterMap[IsOptionEnabled(nMapFilter)]); } else { pMapFilter->Enabled = 1; sprintf_s(szBuffer, "%s %s", pMapFilter->szName, FormatMarker(szValue, Buff, sizeof(Buff))); } } else { pMapFilter->Enabled = atoi(szValue); sprintf_s(szBuffer, "%s is now set to: %d", pMapFilter->szName, pMapFilter->Enabled); } } WriteChatColor(szBuffer, USERCOLOR_DEFAULT); if (szValue) { _itoa_s(pMapFilter->Enabled, szBuffer, 10); WritePrivateProfileString("Map Filters", pMapFilter->szName, szBuffer, INIFileName); } }
VOID HideDoCommand(PSPAWNINFO pChar, PCHAR szLine, BOOL delayed) { if (delayed) { PCHATBUF pChat = (PCHATBUF)malloc(sizeof(CHATBUF)); if (pChat) { strcpy(pChat->szText,szLine); pChat->pNext = NULL; if (!gDelayedCommands) { gDelayedCommands = pChat; } else { PCHATBUF pCurrent; for (pCurrent = gDelayedCommands;pCurrent->pNext;pCurrent=pCurrent->pNext); pCurrent->pNext = pChat; } } return; } CAutoLock DoCommandLock(&gCommandCS); CHAR szCmd[MAX_STRING] = {0}; CHAR szParam[MAX_STRING] = {0}; CHAR szOriginalLine[MAX_STRING] = {0}; strcpy(szOriginalLine,szLine); GetArg(szCmd,szLine,1); PALIAS pLoop = pAliases; while (pLoop) { if (!stricmp(szCmd,pLoop->szName)) { sprintf(szLine,"%s%s",pLoop->szCommand,szOriginalLine+strlen(pLoop->szName)); break; } pLoop = pLoop->pNext; } GetArg(szCmd,szLine,1); if (szCmd[0]==0) return; strcpy(szParam, GetNextArg(szLine)); if ((szCmd[0]==':') || (szCmd[0]=='{')) { bRunNextCommand = TRUE; return; } if(gMacroBlock && gMacroBlock->LoopLine!=0) { //this is a command thats inside a while loop //so its time to loop back gMacroBlock = GetWhileBlock(gMacroBlock->LoopLine); if (szCmd[0]=='}') { bRunNextCommand = TRUE; return; } } else if (szCmd[0]=='}') { if (strstr(szLine,"{")) { GetArg(szCmd,szLine,2); if (stricmp(szCmd,"else")) { FatalError("} and { seen on the same line without an else present"); } // DebugSpew("DoCommand - handing {} off to FailIf"); FailIf(pChar,"{",gMacroBlock,TRUE); } else { // handle this: // /if () { // } else /echo stuff GetArg(szCmd,szLine,2); if (!stricmp(szCmd,"else")) { // check here to fail this: // /if () { // } else // /echo stuff GetArg(szCmd,szLine,3); if (!stricmp(szCmd,"")) { FatalError("no command or { following else"); } bRunNextCommand = TRUE; } else { bRunNextCommand = TRUE; } } return; } if (szCmd[0]==';' || szCmd[0]=='[') { pEverQuest->InterpretCmd((EQPlayer*)pChar,szOriginalLine); return; } PMQCOMMAND pCommand=pCommands; while(pCommand) { if (pCommand->InGameOnly && gGameState!=GAMESTATE_INGAME) { pCommand=pCommand->pNext; continue; } int Pos=strnicmp(szCmd,pCommand->Command,strlen(szCmd)); if (Pos<0) {// command not found break; } if (Pos==0) { if (pCommand->Parse && bAllowCommandParse) { pCommand->Function(pChar,ParseMacroParameter(pChar,szParam)); } else { pCommand->Function(pChar,szParam); } strcpy(szLastCommand,szOriginalLine); return; } pCommand=pCommand->pNext; } if (!strnicmp(szOriginalLine,"sub ",4)) { FatalError("Flow ran into another subroutine."); return; } strcpy(szLastCommand,szOriginalLine); MacroError("DoCommand - Couldn't parse '%s'",szOriginalLine); }
const char *DArgs::operator[] (size_t n) { return GetArg(n); }
//////////////////////////////////////////////////////////////// // キー入力処理 //////////////////////////////////////////////////////////////// void cWndMon::KeyIn( int kcode, bool shift, int ccode ) { static int LastKey = KVC_ENTER; // 前回のキー static int HisLevel = 1; // ヒストリレベル switch( kcode ){ // キーコード case KVC_F6: // モニタモード変更 vm->el->ToggleMonitor(); break; case KVC_ENTER: // Enter case KVC_P_ENTER: // Enter(テンキー) ZCons::Printf( "\n" ); if( strlen( KeyBuf ) > 0 ){ // キーバッファが有効で if( stricmp( KeyBuf, HisBuf[1] ) != 0 ){ // 直前のヒストリと異なるなら for( int i=MAX_HIS-1; i>1; i-- ) strcpy( HisBuf[i], HisBuf[i-1] ); strcpy( HisBuf[1], KeyBuf ); // キーバッファをヒストリバッファにコピー } } // ここで引数解析処理 Exec( GetArg() ); *KeyBuf = '\0'; // キーバッファクリア ZCons::Printf( PROMPT ); break; case KVC_UP: // 上矢印 case KVC_DOWN: // 下矢印 if( LastKey == KVC_UP || LastKey == KVC_DOWN ){ if( kcode == KVC_UP && HisLevel < MAX_HIS-1 && strlen( HisBuf[HisLevel+1] ) > 0 ) HisLevel++; if( kcode == KVC_DOWN && HisLevel > 0 ) HisLevel--; }else{ if( kcode == KVC_UP ) HisLevel = 1; else HisLevel = 0; } // 今のコマンドラインを消去 while( strlen(KeyBuf) > 0 ){ ZCons::LocateR( -1, 0 ); ZCons::PutCharH( ' ' ); ZCons::LocateR( -1, 0 ); KeyBuf[strlen(KeyBuf)-1] = (BYTE)'\0'; } // ヒストリバッファからキーバッファにコピーして表示 strcpy( KeyBuf, HisBuf[HisLevel] ); ZCons::Printf( KeyBuf ); break; case KVC_BACKSPACE: // BackSpace if( strlen(KeyBuf) > 0 ){ ZCons::LocateR( -1, 0 ); ZCons::PutCharH( ' ' ); ZCons::LocateR( -1, 0 ); KeyBuf[strlen(KeyBuf)-1] = (BYTE)'\0'; } break; // メモリウィンドウ case KVC_PAGEDOWN: // PageDown vm->el->memw->SetAddress( vm->el->memw->GetAddress() + ( shift ? 2048 : 16 ) ); break; case KVC_PAGEUP: // PageUp vm->el->memw->SetAddress( vm->el->memw->GetAddress() - ( shift ? 2048 : 16 ) ); break; default: // 有効な文字コードかつバッファがあふれていなければ if( ( ccode > 0x1f ) && ( ccode < 0x80 ) ){ if( strlen(KeyBuf) < (MAX_CHRS-1) ){ char *p = &KeyBuf[strlen(KeyBuf)]; *p++ = (BYTE)ccode; *p = (BYTE)'\0'; // ZCons::PutCharH( ccode ); ZCons::Printf( "%c", ccode ); } } } LastKey = kcode; }
/** Main entrypoint for DumpDynPcd shell application. @param[in] ImageHandle The image handle. @param[in] SystemTable The system table. @retval EFI_SUCCESS Command completed successfully. @retval EFI_INVALID_PARAMETER Command usage error. @retval EFI_OUT_OF_RESOURCES Not enough resources were available to run the command. @retval EFI_ABORTED Aborted by user. @retval EFI_NOT_FOUND The specified PCD is not found. @retval Others Error status returned from gBS->LocateProtocol. **/ EFI_STATUS EFIAPI DumpDynPcdMain ( IN EFI_HANDLE ImageHandle, IN EFI_SYSTEM_TABLE *SystemTable ) { EFI_STATUS Status; CHAR16 *InputPcdName; InputPcdName = NULL; Status = gBS->LocateProtocol(&gEfiUnicodeCollation2ProtocolGuid, NULL, (VOID **) &mUnicodeCollation); if (EFI_ERROR (Status)) { mUnicodeCollation = NULL; } Status = gBS->LocateProtocol (&gEfiPcdProtocolGuid, NULL, (VOID **) &mPiPcd); if (EFI_ERROR (Status)) { Print (L"DumpDynPcd: %EError. %NPI PCD protocol is not present.\n"); return Status; } Status = gBS->LocateProtocol (&gEfiGetPcdInfoProtocolGuid, NULL, (VOID **) &mPiPcdInfo); if (EFI_ERROR (Status)) { Print (L"DumpDynPcd: %EError. %NPI PCD info protocol is not present.\n"); return Status; } Status = gBS->LocateProtocol (&gPcdProtocolGuid, NULL, (VOID **) &mPcd); if (EFI_ERROR (Status)) { Print (L"DumpDynPcd: %EError. %NPCD protocol is not present.\n"); return Status; } Status = gBS->LocateProtocol (&gGetPcdInfoProtocolGuid, NULL, (VOID **) &mPcdInfo); if (EFI_ERROR (Status)) { Print (L"DumpDynPcd: %EError. %NPCD info protocol is not present.\n"); return Status; } // // get the command line arguments // Status = GetArg(); if (EFI_ERROR(Status)){ Print (L"DumpDynPcd: %EError. %NThe input parameters are not recognized.\n"); Status = EFI_INVALID_PARAMETER; return Status; } if (Argc > 2){ Print (L"DumpDynPcd: %EError. %NToo many arguments specified.\n"); Status = EFI_INVALID_PARAMETER; return Status; } if (Argc == 1){ Status = ProcessPcd (InputPcdName); goto Done; } if ((StrCmp(Argv[1], L"-?") == 0)||(StrCmp(Argv[1], L"-h") == 0)||(StrCmp(Argv[1], L"-H") == 0)){ ShowHelp (); goto Done; } else { if ((StrCmp(Argv[1], L"-v") == 0)||(StrCmp(Argv[1], L"-V") == 0)){ ShowVersion (); goto Done; } else { if (StrStr(Argv[1], L"-") != NULL){ Print (L"DumpDynPcd: %EError. %NThe argument '%B%s%N' is invalid.\n", Argv[1]); goto Done; } } } InputPcdName = Argv[1]; Status = ProcessPcd (InputPcdName); Done: if (mTempPcdNameBuffer != NULL) { FreePool (mTempPcdNameBuffer); } return Status; }
// // Load OpenSSL's list of root certificate authorities // void PaymentServer::LoadRootCAs(X509_STORE* _store) { if (PaymentServer::certStore == NULL) atexit(PaymentServer::freeCertStore); else freeCertStore(); // Unit tests mostly use this, to pass in fake root CAs: if (_store) { PaymentServer::certStore = _store; return; } // Normal execution, use either -rootcertificates or system certs: PaymentServer::certStore = X509_STORE_new(); // Note: use "-system-" default here so that users can pass -rootcertificates="" // and get 'I don't like X.509 certificates, don't trust anybody' behavior: QString certFile = QString::fromStdString(GetArg("-rootcertificates", "-system-")); if (certFile.isEmpty()) return; // Empty store QList<QSslCertificate> certList; if (certFile != "-system-") { certList = QSslCertificate::fromPath(certFile); // Use those certificates when fetching payment requests, too: QSslSocket::setDefaultCaCertificates(certList); } else certList = QSslSocket::systemCaCertificates (); int nRootCerts = 0; const QDateTime currentTime = QDateTime::currentDateTime(); foreach (const QSslCertificate& cert, certList) { if (currentTime < cert.effectiveDate() || currentTime > cert.expiryDate()) { ReportInvalidCertificate(cert); continue; } #if QT_VERSION >= 0x050000 if (cert.isBlacklisted()) { ReportInvalidCertificate(cert); continue; } #endif QByteArray certData = cert.toDer(); const unsigned char *data = (const unsigned char *)certData.data(); X509* x509 = d2i_X509(0, &data, certData.size()); if (x509 && X509_STORE_add_cert(PaymentServer::certStore, x509)) { // Note: X509_STORE_free will free the X509* objects when // the PaymentServer is destroyed ++nRootCerts; } else { ReportInvalidCertificate(cert); continue; } } if (fDebug) qDebug() << "PaymentServer::LoadRootCAs : Loaded " << nRootCerts << " root certificates"; // Project for another day: // Fetch certificate revocation lists, and add them to certStore. // Issues to consider: // performance (start a thread to fetch in background?) // privacy (fetch through tor/proxy so IP address isn't revealed) // would it be easier to just use a compiled-in blacklist? // or use Qt's blacklist? // "certificate stapling" with server-side caching is more efficient }
void AddTimeData(const CNetAddr& ip, int64_t nOffsetSample) { LOCK(cs_nTimeOffset); // Ignore duplicates static std::set<CNetAddr> setKnown; if (setKnown.size() == GULDEN_TIMEDATA_MAX_SAMPLES) return; if (!setKnown.insert(ip).second) return; // Add data static CMedianFilter<int64_t> vTimeOffsets(GULDEN_TIMEDATA_MAX_SAMPLES, 0); vTimeOffsets.input(nOffsetSample); LogPrint(BCLog::NET,"added time data, samples %d, offset %+d (%+d minutes)\n", vTimeOffsets.size(), nOffsetSample, nOffsetSample/60); // There is a known issue here (see issue #4521): // // - The structure vTimeOffsets contains up to 200 elements, after which // any new element added to it will not increase its size, replacing the // oldest element. // // - The condition to update nTimeOffset includes checking whether the // number of elements in vTimeOffsets is odd, which will never happen after // there are 200 elements. // // But in this case the 'bug' is protective against some attacks, and may // actually explain why we've never seen attacks which manipulate the // clock offset. // // So we should hold off on fixing this and clean it up as part of // a timing cleanup that strengthens it in a number of other ways. // if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1) { int64_t nMedian = vTimeOffsets.median(); std::vector<int64_t> vSorted = vTimeOffsets.sorted(); // Only let other nodes change our time by so much if (abs64(nMedian) <= std::max<int64_t>(0, GetArg("-maxtimeadjustment", DEFAULT_MAX_TIME_ADJUSTMENT))) { nTimeOffset = nMedian; } else { nTimeOffset = 0; static bool fDone; if (!fDone) { // If nobody has a time different than ours but within 5 minutes of ours, give a warning bool fMatch = false; for(int64_t nOffset : vSorted) if (nOffset != 0 && abs64(nOffset) < 5 * 60) fMatch = true; if (!fMatch) { fDone = true; std::string strMessage = strprintf(_("Please check that your computer's date and time are correct! If your clock is wrong, %s will not work properly."), _(PACKAGE_NAME)); SetMiscWarning(strMessage); uiInterface.ThreadSafeMessageBox(strMessage, "", CClientUIInterface::MSG_WARNING); } } } if (LogAcceptCategory(BCLog::NET)) { for(int64_t n : vSorted) { LogPrint(BCLog::NET, "%+d ", n); } LogPrint(BCLog::NET, "| "); LogPrint(BCLog::NET, "nTimeOffset = %+d (%+d minutes)\n", nTimeOffset, nTimeOffset/60); } } }
UniValue CallRPC(const std::string& strMethod, const UniValue& params) { std::string host = GetArg("-rpcconnect", DEFAULT_RPCCONNECT); int port = GetArg("-rpcport", BaseParams().RPCPort()); // Obtain event base raii_event_base base = obtain_event_base(); // Synchronously look up hostname raii_evhttp_connection evcon = obtain_evhttp_connection_base(base.get(), host, port); evhttp_connection_set_timeout(evcon.get(), GetArg("-rpcclienttimeout", DEFAULT_HTTP_CLIENT_TIMEOUT)); HTTPReply response; raii_evhttp_request req = obtain_evhttp_request(http_request_done, (void*)&response); if (req == NULL) throw std::runtime_error("create http request failed"); #if LIBEVENT_VERSION_NUMBER >= 0x02010300 evhttp_request_set_error_cb(req.get(), http_error_cb); #endif // Get credentials std::string strRPCUserColonPass; if (GetArg("-rpcpassword", "") == "") { // Try fall back to cookie-based authentication if no password is provided if (!GetAuthCookie(&strRPCUserColonPass)) { throw std::runtime_error(strprintf( _("Could not locate RPC credentials. No authentication cookie could be found, and no rpcpassword is set in the configuration file (%s)"), GetConfigFile(GetArg("-conf", BITCOIN_CONF_FILENAME)).string().c_str())); } } else { strRPCUserColonPass = GetArg("-rpcuser", "") + ":" + GetArg("-rpcpassword", ""); } struct evkeyvalq* output_headers = evhttp_request_get_output_headers(req.get()); assert(output_headers); evhttp_add_header(output_headers, "Host", host.c_str()); evhttp_add_header(output_headers, "Connection", "close"); evhttp_add_header(output_headers, "Authorization", (std::string("Basic ") + EncodeBase64(strRPCUserColonPass)).c_str()); // Attach request data std::string strRequest = JSONRPCRequestObj(strMethod, params, 1).write() + "\n"; struct evbuffer* output_buffer = evhttp_request_get_output_buffer(req.get()); assert(output_buffer); evbuffer_add(output_buffer, strRequest.data(), strRequest.size()); int r = evhttp_make_request(evcon.get(), req.get(), EVHTTP_REQ_POST, "/"); req.release(); // ownership moved to evcon in above call if (r != 0) { throw CConnectionFailed("send http request failed"); } event_base_dispatch(base.get()); if (response.status == 0) throw CConnectionFailed(strprintf("couldn't connect to server: %s (code %d)\n(make sure server is running and you are connecting to the correct RPC port)", http_errorstring(response.error), response.error)); else if (response.status == HTTP_UNAUTHORIZED) throw std::runtime_error("incorrect rpcuser or rpcpassword (authorization failed)"); else if (response.status >= 400 && response.status != HTTP_BAD_REQUEST && response.status != HTTP_NOT_FOUND && response.status != HTTP_INTERNAL_SERVER_ERROR) throw std::runtime_error(strprintf("server returned HTTP error %d", response.status)); else if (response.body.empty()) throw std::runtime_error("no response from server"); // Parse reply UniValue valReply(UniValue::VSTR); if (!valReply.read(response.body)) throw std::runtime_error("couldn't parse reply from server"); const UniValue& reply = valReply.get_obj(); if (reply.empty()) throw std::runtime_error("expected reply to have result, error and id properties"); return reply; }
/********************************* * main - this is where it begins *********************************/ int main(int argc, char **argv) { std::cout << "********************************************" << std::endl; std::cout << "*** ptsminer - Pts Pool Miner v" << VERSION_MAJOR << "." << VERSION_MINOR << " " << VERSION_EXT << std::endl; std::cout << "*** by xolokram/TB - www.beeeeer.org - glhf" << std::endl; std::cout << "***" << std::endl; std::cout << "*** press CTRL+C to exit" << std::endl; std::cout << "********************************************" << std::endl; t_start = boost::posix_time::second_clock::universal_time(); running = true; #if defined(__MINGW32__) || defined(__MINGW64__) SetConsoleCtrlHandler(ctrl_handler, TRUE); #elif defined(__GNUG__) && !defined(__APPLE__) set_signal_handler(SIGINT, ctrl_handler); #endif if (argc < 2) { std::cerr << "usage: " << argv[0] << " -poolfee=<fee-in-%> -poolip=<ip> -poolport=<port> -pooluser=<user> -poolpassword=<password>" << std::endl; return EXIT_FAILURE; } const int atexit_res = std::atexit(exit_handler); if (atexit_res != 0) std::cerr << "atexit registration failed, shutdown will be dirty!" << std::endl; // init everything: ParseParameters(argc, argv); socket_to_server = NULL; //pool_share_minimum = (unsigned int)GetArg("-poolshare", 7); thread_num_max = GetArg("-genproclimit", 1); // what about boost's hardware_concurrency() ? fee_to_pay = GetArg("-poolfee", 3); miner_id = GetArg("-minerid", 0); pool_username = GetArg("-pooluser", ""); pool_password = GetArg("-poolpassword", ""); if (thread_num_max == 0 || thread_num_max > MAX_THREADS) { std::cerr << "usage: " << "current maximum supported number of threads = " << MAX_THREADS << std::endl; return EXIT_FAILURE; } if (fee_to_pay == 0 || fee_to_pay > 100) { std::cerr << "usage: " << "please use a pool fee between [1 , 100]" << std::endl; return EXIT_FAILURE; } if (miner_id > 65535) { std::cerr << "usage: " << "please use a miner id between [0 , 65535]" << std::endl; return EXIT_FAILURE; } { //password to sha1 boost::uuids::detail::sha1 sha; sha.process_bytes(pool_password.c_str(), pool_password.size()); unsigned int digest[5]; sha.get_digest(digest); std::stringstream ss; ss << std::setw(5) << std::setfill('0') << std::hex << (digest[0] ^ digest[1] ^ digest[4]) << (digest[2] ^ digest[3] ^ digest[4]); pool_password = ss.str(); } std::cout << pool_username << std::endl; fPrintToConsole = true; // always on fDebug = GetBoolArg("-debug"); pindexBest = new CBlockIndex(); //GeneratePrimeTable(); // ok, start mining: CBlockProviderGW* bprovider = new CBlockProviderGW(); CMasterThread *mt = new CMasterThread(bprovider); mt->run(); // end: return EXIT_SUCCESS; }
void run() { { boost::unique_lock<boost::shared_mutex> lock(_mutex_master); std::cout << "spawning " << thread_num_max << " worker thread(s)" << std::endl; for (unsigned int i = 0; i < thread_num_max; ++i) { CWorkerThread *worker = new CWorkerThread(this, i, _bprovider); worker->work(); } } boost::asio::io_service io_service; boost::asio::ip::tcp::resolver resolver(io_service); //resolve dns boost::asio::ip::tcp::resolver::query query(GetArg("-poolip", "127.0.0.1"), GetArg("-poolport", "1337")); boost::asio::ip::tcp::resolver::iterator endpoint; boost::asio::ip::tcp::resolver::iterator end; boost::asio::ip::tcp::no_delay nd_option(true); boost::asio::socket_base::keep_alive ka_option(true); while (running) { endpoint = resolver.resolve(query); boost::scoped_ptr<boost::asio::ip::tcp::socket> socket; boost::system::error_code error_socket = boost::asio::error::host_not_found; while (error_socket && endpoint != end) { //socket->close(); socket.reset(new boost::asio::ip::tcp::socket(io_service)); boost::asio::ip::tcp::endpoint tcp_ep = *endpoint++; socket->connect(tcp_ep, error_socket); std::cout << "connecting to " << tcp_ep << std::endl; } socket->set_option(nd_option); socket->set_option(ka_option); if (error_socket) { std::cout << error_socket << std::endl; boost::this_thread::sleep(boost::posix_time::seconds(10)); continue; } { //send hello message char* hello = new char[pool_username.length()+/*v0.2/0.3=*/2+/*v0.4=*/20+/*v0.7=*/1+pool_password.length()]; memcpy(hello+1, pool_username.c_str(), pool_username.length()); *((unsigned char*)hello) = pool_username.length(); *((unsigned char*)(hello+pool_username.length()+1)) = 0; //hi, i'm v0.4+ *((unsigned char*)(hello+pool_username.length()+2)) = VERSION_MAJOR; *((unsigned char*)(hello+pool_username.length()+3)) = VERSION_MINOR; *((unsigned char*)(hello+pool_username.length()+4)) = thread_num_max; *((unsigned char*)(hello+pool_username.length()+5)) = fee_to_pay; *((unsigned short*)(hello+pool_username.length()+6)) = miner_id; *((unsigned int*)(hello+pool_username.length()+8)) = 0; *((unsigned int*)(hello+pool_username.length()+12)) = 0; *((unsigned int*)(hello+pool_username.length()+16)) = 0; *((unsigned char*)(hello+pool_username.length()+20)) = pool_password.length(); memcpy(hello+pool_username.length()+21, pool_password.c_str(), pool_password.length()); *((unsigned short*)(hello+pool_username.length()+21+pool_password.length())) = 0; //EXTENSIONS boost::system::error_code error; socket->write_some(boost::asio::buffer(hello, pool_username.length()+2+20+1+pool_password.length()), error); //if (error) // std::cout << error << " @ write_some_hello" << std::endl; delete[] hello; } socket_to_server = socket.get(); //TODO: lock/mutex int reject_counter = 0; bool done = false; while (!done) { int type = -1; { //get the data header unsigned char buf = 0; //get header boost::system::error_code error; size_t len = boost::asio::read(*socket_to_server, boost::asio::buffer(&buf, 1), boost::asio::transfer_all(), error); //size_t len = socket->read_some(boost::asio::buffer(&buf, 1), error); if (error == boost::asio::error::eof) break; // Connection closed cleanly by peer. else if (error) { //std::cout << error << " @ read_some1" << std::endl; break; } type = buf; if (len != 1) std::cout << "error on read1: " << len << " should be " << 1 << std::endl; } switch (type) { case 0: { size_t buf_size = 112; //*thread_num_max; unsigned char* buf = new unsigned char[buf_size]; //get header boost::system::error_code error; size_t len = boost::asio::read(*socket_to_server, boost::asio::buffer(buf, buf_size), boost::asio::transfer_all(), error); //size_t len = socket->read_some(boost::asio::buffer(buf, buf_size), error); //while (len < buf_size) // len += socket->read_some(boost::asio::buffer(buf+len, buf_size-len), error); if (error == boost::asio::error::eof) { done = true; break; // Connection closed cleanly by peer. } else if (error) { //std::cout << error << " @ read2a" << std::endl; done = true; break; } if (len == buf_size) { _bprovider->setBlocksFromData(buf); std::cout << "[MASTER] work received"<< std::endl; std::cout << "[MASTER] network target:"<< nNetworkBits.ToString().c_str() << std::endl; std::cout << "[MASTER] share target:"<< nShareBits.ToString().c_str() << std::endl; } else std::cout << "error on read2a: " << len << " should be " << buf_size << std::endl; delete[] buf; CBlockIndex *pindexOld = pindexBest; pindexBest = new CBlockIndex(); //=notify worker (this could need a efficient alternative) delete pindexOld; } break; case 1: { size_t buf_size = 4; int buf; //get header boost::system::error_code error; size_t len = boost::asio::read(*socket_to_server, boost::asio::buffer(&buf, buf_size), boost::asio::transfer_all(), error); //size_t len = socket->read_some(boost::asio::buffer(&buf, buf_size), error); //while (len < buf_size) // len += socket->read_some(boost::asio::buffer(&buf+len, buf_size-len), error); if (error == boost::asio::error::eof) { done = true; break; // Connection closed cleanly by peer. } else if (error) { //std::cout << error << " @ read2b" << std::endl; done = true; break; } if (len == buf_size) { int retval = buf > 1000 ? 1 : buf; std::cout << "[MASTER] submitted share -> " << (retval == 0 ? "REJECTED" : retval < 0 ? "STALE" : retval == 1 ? "BLOCK" : "SHARE") << std::endl; std::map<int,unsigned long>::iterator it = statistics.find(retval); if (retval > 0) reject_counter = 0; else reject_counter++; // if (reject_counter >= 3) { // std::cout << "too many rejects (3) in a row, forcing reconnect." << std::endl; // socket->close(); // done = true; // } if (it == statistics.end()) statistics.insert(std::pair<int,unsigned long>(retval,1)); else statistics[retval]++; stats_running(); } else std::cout << "error on read2b: " << len << " should be " << buf_size << std::endl; } break; case 2: { //PING-PONG EVENT, nothing to do } break; default: { //std::cout << "unknown header type = " << type << std::endl; } } } socket_to_server = NULL; //TODO: lock/mutex for (int i = 0; i < 50 && submitting_share < 1; ++i) //wait <5 seconds until reconnect (force reconnect when share is waiting to be submitted) boost::this_thread::sleep(boost::posix_time::milliseconds(100)); } }
//______________________________________________________________________________ // [] //` OBServer_Help [] // [] void OBServer_Help (void ** ppData, string_arr& FnNames, string_arr& FnDesc, CPtr<FUNCTION_ARGS>& REGISTERED_FUNCTIONS_ARGS, const char * InputArgs) { int OBServer_result = OBServer_OK; OBServer_WRAPPER_START; string OutArgs; OutArgs.Format( "%ca1%ca2%ca3%ca4%ca5%ca6%ca7%ca8", ARG_NAME_HEADER_CHAR, ARG_NAME_HEADER_CHAR, ARG_NAME_HEADER_CHAR, ARG_NAME_HEADER_CHAR, ARG_NAME_HEADER_CHAR, ARG_NAME_HEADER_CHAR, ARG_NAME_HEADER_CHAR, ARG_NAME_HEADER_CHAR); // Список функций с описаниями int FuncNum = -1; if (!GetArg(InputArgs, FuncNum, "a1")) { // Запись имён функций в выходной буфер: PackArg(OutArgs.c_str(), FnNames, "a1", BufferPos); PackArg(OutArgs.c_str(), FnDesc, "a2", BufferPos); } else // Описание аргументов функции { if ((FuncNum >= 0) && (FuncNum < REGISTERED_FUNCTIONS_ARGS.Size())) { // Функция PackArg(OutArgs.c_str(), FnNames[FuncNum], "a1", BufferPos); PackArg(OutArgs.c_str(), FnDesc[FuncNum], "a2", BufferPos); // Входные аргументы PackArg( OutArgs.c_str(), REGISTERED_FUNCTIONS_ARGS[FuncNum].InArgs_Type, "a3", BufferPos); PackArg( OutArgs.c_str(), REGISTERED_FUNCTIONS_ARGS[FuncNum].InArgs_Name, "a4", BufferPos); PackArg( OutArgs.c_str(), REGISTERED_FUNCTIONS_ARGS[FuncNum].InArgs_Description, "a5", BufferPos); // Выходные аргументы PackArg( OutArgs.c_str(), REGISTERED_FUNCTIONS_ARGS[FuncNum].OutArgs_Type, "a6", BufferPos); PackArg( OutArgs.c_str(), REGISTERED_FUNCTIONS_ARGS[FuncNum].OutArgs_Name, "a7", BufferPos); PackArg( OutArgs.c_str(), REGISTERED_FUNCTIONS_ARGS[FuncNum].OutArgs_Description, "a8", BufferPos); } else { OBServer_result = OBServer_SYSTEM_ERROR; } } if (OBServer_result == OBServer_OK) { } OBServer_WRAPPER_END; }
QVariant OptionsModel::data(const QModelIndex & index, int role) const { if(role == Qt::EditRole) { QSettings settings; switch(index.row()) { case StartAtStartup: return QVariant(GUIUtil::GetStartOnSystemStartup()); case MinimizeToTray: return QVariant(fMinimizeToTray); case MapPortUPnP: return settings.value("fUseUPnP", GetBoolArg("-upnp", true)); case MinimizeOnClose: return QVariant(fMinimizeOnClose); case ProxyUse: return settings.value("fUseProxy", false); case ProxyIP: { proxyType proxy; if (GetProxy(NET_IPV4, proxy)) return QVariant(QString::fromStdString(proxy.ToStringIP())); else return QVariant(QString::fromStdString("127.0.0.1")); } case ProxyPort: { proxyType proxy; if (GetProxy(NET_IPV4, proxy)) return QVariant(proxy.GetPort()); else return QVariant(9050); } case Fee: return QVariant((qint64) nTransactionFee); case ReserveBalance: return QVariant((qint64) nReserveBalance); case DisplayUnit: return QVariant(nDisplayUnit); case Language: return settings.value("language", ""); case CoinControlFeatures: return QVariant(fCoinControlFeatures); case SandstormRounds: return QVariant(nSandstormRounds); case AnonymizeDarkSilkAmount: return QVariant(nAnonymizeDarkSilkAmount); case UseBlackTheme: return QVariant(fUseBlackTheme); #ifdef USE_NATIVE_I2P case I2PUseI2POnly: { ScopeGroupHelper s(settings, I2P_OPTIONS_SECTION_NAME); bool useI2POnly = false; if (mapArgs.count("-onlynet")) { const std::vector<std::string>& onlyNets = mapMultiArgs["-onlynet"]; if (std::find(onlyNets.begin(), onlyNets.end(), NATIVE_I2P_NET_STRING) != onlyNets.end()) useI2POnly = true; } return settings.value("useI2POnly", useI2POnly); } case I2PSAMHost: { ScopeGroupHelper s(settings, I2P_OPTIONS_SECTION_NAME); return settings.value("samhost", QString::fromStdString(GetArg(I2P_SAM_HOST_PARAM, I2P_SAM_HOST_DEFAULT))); } case I2PSAMPort: { ScopeGroupHelper s(settings, I2P_OPTIONS_SECTION_NAME); return settings.value("samport", QString::number((qint64)GetArg(I2P_SAM_PORT_PARAM, I2P_SAM_PORT_DEFAULT))); } case I2PSessionName: { ScopeGroupHelper s(settings, I2P_OPTIONS_SECTION_NAME); return settings.value("sessionName", QString::fromStdString(GetArg(I2P_SESSION_NAME_PARAM, I2P_SESSION_NAME_DEFAULT))); } case I2PInboundQuantity: return QVariant(i2pInboundQuantity); case I2PInboundLength: return QVariant(i2pInboundLength); case I2PInboundLengthVariance: return QVariant(i2pInboundLengthVariance); case I2PInboundBackupQuantity: return QVariant(i2pInboundBackupQuantity); case I2PInboundAllowZeroHop: return QVariant(i2pInboundAllowZeroHop); case I2PInboundIPRestriction: return QVariant(i2pInboundIPRestriction); case I2POutboundQuantity: return QVariant(i2pOutboundQuantity); case I2POutboundLength: return QVariant(i2pOutboundLength); case I2POutboundLengthVariance: return QVariant(i2pOutboundLengthVariance); case I2POutboundBackupQuantity: return QVariant(i2pOutboundBackupQuantity); case I2POutboundAllowZeroHop: return QVariant(i2pOutboundAllowZeroHop); case I2POutboundIPRestriction: return QVariant(i2pOutboundIPRestriction); case I2POutboundPriority: return QVariant(i2pOutboundPriority); #endif default: return QVariant(); } } return QVariant(); }
// // Load OpenSSL's list of root certificate authorities // void PaymentServer::LoadRootCAs(X509_STORE* _store) { // Unit tests mostly use this, to pass in fake root CAs: if (_store) { certStore.reset(_store); return; } // Normal execution, use either -rootcertificates or system certs: certStore.reset(X509_STORE_new()); // Note: use "-system-" default here so that users can pass -rootcertificates="" // and get 'I don't like X.509 certificates, don't trust anybody' behavior: QString certFile = QString::fromStdString(GetArg("-rootcertificates", "-system-")); // Empty store if (certFile.isEmpty()) { qDebug() << QString("PaymentServer::%1: Payment request authentication via X.509 certificates disabled.").arg(__func__); return; } QList<QSslCertificate> certList; if (certFile != "-system-") { qDebug() << QString("PaymentServer::%1: Using \"%2\" as trusted root certificate.").arg(__func__).arg(certFile); certList = QSslCertificate::fromPath(certFile); // Use those certificates when fetching payment requests, too: QSslSocket::setDefaultCaCertificates(certList); } else certList = QSslSocket::systemCaCertificates(); int nRootCerts = 0; const QDateTime currentTime = QDateTime::currentDateTime(); Q_FOREACH (const QSslCertificate& cert, certList) { // Don't log NULL certificates if (cert.isNull()) continue; // Not yet active/valid, or expired certificate if (currentTime < cert.effectiveDate() || currentTime > cert.expiryDate()) { ReportInvalidCertificate(cert); continue; } #if QT_VERSION >= 0x050000 // Blacklisted certificate if (cert.isBlacklisted()) { ReportInvalidCertificate(cert); continue; } #endif QByteArray certData = cert.toDer(); const unsigned char *data = (const unsigned char *)certData.data(); std::unique_ptr<X509, X509Deleter> x509(d2i_X509(0, &data, certData.size())); if (x509 && X509_STORE_add_cert(certStore.get(), x509.get())) { // Note: X509_STORE increases the reference count to the X509 object, // we still have to release our reference to it. ++nRootCerts; } else { ReportInvalidCertificate(cert); continue; } } qWarning() << "PaymentServer::LoadRootCAs: Loaded " << nRootCerts << " root certificates"; // Project for another day: // Fetch certificate revocation lists, and add them to certStore. // Issues to consider: // performance (start a thread to fetch in background?) // privacy (fetch through tor/proxy so IP address isn't revealed) // would it be easier to just use a compiled-in blacklist? // or use Qt's blacklist? // "certificate stapling" with server-side caching is more efficient }
CFeeBumper::CFeeBumper(const CWallet *pWallet, const uint256 txidIn, int newConfirmTarget, bool ignoreGlobalPayTxFee, CAmount totalFee, bool newTxReplaceable, FeeEstimateMode fee_mode) : txid(std::move(txidIn)), nOldFee(0), nNewFee(0) { vErrors.clear(); bumpedTxid.SetNull(); AssertLockHeld(pWallet->cs_wallet); if (!pWallet->mapWallet.count(txid)) { vErrors.push_back("Invalid or non-wallet transaction id"); currentResult = BumpFeeResult::INVALID_ADDRESS_OR_KEY; return; } auto it = pWallet->mapWallet.find(txid); const CWalletTx& wtx = it->second; if (!preconditionChecks(pWallet, wtx)) { return; } if (!SignalsOptInRBF(wtx)) { vErrors.push_back("Transaction is not BIP 125 replaceable"); currentResult = BumpFeeResult::WALLET_ERROR; return; } if (wtx.mapValue.count("replaced_by_txid")) { vErrors.push_back(strprintf("Cannot bump transaction %s which was already bumped by transaction %s", txid.ToString(), wtx.mapValue.at("replaced_by_txid"))); currentResult = BumpFeeResult::WALLET_ERROR; return; } // check that original tx consists entirely of our inputs // if not, we can't bump the fee, because the wallet has no way of knowing the value of the other inputs (thus the fee) if (!pWallet->IsAllFromMe(wtx, ISMINE_SPENDABLE)) { vErrors.push_back("Transaction contains inputs that don't belong to this wallet"); currentResult = BumpFeeResult::WALLET_ERROR; return; } // figure out which output was change // if there was no change output or multiple change outputs, fail int nOutput = -1; for (size_t i = 0; i < wtx.tx->vout.size(); ++i) { if (pWallet->IsChange(wtx.tx->vout[i])) { if (nOutput != -1) { vErrors.push_back("Transaction has multiple change outputs"); currentResult = BumpFeeResult::WALLET_ERROR; return; } nOutput = i; } } if (nOutput == -1) { vErrors.push_back("Transaction does not have a change output"); currentResult = BumpFeeResult::WALLET_ERROR; return; } // Calculate the expected size of the new transaction. int64_t txSize = GetVirtualTransactionSize(*(wtx.tx)); const int64_t maxNewTxSize = CalculateMaximumSignedTxSize(*wtx.tx, pWallet); if (maxNewTxSize < 0) { vErrors.push_back("Transaction contains inputs that cannot be signed"); currentResult = BumpFeeResult::INVALID_ADDRESS_OR_KEY; return; } // calculate the old fee and fee-rate nOldFee = wtx.GetDebit(ISMINE_SPENDABLE) - wtx.tx->GetValueOut(); CFeeRate nOldFeeRate(nOldFee, txSize); CFeeRate nNewFeeRate; // The wallet uses a conservative WALLET_INCREMENTAL_RELAY_FEE value to // future proof against changes to network wide policy for incremental relay // fee that our node may not be aware of. CFeeRate walletIncrementalRelayFee = CFeeRate(WALLET_INCREMENTAL_RELAY_FEE); if (::incrementalRelayFee > walletIncrementalRelayFee) { walletIncrementalRelayFee = ::incrementalRelayFee; } if (totalFee > 0) { CAmount minTotalFee = nOldFeeRate.GetFee(maxNewTxSize) + ::incrementalRelayFee.GetFee(maxNewTxSize); if (totalFee < minTotalFee) { vErrors.push_back(strprintf("Insufficient totalFee, must be at least %s (oldFee %s + incrementalFee %s)", FormatMoney(minTotalFee), FormatMoney(nOldFeeRate.GetFee(maxNewTxSize)), FormatMoney(::incrementalRelayFee.GetFee(maxNewTxSize)))); currentResult = BumpFeeResult::INVALID_PARAMETER; return; } CAmount requiredFee = CWallet::GetRequiredFee(maxNewTxSize); if (totalFee < requiredFee) { vErrors.push_back(strprintf("Insufficient totalFee (cannot be less than required fee %s)", FormatMoney(requiredFee))); currentResult = BumpFeeResult::INVALID_PARAMETER; return; } nNewFee = totalFee; nNewFeeRate = CFeeRate(totalFee, maxNewTxSize); } else { bool conservative_estimate = CalculateEstimateType(fee_mode, newTxReplaceable); nNewFee = CWallet::GetMinimumFee(maxNewTxSize, newConfirmTarget, mempool, ::feeEstimator, nullptr /* FeeCalculation */, ignoreGlobalPayTxFee, conservative_estimate); nNewFeeRate = CFeeRate(nNewFee, maxNewTxSize); // New fee rate must be at least old rate + minimum incremental relay rate // walletIncrementalRelayFee.GetFeePerK() should be exact, because it's initialized // in that unit (fee per kb). // However, nOldFeeRate is a calculated value from the tx fee/size, so // add 1 satoshi to the result, because it may have been rounded down. if (nNewFeeRate.GetFeePerK() < nOldFeeRate.GetFeePerK() + 1 + walletIncrementalRelayFee.GetFeePerK()) { nNewFeeRate = CFeeRate(nOldFeeRate.GetFeePerK() + 1 + walletIncrementalRelayFee.GetFeePerK()); nNewFee = nNewFeeRate.GetFee(maxNewTxSize); } } // Check that in all cases the new fee doesn't violate maxTxFee if (nNewFee > maxTxFee) { vErrors.push_back(strprintf("Specified or calculated fee %s is too high (cannot be higher than maxTxFee %s)", FormatMoney(nNewFee), FormatMoney(maxTxFee))); currentResult = BumpFeeResult::WALLET_ERROR; return; } // check that fee rate is higher than mempool's minimum fee // (no point in bumping fee if we know that the new tx won't be accepted to the mempool) // This may occur if the user set TotalFee or paytxfee too low, if fallbackfee is too low, or, perhaps, // in a rare situation where the mempool minimum fee increased significantly since the fee estimation just a // moment earlier. In this case, we report an error to the user, who may use totalFee to make an adjustment. CFeeRate minMempoolFeeRate = mempool.GetMinFee(GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000); if (nNewFeeRate.GetFeePerK() < minMempoolFeeRate.GetFeePerK()) { vErrors.push_back(strprintf("New fee rate (%s) is less than the minimum fee rate (%s) to get into the mempool. totalFee value should to be at least %s or settxfee value should be at least %s to add transaction.", FormatMoney(nNewFeeRate.GetFeePerK()), FormatMoney(minMempoolFeeRate.GetFeePerK()), FormatMoney(minMempoolFeeRate.GetFee(maxNewTxSize)), FormatMoney(minMempoolFeeRate.GetFeePerK()))); currentResult = BumpFeeResult::WALLET_ERROR; return; } // Now modify the output to increase the fee. // If the output is not large enough to pay the fee, fail. CAmount nDelta = nNewFee - nOldFee; assert(nDelta > 0); mtx = *wtx.tx; CTxOut* poutput = &(mtx.vout[nOutput]); if (poutput->nValue < nDelta) { vErrors.push_back("Change output is too small to bump the fee"); currentResult = BumpFeeResult::WALLET_ERROR; return; } // If the output would become dust, discard it (converting the dust to fee) poutput->nValue -= nDelta; if (poutput->nValue <= GetDustThreshold(*poutput, ::dustRelayFee)) { LogPrint(BCLog::RPC, "Bumping fee and discarding dust output\n"); nNewFee += poutput->nValue; mtx.vout.erase(mtx.vout.begin() + nOutput); } // Mark new tx not replaceable, if requested. if (!newTxReplaceable) { for (auto& input : mtx.vin) { if (input.nSequence < 0xfffffffe) input.nSequence = 0xfffffffe; } } currentResult = BumpFeeResult::OK; }
int startup(int argc, char *argv[]) { int i, len; FULL_CHAR *arg; OBJECT t, y, res, s; /* current token, parser output */ BOOLEAN stdin_seen; /* TRUE when stdin file seen */ int source_file_count; /* number of source files in command */ FULL_CHAR *cross_db; /* name of cross reference database */ FULL_CHAR *outfile; /* name of output file */ FULL_CHAR *lib; /* name of library directory */ FILE *out_fp; long MemCheckLong; FULL_CHAR oname[MAX_BUFF], oval[MAX_BUFF], buff[MAX_BUFF], *p; int bp; OBJECT z; BOOLEAN seen_wordcount; #if LOCALE_ON char catname[MAX_BUFF], *loc; #endif /* find the name of the library directory, from envt or else from -D */ lib = AsciiToFull(getenv("LOUTLIB")); if( lib == (FULL_CHAR *) NULL ) lib = AsciiToFull(LIB_DIR); /* set locale if that's what we are doing */ #if LOCALE_ON loc = setlocale(LC_MESSAGES, ""); if( loc == (char *) NULL ) { Error(1, 6, "unable to initialize locale", WARN, no_fpos); loc = "C"; } sprintf(catname, "%s/%s/%s/LC_MESSAGES/errors.%s", lib, LOCALE_DIR, loc, loc); MsgCat = catopen(catname, 0); #endif /* initialise various modules, add current directory to search paths */ TotalWordCount = 0; seen_wordcount = FALSE; BackEnd = PS_BackEnd; PlainCharWidth = PLAIN_WIDTH; PlainCharHeight = PLAIN_HEIGHT; PlainFormFeed = FALSE; InitializeAll = FALSE; UseCollate = COLLATE; AllowCrossDb = TRUE; InMemoryDbIndexes = TRUE; Encapsulated = FALSE; SafeExecution = SAFE_DFT ? TRUE : FALSE; Kern = TRUE; MemInit(); InitSym(); LexInit(); InitFiles(); AddToPath(SOURCE_PATH, MakeWord(WORD, STR_EMPTY, no_fpos)); AddToPath(DATABASE_PATH, MakeWord(WORD, STR_EMPTY, no_fpos)); AddToPath(INCLUDE_PATH, MakeWord(WORD, STR_EMPTY, no_fpos)); /* read command line */ stdin_seen = FALSE; AltErrorFormat = FALSE; cross_db = CROSS_DB; outfile = STR_STDOUT; source_file_count = 0; New(CommandOptions, ACAT); for( i = 1; i < argc; i++ ) { if( *argv[i] == CH_HYPHEN ) switch( *(argv[i]+1) ) { case CH_FLAG_OUTFILE: /* read name of output file */ if( (outfile = GetArg(argv, argc, &i)) == NULL ) Error(1, 7, "usage: -o <filename>", FATAL, no_fpos); if( StringEndsWith(outfile, SOURCE_SUFFIX) ) Error(1, 28, "-o: output file name %s ends with %s", FATAL, no_fpos, outfile, SOURCE_SUFFIX); break; case CH_FLAG_SUPPRESS: /* suppress references to OldCrossDb and NewCrossDb */ AllowCrossDb = FALSE; break; case CH_FLAG_MEMCR: /* don't use in-memory database indexes */ InMemoryDbIndexes = FALSE; break; case CH_FLAG_NOKERN: /* suppress kerning */ Kern = FALSE; break; case CH_FLAG_NOCOLLATE: /* suppress local collation */ UseCollate = FALSE; break; case CH_FLAG_COLLATE: /* invoke local collation */ UseCollate = TRUE; break; case CH_FLAG_CROSS: /* read name of cross reference database */ if( (cross_db = GetArg(argv, argc, &i)) == NULL ) Error(1, 8, "usage: -c <filename>", FATAL, no_fpos); break; case CH_FLAG_ERRFILE: /* read log file name */ if( (arg = GetArg(argv, argc, &i)) == NULL ) Error(1, 9, "usage: -e <filename>", FATAL, no_fpos); ErrorInit(arg); break; case CH_FLAG_ALTERR: /* alternative error message format */ AltErrorFormat = TRUE; break; case CH_FLAG_EPSFIRST: /* -EPS produces encapsulated PostScript output */ if( !StringEqual(AsciiToFull(argv[i]+1), STR_EPS) ) Error(1, 10, "usage: -EPS", FATAL, no_fpos); Encapsulated = TRUE; break; case CH_FLAG_DIRPATH: /* add directory to database and sysdatabase paths */ if( (arg = GetArg(argv, argc, &i)) == NULL ) Error(1, 11, "usage: -D <directoryname>", FATAL, no_fpos); AddToPath(DATABASE_PATH, MakeWord(WORD, arg, no_fpos)); AddToPath(SYSDATABASE_PATH, MakeWord(WORD, arg, no_fpos)); break; case CH_FLAG_ENCPATH: /* add directory to character mapping path */ if( (arg = GetArg(argv, argc, &i)) == NULL ) Error(1, 12, "usage: -C <directoryname>", FATAL, no_fpos); AddToPath(MAPPING_PATH, MakeWord(WORD, arg, no_fpos)); break; case CH_FLAG_FNTPATH: /* add directory to font path */ if( (arg = GetArg(argv, argc, &i)) == NULL ) Error(1, 13, "usage: -F <directoryname>", FATAL, no_fpos); AddToPath(FONT_PATH, MakeWord(WORD, arg, no_fpos)); break; case CH_FLAG_HYPPATH: /* add directory to hyph path */ if( (arg = GetArg(argv, argc, &i)) == NULL ) Error(1, 14, "usage: -H <directoryname>", FATAL, no_fpos); AddToPath(HYPH_PATH, MakeWord(WORD, arg, no_fpos)); break; case CH_FLAG_INCPATH: /* add directory to include and sysinclude paths */ if( (arg = GetArg(argv, argc, &i)) == NULL ) Error(1, 15, "usage: -I <directoryname>", FATAL, no_fpos); AddToPath(INCLUDE_PATH, MakeWord(WORD, arg, no_fpos)); AddToPath(SYSINCLUDE_PATH, MakeWord(WORD, arg, no_fpos)); break; case CH_FLAG_INCLUDE: /* read sysinclude file and strip any .lt suffix */ if( (arg = GetArg(argv, argc, &i)) == NULL ) Error(1, 16, "usage: -i <filename>", FATAL, no_fpos); len = StringLength(arg) - StringLength(SOURCE_SUFFIX); if( len >= 0 && StringEqual(&arg[len], SOURCE_SUFFIX) ) StringCopy(&arg[len], STR_EMPTY); debug0(DFS, D, " calling DefineFile from main (1)"); DefineFile(arg, STR_EMPTY, no_fpos, SOURCE_FILE, SYSINCLUDE_PATH); break; case CH_FLAG_HYPHEN: /* declare hyphenation file */ if( FirstFile(HYPH_FILE) != NO_FILE ) Error(1, 17, "two -h options illegal", FATAL, no_fpos); if( (arg = GetArg(argv, argc, &i)) == NULL ) Error(1, 18, "usage: -h <filename>", FATAL, no_fpos); debug0(DFS, D, " calling DefineFile from main (2)"); DefineFile(arg, STR_EMPTY, no_fpos, HYPH_FILE, INCLUDE_PATH); DefineFile(arg, HYPH_SUFFIX, no_fpos, HYPH_PACKED_FILE, INCLUDE_PATH); break; case CH_FLAG_VERSION: fprintf(stderr, "%s\n", LOUT_VERSION); fprintf(stderr, "%-28s %s\n", "Basser Lout written by:", "Jeffrey H. Kingston ([email protected])"); fprintf(stderr, "%-28s %s\n", "Free source available from:", "ftp://ftp.cs.usyd.edu.au/jeff/lout"); fprintf(stderr, "%-28s %s %s\n", "This executable compiled:", __TIME__, __DATE__); fprintf(stderr, "%-28s %s%s%s\n", "System include directory:", lib, STR_DIR, INCL_DIR); fprintf(stderr, "%-28s %s%s%s\n", "System database directory:", lib, STR_DIR, DATA_DIR); fprintf(stderr, "Database index files created afresh automatically:%s\n", USE_STAT ? " yes" : " no"); fprintf(stderr, "Safe execution (disabling system()) is default:%s\n", SAFE_DFT ? " yes" : " no"); fprintf(stderr, "strcoll() used for sorting by default:%s\n", COLLATE ? " yes" : " no"); fprintf(stderr, "PDF compression on:%s\n", PDF_COMPRESSION ? " yes" : " no"); fprintf(stderr, "Debugging (-d, -dd, -ddd flags) available:%s\n", DEBUG_ON ? " yes" : " no"); fprintf(stderr, "\n"); fprintf(stderr, "Basser Lout comes with ABSOLUTELY NO WARRANTY.\n"); fprintf(stderr, "This is free software, and you are welcome to\n"); fprintf(stderr, "redistribute it under certain conditions. For\n"); fprintf(stderr, "details on both points, consult the GNU General\n"); fprintf(stderr, "Public License (distributed with this software).\n"); exit(0); break; case CH_FLAG_WORDS: seen_wordcount = TRUE; break; case CH_FLAG_PDF: BackEnd = PDF_BackEnd; break; case CH_FLAG_FFPLAIN: if( StringEqual(AsciiToFull(argv[i]+1), STR_PDF) ) { BackEnd = PDF_BackEnd; break; } PlainFormFeed = TRUE; /* NB NO BREAK */ case CH_FLAG_PLAIN: BackEnd = Plain_BackEnd; if( *(argv[i]+2) != '\0' ) { float len1, len2; FULL_CHAR units1, units2; if( sscanf(argv[i]+2, "%f%c%f%c",&len1,&units1,&len2,&units2) != 4 ) { Error(1, 19, "usage: lout -%c<length><length>", FATAL, no_fpos, *(argv[i]+1)); } switch( units1 ) { case CH_UNIT_CM: PlainCharWidth = len1 * CM; break; case CH_UNIT_IN: PlainCharWidth = len1 * IN; break; case CH_UNIT_PT: PlainCharWidth = len1 * PT; break; case CH_UNIT_EM: PlainCharWidth = len1 * EM; break; default: Error(1, 20, "lout -%c: units must be c, i, p, or m", FATAL, no_fpos, *(argv[i]+1)); break; } switch( units2 ) { case CH_UNIT_CM: PlainCharHeight = len2 * CM; break; case CH_UNIT_IN: PlainCharHeight = len2 * IN; break; case CH_UNIT_PT: PlainCharHeight = len2 * PT; break; case CH_UNIT_EM: PlainCharHeight = len2 * EM; break; default: Error(1, 21, "lout -%c: units must be c, i, p, or m", FATAL, no_fpos, *(argv[i]+1)); break; } } break; case CH_FLAG_INITALL: InitializeAll = TRUE; AllowCrossDb = FALSE; break; case CH_FLAG_USAGE: PrintUsage(stderr); exit(0); break; case CH_FLAG_DEBUG: debug_init(AsciiToFull(argv[i])); break; case CH_FLAG_MEMCHECK: sscanf(argv[i], "-m%ld", &MemCheckLong); MemCheck = (POINTER) MemCheckLong; fprintf(stderr, "checking memory location %ld\n", (long) MemCheck); break; case '\0': /* read stdin as file name */ if( stdin_seen ) Error(1, 23, "standard input specified twice", FATAL, no_fpos); stdin_seen = TRUE; debug0(DFS, D, " calling DefineFile from main (3)"); DefineFile(STR_STDIN, STR_EMPTY, no_fpos, SOURCE_FILE, SOURCE_PATH); break; case CH_FLAG_OPTION: /* read command-line document option */ if( sscanf(argv[i]+2, "%[^{ ] { %[^}] }", oname, oval) != 2 || StringLength(oname) == 0 || StringLength(oval) == 0 ) Error(1, 24, "error in command-line option %s", FATAL, no_fpos, argv[i]+2); y = MakeWord(WORD, oname, no_fpos); Link(CommandOptions, y); New(y, ACAT); Link(CommandOptions, y); bp = 0; for( p = oval; *p != '\0'; p++ ) switch( *p ) { case ' ': case '\t': case '\n': case '{': case '}': if( bp > 0 ) { buff[bp++] = '\0'; if( Down(y) != y ) { OBJECT g; New(g, GAP_OBJ); hspace(g) = 1; vspace(g) = 0; FposCopy(fpos(g), *no_fpos); Link(y, g); } z = MakeWord(WORD, buff, no_fpos); Link(y, z); bp = 0; } break; default: buff[bp++] = *p; break; } if( bp > 0 ) { buff[bp++] = '\0'; z = MakeWord(WORD, buff, no_fpos); Link(y, z); } if( Down(y) == y ) Error(1, 25, "error in command-line option %s", FATAL, no_fpos, argv[i]+2); break; case CH_FLAG_SAFE: /* ensure safe execution by disabling system calls */ SafeExecution = TRUE; break; case CH_FLAG_UNSAFE: /* allow unsafe execution */ SafeExecution = FALSE; break; default: PrintUsage(stderr); Error(1, 26, "unknown command line flag %s", FATAL, no_fpos, argv[i]); break; } else { /* argument is source file, strip any .lout suffix and define it */ arg = AsciiToFull(argv[i]); len = StringLength(arg) - StringLength(SOURCE_SUFFIX); if( len >= 0 && StringEqual(&arg[len], SOURCE_SUFFIX) ) StringCopy(&arg[len], STR_EMPTY); debug0(DFS, D, " calling DefineFile from main (4)"); DefineFile(AsciiToFull(argv[i]), STR_EMPTY, no_fpos, SOURCE_FILE, SOURCE_PATH); source_file_count++; } } /* for */ if( UseCollate ) { if (!setlocale (LC_COLLATE, "")) Error(1, 30, "unable to initialize collation", WARN, no_fpos); } /* start timing if required */ ifdebug(DPP, D, ProfileOn("main")); /* open output file, or stdout if none specified, and initialize printer */ if( StringEqual(outfile, STR_STDOUT) ) { #if OS_DOS /* For DOS/Win32 we need to set binary mode on stdout to prevent PDF compressed streams and xrefs from being corrupted - Uwe 12/98 */ if( BackEnd->code != PLAINTEXT && _setmode(_fileno(stdout), _O_BINARY) == -1 ) Error(1, 31, "cannot set binary mode on stdout", FATAL, no_fpos); #endif out_fp = stdout; } else { out_fp = StringFOpen(outfile, BackEnd->code == PLAINTEXT ? WRITE_TEXT : WRITE_BINARY); if( out_fp == null ) Error(1, 27, "cannot open output file %s", FATAL, no_fpos, outfile); } /* initialize miscellaneous modules */ ColourInit(); LanguageInit(); BackEnd->PrintInitialize(out_fp); /* append default directories to file search paths */ AddToPath(FONT_PATH, MakeWordThree(lib, STR_DIR, AsciiToFull(FONT_DIR))); AddToPath(HYPH_PATH, MakeWordThree(lib, STR_DIR, AsciiToFull(HYPH_DIR))); AddToPath(MAPPING_PATH, MakeWordThree(lib, STR_DIR, AsciiToFull(MAPS_DIR))); AddToPath(SYSDATABASE_PATH,MakeWordThree(lib,STR_DIR, AsciiToFull(DATA_DIR))); AddToPath(DATABASE_PATH, MakeWordThree(lib, STR_DIR, AsciiToFull(DATA_DIR))); AddToPath(SYSINCLUDE_PATH,MakeWordThree(lib, STR_DIR, AsciiToFull(INCL_DIR))); AddToPath(INCLUDE_PATH, MakeWordThree(lib, STR_DIR, AsciiToFull(INCL_DIR))); /* use stdin if no source files were mentioned */ if( source_file_count == 0 ) { debug0(DFS, D, " calling DefineFile from main (5)"); DefineFile(STR_STDIN, STR_EMPTY, no_fpos, SOURCE_FILE, SOURCE_PATH); } /* load predefined symbols into symbol table */ StartSym = nilobj; /* Not a mistake */ StartSym = load(KW_START, 0, FALSE, FALSE, TRUE, NO_PREC ); GalleySym = load(KW_GALLEY, 0, FALSE, FALSE, TRUE, NO_PREC ); ForceGalleySym= load(KW_FORCE_GALLEY, 0, FALSE, FALSE, TRUE, NO_PREC ); InputSym = load(KW_INPUT, 0, FALSE, FALSE, TRUE, NO_PREC ); PrintSym = load(KW_PRINT, 0, FALSE, FALSE, TRUE, NO_PREC ); FilterInSym = load(KW_FILTERIN, 0, FALSE, FALSE, FALSE, NO_PREC ); FilterOutSym = load(KW_FILTEROUT, 0, FALSE, FALSE, FALSE, NO_PREC ); FilterErrSym = load(KW_FILTERERR, 0, FALSE, FALSE, FALSE, NO_PREC ); OptGallSym = load(KW_OPTGALL, 0, FALSE, TRUE, FALSE, DEFAULT_PREC); VerbatimSym = load(KW_VERBATIM,VERBATIM,FALSE, TRUE, FALSE, DEFAULT_PREC); RawVerbatimSym= load(KW_RAWVERBATIM,RAW_VERBATIM,FALSE,TRUE,FALSE,DEFAULT_PREC); load(KW_BEGIN, BEGIN, FALSE, FALSE, FALSE, BEGIN_PREC ); load(KW_END, END, FALSE, FALSE, FALSE, END_PREC ); load(KW_ENV, ENV, FALSE, FALSE, FALSE, NO_PREC ); load(KW_ENVA, ENVA, FALSE, FALSE, FALSE, NO_PREC ); load(KW_ENVB, ENVB, FALSE, FALSE, FALSE, NO_PREC ); load(KW_ENVC, ENVC, FALSE, FALSE, FALSE, NO_PREC ); load(KW_ENVD, ENVD, FALSE, FALSE, FALSE, NO_PREC ); load(KW_CENV, CENV, FALSE, FALSE, FALSE, NO_PREC ); load(KW_CLOS, CLOS, FALSE, FALSE, FALSE, NO_PREC ); load(KW_LVIS, LVIS, FALSE, FALSE, FALSE, NO_PREC ); load(KW_LUSE, LUSE, FALSE, FALSE, FALSE, NO_PREC ); load(KW_LEO, LEO, FALSE, FALSE, FALSE, NO_PREC ); load(KW_LBR, LBR, FALSE, FALSE, FALSE, LBR_PREC ); load(KW_RBR, RBR, FALSE, FALSE, FALSE, RBR_PREC ); load(KW_INCLUDE, INCLUDE, FALSE, FALSE, FALSE, NO_PREC ); load(KW_SYSINCLUDE, SYS_INCLUDE, FALSE, FALSE, FALSE, NO_PREC ); load(KW_PREPEND, PREPEND, FALSE, FALSE, FALSE, NO_PREC ); load(KW_SYSPREPEND, SYS_PREPEND, FALSE, FALSE, FALSE, NO_PREC ); load(KW_DATABASE, DATABASE, FALSE, FALSE, FALSE, NO_PREC ); load(KW_SYSDATABASE, SYS_DATABASE, FALSE, FALSE, FALSE, NO_PREC ); load(KW_USE, USE, FALSE, FALSE, FALSE, NO_PREC ); load(KW_NOT_REVEALED, NOT_REVEALED, FALSE, FALSE, FALSE, NO_PREC ); load(KW_CASE, CASE, TRUE, TRUE, FALSE, DEFAULT_PREC); load(KW_YIELD, YIELD, TRUE, TRUE, FALSE, DEFAULT_PREC); load(KW_BACKEND, BACKEND, FALSE, FALSE, FALSE, DEFAULT_PREC); load(KW_XCHAR, XCHAR, FALSE, TRUE, FALSE, DEFAULT_PREC); load(KW_FONT, FONT, TRUE, TRUE, FALSE, DEFAULT_PREC); load(KW_SPACE, SPACE, TRUE, TRUE, FALSE, DEFAULT_PREC); load(KW_YUNIT, YUNIT, TRUE, TRUE, FALSE, DEFAULT_PREC); load(KW_ZUNIT, ZUNIT, TRUE, TRUE, FALSE, DEFAULT_PREC); load(KW_BREAK, BREAK, TRUE, TRUE, FALSE, DEFAULT_PREC); load(KW_UNDERLINE, UNDERLINE, FALSE, TRUE, FALSE, DEFAULT_PREC); load(KW_COLOUR, COLOUR, TRUE, TRUE, FALSE, DEFAULT_PREC); load(KW_COLOR, COLOUR, TRUE, TRUE, FALSE, DEFAULT_PREC); load(KW_OUTLINE, OUTLINE, FALSE, TRUE, FALSE, DEFAULT_PREC); load(KW_LANGUAGE, LANGUAGE, TRUE, TRUE, FALSE, DEFAULT_PREC); load(KW_CURR_LANG, CURR_LANG, FALSE, FALSE, FALSE, DEFAULT_PREC); load(KW_CURR_FAMILY, CURR_FAMILY, FALSE, FALSE, FALSE, DEFAULT_PREC); load(KW_CURR_FACE, CURR_FACE, FALSE, FALSE, FALSE, DEFAULT_PREC); load(KW_CURR_YUNIT, CURR_YUNIT, FALSE, FALSE, FALSE, DEFAULT_PREC); load(KW_CURR_ZUNIT, CURR_ZUNIT, FALSE, FALSE, FALSE, DEFAULT_PREC); load(KW_COMMON, COMMON, TRUE, TRUE, FALSE, DEFAULT_PREC); load(KW_RUMP, RUMP, TRUE, TRUE, FALSE, DEFAULT_PREC); load(KW_MELD, MELD, TRUE, TRUE, FALSE, DEFAULT_PREC); load(KW_INSERT, INSERT, TRUE, TRUE, FALSE, DEFAULT_PREC); load(KW_ONE_OF, ONE_OF, FALSE, TRUE, FALSE, DEFAULT_PREC); load(KW_NEXT, NEXT, FALSE, TRUE, FALSE, DEFAULT_PREC); load(KW_PLUS, PLUS, TRUE, TRUE, FALSE, DEFAULT_PREC); load(KW_MINUS, MINUS, TRUE, TRUE, FALSE, DEFAULT_PREC); load(KW_OPEN, OPEN, TRUE, TRUE, FALSE, DEFAULT_PREC); load(KW_TAGGED, TAGGED, TRUE, TRUE, FALSE, DEFAULT_PREC); load(KW_WIDE, WIDE, TRUE, TRUE, FALSE, DEFAULT_PREC); load(KW_HIGH, HIGH, TRUE, TRUE, FALSE, DEFAULT_PREC); load(KW_HSHIFT, HSHIFT, TRUE, TRUE, FALSE, DEFAULT_PREC); load(KW_VSHIFT, VSHIFT, TRUE, TRUE, FALSE, DEFAULT_PREC); load(KW_BEGIN_HEADER, BEGIN_HEADER, TRUE, TRUE, FALSE, DEFAULT_PREC); load(KW_END_HEADER, END_HEADER, FALSE, FALSE, FALSE, DEFAULT_PREC); load(KW_SET_HEADER, SET_HEADER, TRUE, TRUE, FALSE, DEFAULT_PREC); load(KW_CLEAR_HEADER, CLEAR_HEADER, FALSE, FALSE, FALSE, DEFAULT_PREC); load(KW_ONE_COL, ONE_COL, FALSE, TRUE, FALSE, DEFAULT_PREC); load(KW_ONE_ROW, ONE_ROW, FALSE, TRUE, FALSE, DEFAULT_PREC); load(KW_HSCALE, HSCALE, FALSE, TRUE, FALSE, DEFAULT_PREC); load(KW_VSCALE, VSCALE, FALSE, TRUE, FALSE, DEFAULT_PREC); load(KW_HCOVER, HCOVER, FALSE, TRUE, FALSE, DEFAULT_PREC); load(KW_VCOVER, VCOVER, FALSE, TRUE, FALSE, DEFAULT_PREC); load(KW_KERN_SHRINK, KERN_SHRINK, TRUE, TRUE, FALSE, DEFAULT_PREC); load(KW_SCALE, SCALE, TRUE, TRUE, FALSE, DEFAULT_PREC); load(KW_HCONTRACT, HCONTRACT, FALSE, TRUE, FALSE, DEFAULT_PREC); load(KW_VCONTRACT, VCONTRACT, FALSE, TRUE, FALSE, DEFAULT_PREC); load(KW_HLIMITED, HLIMITED, FALSE, TRUE, FALSE, DEFAULT_PREC); load(KW_VLIMITED, VLIMITED, FALSE, TRUE, FALSE, DEFAULT_PREC); load(KW_HEXPAND, HEXPAND, FALSE, TRUE, FALSE, DEFAULT_PREC); load(KW_VEXPAND, VEXPAND, FALSE, TRUE, FALSE, DEFAULT_PREC); load(KW_STARTHVSPAN, START_HVSPAN, FALSE, TRUE, FALSE, DEFAULT_PREC); load(KW_STARTHSPAN, START_HSPAN, FALSE, TRUE, FALSE, DEFAULT_PREC); load(KW_STARTVSPAN, START_VSPAN, FALSE, TRUE, FALSE, DEFAULT_PREC); load(KW_HSPAN, HSPAN, FALSE, FALSE, FALSE, DEFAULT_PREC); load(KW_VSPAN, VSPAN, FALSE, FALSE, FALSE, DEFAULT_PREC); load(KW_PADJUST, PADJUST, FALSE, TRUE, FALSE, DEFAULT_PREC); load(KW_HADJUST, HADJUST, FALSE, TRUE, FALSE, DEFAULT_PREC); load(KW_VADJUST, VADJUST, FALSE, TRUE, FALSE, DEFAULT_PREC); load(KW_ROTATE, ROTATE, TRUE, TRUE, FALSE, DEFAULT_PREC); load(KW_BACKGROUND, BACKGROUND, TRUE, TRUE, FALSE, DEFAULT_PREC); load(KW_INCGRAPHIC, INCGRAPHIC, FALSE, TRUE, FALSE, DEFAULT_PREC); load(KW_SINCGRAPHIC, SINCGRAPHIC, FALSE, TRUE, FALSE, DEFAULT_PREC); load(KW_PLAINGRAPHIC, PLAIN_GRAPHIC, TRUE, TRUE, FALSE, DEFAULT_PREC); load(KW_GRAPHIC, GRAPHIC, TRUE, TRUE, FALSE, DEFAULT_PREC); load(KW_LINK_SOURCE, LINK_SOURCE, TRUE, TRUE, FALSE, DEFAULT_PREC); load(KW_LINK_DEST, LINK_DEST, TRUE, TRUE, FALSE, DEFAULT_PREC); load(KW_CROSS, CROSS, TRUE, TRUE, FALSE, CROSSOP_PREC); load(KW_FORCE_CROSS, FORCE_CROSS, TRUE, TRUE, FALSE, CROSSOP_PREC); load(KW_NULL, NULL_CLOS, FALSE, FALSE, TRUE, NO_PREC ); load(KW_PAGE_LABEL, PAGE_LABEL, FALSE, TRUE, TRUE, DEFAULT_PREC); #define setcat(s, mk, jn) has_mark(s)=mk, has_join(s)=jn s=load(KW_VCAT_NN, VCAT, TRUE, TRUE, FALSE, VCAT_PREC); setcat(s,FALSE,FALSE); s=load(KW_VCAT_MN, VCAT, TRUE, TRUE, FALSE, VCAT_PREC); setcat(s,TRUE, FALSE); s=load(KW_VCAT_NJ, VCAT, TRUE, TRUE, FALSE, VCAT_PREC); setcat(s,FALSE,TRUE); s=load(KW_VCAT_MJ, VCAT, TRUE, TRUE, FALSE, VCAT_PREC); setcat(s,TRUE, TRUE); s=load(KW_HCAT_NN, HCAT, TRUE, TRUE, FALSE, HCAT_PREC); setcat(s,FALSE,FALSE); s=load(KW_HCAT_MN, HCAT, TRUE, TRUE, FALSE, HCAT_PREC); setcat(s,TRUE, FALSE); s=load(KW_HCAT_NJ, HCAT, TRUE, TRUE, FALSE, HCAT_PREC); setcat(s,FALSE,TRUE); s=load(KW_HCAT_MJ, HCAT, TRUE, TRUE, FALSE, HCAT_PREC); setcat(s,TRUE, TRUE); s=load(KW_ACAT_NJ, ACAT, TRUE, TRUE, FALSE, ACAT_PREC); setcat(s,FALSE,TRUE); s=load(KW_ACAT_MJ, ACAT, TRUE, TRUE, FALSE, ACAT_PREC); setcat(s,TRUE, TRUE); /* intialize fonts and load @FontDef symbol */ FontInit(); /* intialize current time and load @Moment symbol */ InitTime(); /* initialize filter module */ FilterInit(); /* initialize enviroment table module */ EnvInit(); /* initialise scope chain to <StartSym> */ PushScope(StartSym, FALSE, FALSE); /* initialise lexical analyser */ LexPush(FirstFile(SOURCE_FILE), 0, SOURCE_FILE, 1, FALSE); /* process input files */ InitParser(cross_db); t = NewToken(BEGIN, no_fpos, 0, 0, BEGIN_PREC, StartSym); res = Parse(&t, StartSym, TRUE, TRUE); debug0(DGT, D, "calling TransferEnd(res) from main()"); DisposeObject(CommandOptions); TransferEnd(res); TransferClose(); /* close various modules */ BackEnd->PrintAfterLastPage(); BackEnd->LinkCheck(); CrossClose(); CloseFiles(); /* remove any leftover filter temporary files */ FilterScavenge(TRUE); /* print word count, if required */ if( seen_wordcount ) Error(1, 29, "total of all words printed: %d", WARN,no_fpos,TotalWordCount); /* check for unbalanced error blocks */ CheckErrorBlocks(); /* wrapup */ ifdebug(DST, DD, CheckSymSpread() ); ifdebug(ANY, D, DeleteEverySym() ); debug0(DMA, D, "at end of run:"); ifdebug(DMA, D, DebugMemory() ); ifdebug(DPP, D, ProfileOff("main")); ifdebug(DPP, D, ProfilePrint()); ifdebug(DET, D, EnvDebug()); #if LOCALE_ON catclose(MsgCat); #endif exit(0); return 0; } /* end main */
void CArgs_rgbm::SetCmdLine( int argc, char* argv[] ) { // start log flog = FileOpenOrDie( "RGBMerge.log", "w" ); // log start time time_t t0 = time( NULL ); char atime[32]; strcpy( atime, ctime( &t0 ) ); atime[24] = '\0'; // remove the newline fprintf( flog, "Start: %s ", atime ); // parse command line args if( argc < 4 ) { printf( "Usage: RGBMerge <xml-file> <tag>" " <-[R,G,B]=i,pct> [options].\n" ); exit( 42 ); } for( int i = 1; i < argc; ++i ) { vector<int> vi; // echo to log fprintf( flog, "%s ", argv[i] ); if( argv[i][0] != '-' ) { if( !infile ) infile = argv[i]; else tag = argv[i]; } else if( GetArg( &zmin, "-zmin=%d", argv[i] ) ) ; else if( GetArg( &zmax, "-zmax=%d", argv[i] ) ) ; else if( ScanChan( 0, "-R=%d", argv[i] ) ) ; else if( ScanChan( 1, "-G=%d", argv[i] ) ) ; else if( ScanChan( 2, "-B=%d", argv[i] ) ) ; else if( GetArgStr( span, "-spanRGB=", argv[i] ) ) ; else if( GetArgList( vi, "-lrbt=", argv[i] ) && vi.size() == 4 ) memcpy( &roi, &vi[0], 4*sizeof(int) ); else { printf( "Did not understand option '%s'.\n", argv[i] ); exit( 42 ); } } fprintf( flog, "\n\n" ); fflush( flog ); }
// // Entry-point for text-editor application // int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR lpCmdLine, int iShowCmd) { MSG msg; HACCEL hAccel; TCHAR **argv; int argc; //TCHAR *pszCmdlineFile = 0; TCHAR arg[MAX_PATH]; // // get the first commandline argument // TCHAR *pszCmdline = GetArg(GetCommandLineW(), arg, MAX_PATH); argv = GetArgvCommandLine(&argc); // check if we have any options if(pszCmdline && *pszCmdline == '-') { pszCmdline = GetArg(pszCmdline, arg, MAX_PATH); // do the user-account-control thing if(lstrcmpi(arg, _T("-uac")) == 0) { //return 0; } // image-file-execute-options else if(lstrcmpi(arg, _T("-ifeo")) == 0) { // skip notepad.exe pszCmdline = GetArg(pszCmdline, arg, MAX_PATH); } // unrecognised option else { } } // has a prior instance elevated us to admin in order to // modify some system-wide settings in the registry? if(argv && argc == 4 && lstrcmpi(argv[1], _T("-uac")) == 0) { g_fAddToExplorer = _ttoi(argv[2]); g_fReplaceNotepad = _ttoi(argv[3]); if(SetExplorerContextMenu(g_fAddToExplorer) && SetImageFileExecutionOptions(g_fReplaceNotepad)) { SaveRegSysSettings(); return 0; } else { return ERROR_ACCESS_DENIED; } } // default to the built-in resources g_hResourceModule = hInst; OleInitialize(0); // initialize window classes InitMainWnd(); InitTextView(); LoadRegSettings(); // create the main window! g_hwndMain = CreateMainWnd(); // open file specified on commmand line if(pszCmdline && *pszCmdline) { // check to see if it's a quoted filename if(*pszCmdline == '\"') { GetArg(pszCmdline, arg, MAX_PATH); pszCmdline = arg; } NeatpadOpenFile(g_hwndMain, pszCmdline); LoadFileData(pszCmdline, g_hwndMain); } // automatically create new document if none specified else { PostMessage(g_hwndMain, WM_COMMAND, IDM_FILE_NEW, 0); } ApplyRegSettings(); ShowWindow(g_hwndMain, iShowCmd); // // load keyboard accelerator table // hAccel = LoadAccelerators(g_hResourceModule, MAKEINTRESOURCE(IDR_ACCELERATOR1)); // // message-loop // while(GetMessage(&msg, NULL, 0, 0) > 0) { if(!TranslateAccelerator(g_hwndMain, hAccel, &msg)) { if((!IsWindow(g_hwndSearchDlg) || !IsDialogMessage(g_hwndSearchDlg, &msg))) { TranslateMessage(&msg); DispatchMessage(&msg); } } } if(g_fSaveOnExit) SaveRegSettings(); OleUninitialize(); ExitProcess(0); return 0; }
VOID MapFilters(PSPAWNINFO pChar, PCHAR szLine) { bRunNextCommand = TRUE; CHAR szArg[MAX_STRING] = { 0 }; GetArg(szArg, szLine, 1); PCHAR szRest = GetNextArg(szLine); CHAR szBuffer[MAX_STRING] = { 0 }; // Display settings if (szArg[0] == 0) { WriteChatColor("Map filtering settings:", USERCOLOR_DEFAULT); WriteChatColor("-----------------------", USERCOLOR_DEFAULT); for (DWORD i = 0; MapFilterOptions[i].szName != NULL; i++) if (RequirementsMet(i)) MapFilterSetting(pChar, i); // Display Help } else if (!_strnicmp(szArg, "help", 4)) { WriteChatColor("Map filtering options:", USERCOLOR_DEFAULT); for (DWORD i = 0; MapFilterOptions[i].szName != NULL; i++) { sprintf_s(szBuffer, "%s%s: %s", MapFilterOptions[i].szName, (MapFilterOptions[i].bIsToggle) ? "" : " #", MapFilterOptions[i].szHelpString); WriteChatColor(szBuffer, USERCOLOR_DEFAULT); } WriteChatColor("'option' color [r g b]: Set display color for 'option' (Omit to reset to default)", USERCOLOR_DEFAULT); // Set option } else { PMAPFILTER Found = 0; for (DWORD i = 0; MapFilterOptions[i].szName != NULL; i++) { if (!_stricmp(szArg, MapFilterOptions[i].szName)) { if (!_strnicmp(szRest, "color", 5)) { if (MapFilterOptions[i].DefaultColor == -1) { sprintf_s(szBuffer, "Option '%s' does not have a color.", MapFilterOptions[i].szName); WriteChatColor(szBuffer, USERCOLOR_DEFAULT); } else { DWORD R, G, B; CHAR szBuffer2[MAX_STRING] = { 0 }; GetArg(szArg, szRest, 2); if (szArg[0] == 0) { MapFilterOptions[i].Color = MapFilterOptions[i].DefaultColor; } else { R = atoi(szArg); G = atoi(GetArg(szArg, szRest, 3)); B = atoi(GetArg(szArg, szRest, 4)); if (R>255) R = 255; if (G>255) G = 255; if (B>255) B = 255; MapFilterOptions[i].Color = R * 0x10000 + G * 0x100 + B; } sprintf_s(szBuffer, "Option '%s' color set to: %d %d %d", MapFilterOptions[i].szName, R, G, B); WriteChatColor(szBuffer, USERCOLOR_DEFAULT); _itoa_s(MapFilterOptions[i].Color & 0xFFFFFF, szBuffer, 10); sprintf_s(szBuffer2, "%s-Color", MapFilterOptions[i].szName); WritePrivateProfileString("Map Filters", szBuffer2, szBuffer, INIFileName); MapFilterOptions[i].Color |= 0xFF000000; } } else { MapFilterSetting(pChar, i, szRest); } Found = &MapFilterOptions[i]; } } if (!Found) SyntaxError("Usage: /mapfilter [option|help]"); else if (Found->RegenerateOnChange) { MapClear(); MapGenerate(); } } }
BitcoinGUI::BitcoinGUI(const NetworkStyle *networkStyle, QWidget *parent) : QMainWindow(parent), clientModel(0), walletFrame(0), unitDisplayControl(0), labelEncryptionIcon(0), labelConnectionsIcon(0), labelBlocksIcon(0), progressBarLabel(0), progressBar(0), progressDialog(0), appMenuBar(0), overviewAction(0), historyAction(0), quitAction(0), sendCoinsAction(0), usedSendingAddressesAction(0), usedReceivingAddressesAction(0), signMessageAction(0), verifyMessageAction(0), aboutAction(0), receiveCoinsAction(0), optionsAction(0), toggleHideAction(0), encryptWalletAction(0), backupWalletAction(0), changePassphraseAction(0), aboutQtAction(0), openRPCConsoleAction(0), openAction(0), showHelpMessageAction(0), trayIcon(0), trayIconMenu(0), notificator(0), rpcConsole(0), prevBlocks(0), spinnerFrame(0) { /* Open CSS when configured */ this->setStyleSheet(GUIUtil::loadStyleSheet()); GUIUtil::restoreWindowGeometry("nWindow", QSize(850, 550), this); QString windowTitle = tr("X11BaseCoin Core") + " - "; #ifdef ENABLE_WALLET /* if compiled with wallet support, -disablewallet can still disable the wallet */ enableWallet = !GetBoolArg("-disablewallet", false); #else enableWallet = false; #endif // ENABLE_WALLET if(enableWallet) { windowTitle += tr("Wallet"); } else { windowTitle += tr("Node"); } QString userWindowTitle = QString::fromStdString(GetArg("-windowtitle", "")); if(!userWindowTitle.isEmpty()) windowTitle += " - " + userWindowTitle; windowTitle += " " + networkStyle->getTitleAddText(); #ifndef Q_OS_MAC QApplication::setWindowIcon(networkStyle->getAppIcon()); setWindowIcon(networkStyle->getAppIcon()); #else MacDockIconHandler::instance()->setIcon(networkStyle->getAppIcon()); #endif setWindowTitle(windowTitle); #if defined(Q_OS_MAC) && QT_VERSION < 0x050000 // This property is not implemented in Qt 5. Setting it has no effect. // A replacement API (QtMacUnifiedToolBar) is available in QtMacExtras. setUnifiedTitleAndToolBarOnMac(true); #endif rpcConsole = new RPCConsole(enableWallet ? this : 0); #ifdef ENABLE_WALLET if(enableWallet) { /** Create wallet frame*/ walletFrame = new WalletFrame(this); } else #endif // ENABLE_WALLET { /* When compiled without wallet or -disablewallet is provided, * the central widget is the rpc console. */ setCentralWidget(rpcConsole); } // Accept D&D of URIs setAcceptDrops(true); // Create actions for the toolbar, menu bar and tray/dock icon // Needs walletFrame to be initialized createActions(networkStyle); // Create application menu bar createMenuBar(); // Create the toolbars createToolBars(); // Create system tray icon and notification createTrayIcon(networkStyle); // Create status bar statusBar(); // Status bar notification icons QFrame *frameBlocks = new QFrame(); frameBlocks->setContentsMargins(0,0,0,0); frameBlocks->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred); QHBoxLayout *frameBlocksLayout = new QHBoxLayout(frameBlocks); frameBlocksLayout->setContentsMargins(3,0,3,0); frameBlocksLayout->setSpacing(3); unitDisplayControl = new UnitDisplayStatusBarControl(); labelEncryptionIcon = new QLabel(); labelConnectionsIcon = new QPushButton(); labelConnectionsIcon->setFlat(true); // Make the button look like a label, but clickable labelConnectionsIcon->setStyleSheet(".QPushButton { background-color: rgba(255, 255, 255, 0);}"); labelConnectionsIcon->setMaximumSize(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE); labelBlocksIcon = new QLabel(); if(enableWallet) { frameBlocksLayout->addStretch(); frameBlocksLayout->addWidget(unitDisplayControl); frameBlocksLayout->addStretch(); frameBlocksLayout->addWidget(labelEncryptionIcon); } frameBlocksLayout->addStretch(); frameBlocksLayout->addWidget(labelConnectionsIcon); frameBlocksLayout->addStretch(); frameBlocksLayout->addWidget(labelBlocksIcon); frameBlocksLayout->addStretch(); // Progress bar and label for blocks download progressBarLabel = new QLabel(); progressBarLabel->setVisible(true); progressBar = new GUIUtil::ProgressBar(); progressBar->setAlignment(Qt::AlignCenter); progressBar->setVisible(true); // Override style sheet for progress bar for styles that have a segmented progress bar, // as they make the text unreadable (workaround for issue #1071) // See https://qt-project.org/doc/qt-4.8/gallery.html QString curStyle = QApplication::style()->metaObject()->className(); if(curStyle == "QWindowsStyle" || curStyle == "QWindowsXPStyle") { progressBar->setStyleSheet("QProgressBar { background-color: #F8F8F8; border: 1px solid grey; border-radius: 7px; padding: 1px; text-align: center; } QProgressBar::chunk { background: QLinearGradient(x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 #00CCFF, stop: 1 #33CCFF); border-radius: 7px; margin: 0px; }"); } statusBar()->addWidget(progressBarLabel); statusBar()->addWidget(progressBar); statusBar()->addPermanentWidget(frameBlocks); // Jump directly to tabs in RPC-console connect(openInfoAction, SIGNAL(triggered()), rpcConsole, SLOT(showInfo())); connect(openRPCConsoleAction, SIGNAL(triggered()), rpcConsole, SLOT(showConsole())); connect(openNetworkAction, SIGNAL(triggered()), rpcConsole, SLOT(showNetwork())); connect(openPeersAction, SIGNAL(triggered()), rpcConsole, SLOT(showPeers())); connect(openRepairAction, SIGNAL(triggered()), rpcConsole, SLOT(showRepair())); connect(openConfEditorAction, SIGNAL(triggered()), rpcConsole, SLOT(showConfEditor())); connect(showBackupsAction, SIGNAL(triggered()), rpcConsole, SLOT(showBackups())); connect(labelConnectionsIcon, SIGNAL(clicked()), rpcConsole, SLOT(showPeers())); // Get restart command-line parameters and handle restart connect(rpcConsole, SIGNAL(handleRestart(QStringList)), this, SLOT(handleRestart(QStringList))); // prevents an open debug window from becoming stuck/unusable on client shutdown connect(quitAction, SIGNAL(triggered()), rpcConsole, SLOT(hide())); // Install event filter to be able to catch status tip events (QEvent::StatusTip) this->installEventFilter(this); // Initially wallet actions should be disabled setWalletActionsEnabled(false); // Subscribe to notifications from core subscribeToCoreSignals(); }
VOID Detour(PSPAWNINFO pChar, PCHAR szFullLine) { DebugSpew("CCommandHook::Detour(%s)",szFullLine); CHAR szFullCommand[MAX_STRING] = {0}; CHAR szCommand[MAX_STRING] = {0}; CHAR szArgs[MAX_STRING] = {0}; CHAR szOrig[MAX_STRING] = {0}; CHAR szSub[MAX_STRING] = {0}; string szSubFullCommand = ""; unsigned int k=0; bool OneCharacterSub = false; PALIAS pLoop = pAliases; PSUB pSubLoop = pSubs; if (szFullLine[0]!=0) { strcpy(szFullCommand,szFullLine); GetArg(szCommand,szFullCommand,1); if (!stricmp(szCommand,"/camp")) { if (gMacroBlock) { WriteChatColor("A macro is currently running. You may wish to /endmacro before you finish camping.", CONCOLOR_YELLOW ); } } szSubFullCommand = szFullCommand; for (unsigned int i=0; i < sizeof(szFullCommand); i++ ) { if (szFullCommand[i] == '%') { if (szFullCommand[i+2] == ' ' || szFullCommand[i+2] == '\0' || !isalnum(szFullCommand[i+2]) ) { if (szFullCommand[i+1] == 'm' || szFullCommand[i+1] == 'M' || szFullCommand[i+1] == 'o' || szFullCommand[i+1] == 'O' || szFullCommand[i+1] == 'p' || szFullCommand[i+1] == 'P' || szFullCommand[i+1] == 'r' || szFullCommand[i+1] == 'R' || szFullCommand[i+1] == 's' || szFullCommand[i+1] == 'S' || szFullCommand[i+1] == 't' || szFullCommand[i+1] == 'T' ) continue; else { szOrig[0] = szFullCommand[i+1]; szOrig[1] = '\0'; k = 1; OneCharacterSub = true; } } if (!OneCharacterSub) { for (unsigned int j=i+1; j < sizeof(szFullCommand); j++ ) { if (szFullCommand[j] == ' ' || szFullCommand[j] == '\0' ) break; else if (!isalnum(szFullCommand[j])) break; szOrig[k] = szFullCommand[j]; k++; } } while (pSubLoop) { if (!stricmp(szOrig, pSubLoop->szOrig)) { sprintf( szSub, "%s", pSubLoop->szSub ); break; } pSubLoop = pSubLoop->pNext; } if (szSub[0] != '\0' ) { szSubFullCommand.replace(i,k+1,szSub); sprintf( szFullCommand, "%s",szSubFullCommand.c_str() ); } szOrig[0] = '\0'; szSub[0] = '\0'; k=0; OneCharacterSub = false; pSubLoop = pSubs; } } sprintf(szFullCommand, "%s", szSubFullCommand.c_str() ); while (pLoop) { if (!stricmp(szCommand,pLoop->szName)) { sprintf(szCommand,"%s%s",pLoop->szCommand,szFullCommand+strlen(pLoop->szName)); strncpy(szFullCommand,szCommand,MAX_STRING); break; } pLoop = pLoop->pNext; } GetArg(szCommand,szFullCommand,1); strcpy(szArgs, GetNextArg(szFullCommand)); PMQCOMMAND pCommand=pCommands; while(pCommand) { if (pCommand->InGameOnly && gGameState!=GAMESTATE_INGAME) { pCommand=pCommand->pNext; continue; } int Pos=strnicmp(szCommand,pCommand->Command,strlen(szCommand)); if (Pos<0) {// command not found break; } if (Pos==0) { if (pCommand->Parse && bAllowCommandParse) ParseMacroParameter(pChar,szArgs); if (pCommand->EQ) { strcat(szCommand," "); strcat(szCommand,szArgs); Trampoline(pChar,szCommand); } else { pCommand->Function(pChar,szArgs); } strcpy(szLastCommand,szFullCommand); return; } pCommand=pCommand->pNext; } } Trampoline(pChar,szFullLine); strcpy(szLastCommand,szFullCommand); }
TStr TEnv::GetArgPostfix(const TStr& PrefixStr) const { int ArgN = GetPrefixArgN(PrefixStr); IAssert(ArgN != -1); TStr ArgStr = GetArg(ArgN); return ArgStr.GetSubStr(PrefixStr.Len(), ArgStr.Len()); }
void Application::OnInit() { nuiInit(NULL); uint Width = 0, Height = 0; bool HasSize = false; bool IsFullScreen = false; bool DebugObject = false; bool DebugInfo = false; bool ShowFPS = false; // nuiRenderer Renderer = eDirect3D; nuiRenderer Renderer = eOpenGL; // nuiRenderer Renderer = eSoftware; // Accept NGL default options ParseDefaultArgs(); GetLog().UseConsole(true); GetLog().SetLevel(_T("font"), 100); // Manual if ( (GetArgCount() == 1) && ((!GetArg(0).Compare(_T("-h"))) || (!GetArg(0).Compare(_T("--help")))) ) { NGL_OUT(_T("no params\n")); Quit (0); return; } // Parse args int i = 0; while (i < GetArgCount()) { nglString arg = GetArg(i); if ((!arg.Compare(_T("--size")) || !arg.Compare(_T("-s"))) && ((i+1) < GetArgCount())) { int w, h; std::string str(GetArg(i+1).GetStdString()); sscanf(str.c_str(), "%dx%d", &w, &h); if (w > 0) Width = w; if (h > 0) Height = h; HasSize = true; i++; } else if (!arg.Compare(_T("--showfps")) || !arg.Compare(_T("-fps"))) ShowFPS = true; else if (!arg.Compare(_T("--fullscreen")) || !arg.Compare(_T("-f"))) IsFullScreen = true; else if (!arg.Compare(_T("--debugobject")) || !arg.Compare(_T("-d"))) DebugObject = true; else if (!arg.Compare(_T("--debuginfo")) || !arg.Compare(_T("-i"))) DebugInfo = true; else if (!arg.Compare(_T("--renderer")) || !arg.Compare(_T("-r"))) { arg = GetArg(i+1); if (!arg.Compare(_T("opengl"))) Renderer = eOpenGL; else if (!arg.Compare(_T("direct3d"))) Renderer = eDirect3D; else if (!arg.Compare(_T("software"))) Renderer = eSoftware; i++; } i++; } nuiMainWindow::SetRenderer(Renderer); if (!HasSize) { if (IsFullScreen) { nglVideoMode current_mode; Width = current_mode.GetWidth(); Height = current_mode.GetHeight(); } else { Width = 320; Height = 480; } } /* Create the nglWindow (and thus a GL context, don't even try to * instantiate the gui (or nglFont) before the nuiWin !) */ nuiContextInfo ContextInfo(nuiContextInfo::StandardContext3D); nglWindowInfo Info; Info.Flags = IsFullScreen ? nglWindow::FullScreen : 0; Info.Width = Width; Info.Height = Height; Info.Pos = nglWindowInfo::ePosCenter; Info.Title = APPLICATION_TITLE; Info.XPos = 0; Info.YPos = 0; mpMainWindow = new MainWindow(ContextInfo,Info, ShowFPS); if ((!mpMainWindow) || (mpMainWindow->GetError())) { if (mpMainWindow) NGL_OUT(_T("Error: cannot create window (%s)\n"), mpMainWindow->GetErrorStr()); Quit (1); return; } mpMainWindow->Acquire(); mpMainWindow->DBG_SetMouseOverInfo(DebugInfo); mpMainWindow->DBG_SetMouseOverObject(DebugObject); mpMainWindow->SetState(nglWindow::eShow); }
// Set wkid, and set nwks which determines if MPI is used, // or not in the case that nwks == 1. // void MPIInit( int& argc, char**& argv ) { // Look for the -nwks=j argument for( int i = 1; i < argc; ++i ) { if( GetArg( &nwks, "-nwks=%d", argv[i] ) ) break; } // Get wkid int thrdtype = -1; if( nwks > 1 ) { // Start MPI MPI_Init_thread( &argc, &argv, MPI_THREAD_FUNNELED, &thrdtype ); MPI_Comm_rank( MPI_COMM_WORLD, &wkid ); } // Create log file 'lsqw_i' char slog[32]; sprintf( slog, "lsqw_%d.txt", wkid ); freopen( slog, "w", stdout ); printf( "---- Read params ----\n" ); // MPI sanity checks if( nwks > 1 ) { // Verify worker count int size; MPI_Comm_size( MPI_COMM_WORLD, &size ); if( size != nwks ) { printf( "MPI: Bad worker count: %d, expected %d\n.", size, nwks ); MPIExit(); exit( 42 ); } // Verify desired threading type. // Funneled means that the application can use // multiple threads but MPI communicates only // with the main thread. if( thrdtype != MPI_THREAD_FUNNELED ) { printf( "MPI: Not funneled thread type." " Try linking with -mt_mpi.\n" ); MPIExit(); exit( 42 ); } } printf( "Worker %d / %d\n", wkid, nwks ); }
//------------------------------------------------------------------------- INT_PTR CALLBACK ResetPermissionDialog::MainDialogProc( HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_INITDIALOG: { hDlg = hWnd; // Set the initial states/configuration bRecurse = true; bResetPerm = true; bRmHidSys = false; bTakeOwn = false; bDontFollowLinks = true; UpdateCheckboxes(false); HICON hIcon = LoadIcon( hInstance, MAKEINTRESOURCE(IDI_SMALL)); SendMessage( hDlg, WM_SETICON, ICON_BIG, (LPARAM)hIcon); LPCTSTR Arg = GetArg(1); #ifdef _DEBUG if (Arg == NULL) Arg = _TEXT("C:\\Temp\\perm"); // Enable editing for the folder text editbox in debug mode SendDlgItemMessage(hDlg, IDTXT_FOLDER, EM_SETREADONLY, FALSE, 0); #endif if (Arg != NULL) { SetFolderText(Arg); UpdateCommandText(); } return TRUE; } case WM_MENUCOMMAND: break; case WM_COMMAND: { UINT wmId = LOWORD(wParam); UINT wmEvent = HIWORD(wParam); #ifdef _DEBUG TCHAR b[1024]; _sntprintf_s( b, _countof(b), _TEXT("WM_COMMAND: wmParam=%08X lParam=%08X | ID=%04X Event=%04X\n"), wParam, lParam, wmId, wmEvent); OutputDebugString(b); // Reflect the folder text changes when the control is editable if (wmId == IDTXT_FOLDER && wmEvent == EN_CHANGE) UpdateCommandText(); #endif switch (wmId) { // // Handle checkboxes // case IDCHK_RECURSE: case IDCHK_DONTFOLLOWLINKS: case IDCHK_TAKEOWN: case IDCHK_RESETPERM: case IDCHK_RM_HS: { // Reforumulate the command text on each option change if (wmEvent == BN_CLICKED) { UpdateCommandText(); return TRUE; } break; } // // Handle context menu // case IDM_ADDTOEXPLORERFOLDERCONTEXTMENU: case IDM_REMOVEFROMEXPLORERFOLDERCONTEXTMENU: AddToExplorerContextMenu(wmId == IDM_ADDTOEXPLORERFOLDERCONTEXTMENU); break; case IDM_BACKUPPERMSCONTEXTMENU: case IDM_RESTOREPERMSCONTEXTMENU: BackRestorePermissions(wmId == IDM_BACKUPPERMSCONTEXTMENU); break; // // About box // case IDBTN_ABOUT: { DialogBox( hInstance, MAKEINTRESOURCE(IDD_ABOUTBOX), hDlg, AboutDlgProc); return TRUE; } // // Choose folder // case IDBTN_CHOOSE_FOLDER: { stringT Folder; if (BrowseFolder(hDlg, STR_SELECT_FOLDER, Folder)) { SetFolderText(Folder.c_str()); UpdateCommandText(); } return TRUE; } // // Trigger the "Advanced" menu // case IDBTN_ADVANCED: { ShowPopupMenu(IDR_ADVANCED_MENU, IDBTN_ADVANCED); return TRUE; } // // GO button // case IDOK: { // Validate the input folder and execute the command ExecuteWindowCommand(true); return TRUE; } // HELP button case IDBTN_HELP: { ShellExecute( hDlg, _TEXT("open"), STR_HELP_URL, nullptr, nullptr, SW_SHOW); return TRUE; } } // switch(wmId) break; } // case WM_COMMAND // Close dialog case WM_CLOSE: EndDialog(hDlg, IDOK); return TRUE; } return FALSE; }
// Writes all missing QSettings with their default values void OptionsModel::Init(bool resetSettings) { if (resetSettings) Reset(); QSettings settings; // Ensure restart flag is unset on client startup setRestartRequired(false); // These are Qt-only settings: // Window if (!settings.contains("fMinimizeToTray")) settings.setValue("fMinimizeToTray", false); fMinimizeToTray = settings.value("fMinimizeToTray").toBool(); if (!settings.contains("fMinimizeOnClose")) settings.setValue("fMinimizeOnClose", false); fMinimizeOnClose = settings.value("fMinimizeOnClose").toBool(); // Display if (!settings.contains("nDisplayUnit")) settings.setValue("nDisplayUnit", BitcoinUnits::BTC); nDisplayUnit = settings.value("nDisplayUnit").toInt(); if (!settings.contains("strThirdPartyTxUrls")) settings.setValue("strThirdPartyTxUrls", ""); strThirdPartyTxUrls = settings.value("strThirdPartyTxUrls", "").toString(); if (!settings.contains("fCoinControlFeatures")) settings.setValue("fCoinControlFeatures", false); fCoinControlFeatures = settings.value("fCoinControlFeatures", false).toBool(); // These are shared with the core or have a command-line parameter // and we want command-line parameters to overwrite the GUI settings. // // If setting doesn't exist create it with defaults. // // If SoftSetArg() or SoftSetBoolArg() return false we were overridden // by command-line and show this in the UI. // Main if (!settings.contains("nDatabaseCache")) settings.setValue("nDatabaseCache", (qint64)nDefaultDbCache); if (!SoftSetArg("-dbcache", settings.value("nDatabaseCache").toString().toStdString())) addOverriddenOption("-dbcache"); if (!settings.contains("nThreadsScriptVerif")) settings.setValue("nThreadsScriptVerif", DEFAULT_SCRIPTCHECK_THREADS); if (!SoftSetArg("-par", settings.value("nThreadsScriptVerif").toString().toStdString())) addOverriddenOption("-par"); if (!settings.contains("blockSizeAcceptLimitBytes")) settings.setValue("blockSizeAcceptLimitBytes", DEFAULT_BLOCK_ACCEPT_SIZE); if (mapArgs.count("-blocksizeacceptlimit")) addOverriddenOption("-blocksizeacceptlimit"); else if (mapArgs.count("-blocksizeacceptlimitbytes")) addOverriddenOption("-blocksizeacceptlimitbytes"); else if (mapArgs.count("-excessiveblocksize")) addOverriddenOption("-excessiveblocksize"); else { QVariant limit = settings.value("blockSizeAcceptLimitBytes"); if (Application::uahfChainState() != Application::UAHFDisabled) { bool ok; int value = settings.value("blockSizeAcceptLimitBytes").toInt(&ok); if (ok && value < 8000000) limit = QVariant(8000000); } SoftSetArg("-blocksizeacceptlimitbytes", limit.toString().toStdString()); } // Wallet #ifdef ENABLE_WALLET if (!settings.contains("bSpendZeroConfChange")) settings.setValue("bSpendZeroConfChange", true); if (!SoftSetBoolArg("-spendzeroconfchange", settings.value("bSpendZeroConfChange").toBool())) addOverriddenOption("-spendzeroconfchange"); #endif // Network if (!settings.contains("fUseUPnP")) settings.setValue("fUseUPnP", DEFAULT_UPNP); if (!SoftSetBoolArg("-upnp", settings.value("fUseUPnP").toBool())) addOverriddenOption("-upnp"); if (!settings.contains("fListen")) settings.setValue("fListen", DEFAULT_LISTEN); if (!SoftSetBoolArg("-listen", settings.value("fListen").toBool())) addOverriddenOption("-listen"); if (!settings.contains("fUseProxy")) settings.setValue("fUseProxy", false); if (!settings.contains("addrProxy")) settings.setValue("addrProxy", "127.0.0.1:9050"); // Only try to set -proxy, if user has enabled fUseProxy if (settings.value("fUseProxy").toBool() && !SoftSetArg("-proxy", settings.value("addrProxy").toString().toStdString())) addOverriddenOption("-proxy"); else if(!settings.value("fUseProxy").toBool() && !GetArg("-proxy", "").empty()) addOverriddenOption("-proxy"); if (!settings.contains("fUseSeparateProxyTor")) settings.setValue("fUseSeparateProxyTor", false); if (!settings.contains("addrSeparateProxyTor")) settings.setValue("addrSeparateProxyTor", "127.0.0.1:9050"); // Only try to set -onion, if user has enabled fUseSeparateProxyTor if (settings.value("fUseSeparateProxyTor").toBool() && !SoftSetArg("-onion", settings.value("addrSeparateProxyTor").toString().toStdString())) addOverriddenOption("-onion"); else if(!settings.value("fUseSeparateProxyTor").toBool() && !GetArg("-onion", "").empty()) addOverriddenOption("-onion"); // Display if (!settings.contains("language")) settings.setValue("language", ""); if (!SoftSetArg("-lang", settings.value("language").toString().toStdString())) addOverriddenOption("-lang"); language = settings.value("language").toString(); }
/** Update Capsule image. @param[in] ImageHandle The image handle. @param[in] SystemTable The system table. @retval EFI_SUCCESS Command completed successfully. @retval EFI_UNSUPPORTED Command usage unsupported. @retval EFI_INVALID_PARAMETER Command usage invalid. @retval EFI_NOT_FOUND The input file can't be found. **/ EFI_STATUS EFIAPI UefiMain ( IN EFI_HANDLE ImageHandle, IN EFI_SYSTEM_TABLE *SystemTable ) { EFI_STATUS Status; RETURN_STATUS RStatus; UINTN FileSize[MAX_CAPSULE_NUM]; VOID *CapsuleBuffer[MAX_CAPSULE_NUM]; EFI_CAPSULE_BLOCK_DESCRIPTOR *BlockDescriptors; EFI_CAPSULE_HEADER *CapsuleHeaderArray[MAX_CAPSULE_NUM + 1]; UINT64 MaxCapsuleSize; EFI_RESET_TYPE ResetType; BOOLEAN NeedReset; BOOLEAN NoReset; CHAR16 *CapsuleName; UINTN CapsuleNum; UINTN Index; EFI_GUID ImageTypeId; UINTN ImageIndex; Status = GetArg(); if (EFI_ERROR(Status)) { Print(L"Please use UEFI SHELL to run this application!\n", Status); return Status; } if (Argc < 2) { PrintUsage(); return EFI_UNSUPPORTED; } if (StrCmp(Argv[1], L"-D") == 0) { if (Argc != 3) { Print(L"CapsuleApp: Incorrect parameter count.\n"); return EFI_UNSUPPORTED; } Status = DumpCapsule(Argv[2]); return Status; } if (StrCmp(Argv[1], L"-G") == 0) { Status = CreateBmpFmp(); return Status; } if (StrCmp(Argv[1], L"-N") == 0) { Status = CreateNestedFmp(); return Status; } if (StrCmp(Argv[1], L"-S") == 0) { Status = DumpCapsuleStatusVariable(); return EFI_SUCCESS; } if (StrCmp(Argv[1], L"-C") == 0) { Status = ClearCapsuleStatusVariable(); return Status; } if (StrCmp(Argv[1], L"-P") == 0) { if (Argc == 2) { DumpFmpData(); } if (Argc >= 3) { if (StrCmp(Argv[2], L"GET") != 0) { Print(L"CapsuleApp: Unrecognized option(%s).\n", Argv[2]); return EFI_UNSUPPORTED; } else { if (Argc != 7) { Print(L"CapsuleApp: Incorrect parameter count.\n"); return EFI_UNSUPPORTED; } // // FMP->GetImage() // RStatus = StrToGuid (Argv[3], &ImageTypeId); if (RETURN_ERROR (RStatus) || (Argv[3][GUID_STRING_LENGTH] != L'\0')) { Print (L"Invalid ImageTypeId - %s\n", Argv[3]); return EFI_INVALID_PARAMETER; } ImageIndex = StrDecimalToUintn(Argv[4]); if (StrCmp(Argv[5], L"-O") != 0) { Print(L"CapsuleApp: NO output file name.\n"); return EFI_UNSUPPORTED; } DumpFmpImage(&ImageTypeId, ImageIndex, Argv[6]); } } return EFI_SUCCESS; } if (StrCmp(Argv[1], L"-E") == 0) { DumpEsrtData(); return EFI_SUCCESS; } if (Argv[1][0] == L'-') { Print(L"CapsuleApp: Unrecognized option(%s).\n", Argv[1]); return EFI_UNSUPPORTED; } CapsuleFirstIndex = 1; NoReset = FALSE; if ((Argc > 1) && (StrCmp(Argv[Argc - 1], L"-NR") == 0)) { NoReset = TRUE; CapsuleLastIndex = Argc - 2; } else { CapsuleLastIndex = Argc - 1; } CapsuleNum = CapsuleLastIndex - CapsuleFirstIndex + 1; if (CapsuleFirstIndex > CapsuleLastIndex) { Print(L"CapsuleApp: NO capsule image.\n"); return EFI_UNSUPPORTED; } if (CapsuleNum > MAX_CAPSULE_NUM) { Print(L"CapsuleApp: Too many capsule images.\n"); return EFI_UNSUPPORTED; } ZeroMem(&CapsuleBuffer, sizeof(CapsuleBuffer)); ZeroMem(&FileSize, sizeof(FileSize)); BlockDescriptors = NULL; for (Index = 0; Index < CapsuleNum; Index++) { CapsuleName = Argv[CapsuleFirstIndex + Index]; Status = ReadFileToBuffer(CapsuleName, &FileSize[Index], &CapsuleBuffer[Index]); if (EFI_ERROR(Status)) { Print(L"CapsuleApp: capsule image (%s) is not found.\n", CapsuleName); goto Done; } if (!IsValidCapsuleHeader (CapsuleBuffer[Index], FileSize[Index])) { Print(L"CapsuleApp: Capsule image (%s) is not a valid capsule.\n", CapsuleName); return EFI_INVALID_PARAMETER; } } // // Every capsule use 2 descriptor 1 for data 1 for end // Status = BuildGatherList(CapsuleBuffer, FileSize, CapsuleNum, &BlockDescriptors); if (EFI_ERROR(Status)) { goto Done; } // // Call the runtime service capsule. // NeedReset = FALSE; for (Index = 0; Index < CapsuleNum; Index++) { CapsuleHeaderArray[Index] = (EFI_CAPSULE_HEADER *) CapsuleBuffer[Index]; if ((CapsuleHeaderArray[Index]->Flags & CAPSULE_FLAGS_PERSIST_ACROSS_RESET) != 0) { NeedReset = TRUE; } } CapsuleHeaderArray[CapsuleNum] = NULL; // // Inquire platform capability of UpdateCapsule. // Status = gRT->QueryCapsuleCapabilities (CapsuleHeaderArray, CapsuleNum, &MaxCapsuleSize, &ResetType); if (EFI_ERROR(Status)) { Print (L"CapsuleApp: failed to query capsule capability - %r\n", Status); goto Done; } for (Index = 0; Index < CapsuleNum; Index++) { if (FileSize[Index] > MaxCapsuleSize) { Print (L"CapsuleApp: capsule is too large to update, %ld is allowed\n", MaxCapsuleSize); Status = EFI_UNSUPPORTED; goto Done; } } // // Check whether the input capsule image has the flag of persist across system reset. // if (NeedReset) { Status = gRT->UpdateCapsule(CapsuleHeaderArray,CapsuleNum,(UINTN) BlockDescriptors); if (Status != EFI_SUCCESS) { Print (L"CapsuleApp: failed to update capsule - %r\n", Status); goto Done; } // // For capsule with CAPSULE_FLAGS_PERSIST_ACROSS_RESET + CAPSULE_FLAGS_INITIATE_RESET, // a system reset should have been triggered by gRT->UpdateCapsule() calling above. // // For capsule with CAPSULE_FLAGS_PERSIST_ACROSS_RESET and without CAPSULE_FLAGS_INITIATE_RESET, // check if -NR (no-reset) has been specified or not. // if (!NoReset) { // // For capsule who has reset flag and no -NR (no-reset) has been specified, after calling UpdateCapsule service, // trigger a system reset to process capsule persist across a system reset. // gRT->ResetSystem (ResetType, EFI_SUCCESS, 0, NULL); } } else { // // For capsule who has no reset flag, only call UpdateCapsule Service without a // system reset. The service will process the capsule immediately. // Status = gRT->UpdateCapsule (CapsuleHeaderArray,CapsuleNum,(UINTN) BlockDescriptors); if (Status != EFI_SUCCESS) { Print (L"CapsuleApp: failed to update capsule - %r\n", Status); } } Status = EFI_SUCCESS; Done: for (Index = 0; Index < CapsuleNum; Index++) { if (CapsuleBuffer[Index] != NULL) { FreePool (CapsuleBuffer[Index]); } } CleanGatherList(BlockDescriptors, CapsuleNum); return Status; }
/* The following function (with dependant type declerations) originates from map2q.c */ static bool ReadMapFile( char *psFile, uint32 *ParCount_p, GDFS_MAPDATA **Head_pp, GDFS_MAPDATA **Tail_pp) { FILE *pFile; char psLineBuffer[MAX_LINE]; short wLine; bool rc, Error, fEndFound; short ArgCount, Decode, k; char *ArgVector[MAX_MAP_ARG + 1]; short State = WAITING_FOR_PARAMETER; GDFS_MAPDATA *New_p=NULL; uint32 Id = 0, Size = 0, WrPos = 0; char *Dummy_p = NULL; uint8 *Data_p = NULL; uint32 ParCount = 0; GDFS_MAPDATA *Head_p = NULL; GDFS_MAPDATA *Tail_p = NULL; pFile = fopen(psFile, "r"); if ( pFile == NULL ) { fprintf(stderr, "Could not open file %s\n", psFile); return(FALSE); } wLine = 1; Error = FALSE; fEndFound = FALSE; ParCount = 0; while ( fgets( psLineBuffer, sizeof( psLineBuffer), pFile) != NULL && !Error && !fEndFound ) { if ( psLineBuffer[0] != '/' ) /* Check that line not is a comment */ { GetArg( psLineBuffer, MAX_MAP_ARG, TRUE, &ArgCount, ArgVector); if ( ArgCount > 0 ) { switch( State) { case WAITING_FOR_PARAMETER: if ( ArgCount == 3 ) /* Typical first line for a parameter */ { Id = strtoul( ArgVector[0], &Dummy_p, 16); Size = strtoul( ArgVector[1], &Dummy_p, 10); /* This parameter is in decimal format. */ New_p = (GDFS_MAPDATA *)malloc( sizeof(GDFS_MAPDATA) + Size - sizeof( uint32)); New_p->Next_p = NULL; New_p->Id = Id; New_p->Size = Size; /* Configuration variables for parameter reading. */ Data_p = (uint8 *)&New_p->Data; WrPos = 0; State = READING_PARAMETER; ParCount++; /* Link into single linked list. */ if ( Head_p == NULL ) { Head_p = New_p; New_p->Prev_p = NULL; } else { Tail_p->Next_p = New_p; New_p->Prev_p = Tail_p; } Tail_p = New_p; } else { fprintf(stderr, "Erroneus data at line %d beginning %s... \n", wLine, ArgVector[0]); Error = TRUE; } break; case READING_PARAMETER: if ( Size - WrPos >= PARAMETERS_PER_ROW ) Decode = PARAMETERS_PER_ROW; else Decode = (short)(Size - WrPos); if ( Decode != ArgCount ) { fprintf(stderr, "Erroneus number of paramters at line %d. Found %d, expected %d\n", wLine, Decode, ArgCount); Error = TRUE; break; } /* Store data */ for ( k = 0 ; k < Decode ; k++ ) { Data_p[WrPos] = (uint8)strtoul( ArgVector[k], &Dummy_p, 16); WrPos++; } /* All data for the parameter is decoded */ if ( WrPos == Size ) State = WAITING_FOR_PARAMETER; break; } } } wLine++; } if ( fDebug ) { fprintf(stderr, "Found %d parameters in map file\n", ParCount); } fclose( pFile); *ParCount_p = ParCount; *Head_pp = Head_p; *Tail_pp = Tail_p; if ( !Error ) { rc = TRUE; } else { rc = FALSE; } return( rc); }