static void H(const AString &s, AString *out) { out->clear(); MD5_CTX m; MD5_Init(&m); MD5_Update(&m, s.c_str(), s.size()); uint8_t key[16]; MD5_Final(key, &m); for (size_t i = 0; i < 16; ++i) { char nibble = key[i] >> 4; if (nibble <= 9) { nibble += '0'; } else { nibble += 'a' - 10; } out->append(&nibble, 1); nibble = key[i] & 0x0f; if (nibble <= 9) { nibble += '0'; } else { nibble += 'a' - 10; } out->append(&nibble, 1); } }
bool cScoreboardSerializer::Save(void) { cFastNBTWriter Writer; SaveScoreboardToNBT(Writer); Writer.Finish(); #ifdef _DEBUG cParsedNBT TestParse(Writer.GetResult().data(), Writer.GetResult().size()); ASSERT(TestParse.IsValid()); #endif // _DEBUG cFile File; if (!File.Open(FILE_IO_PREFIX + m_Path, cFile::fmWrite)) { return false; } AString Compressed; int res = CompressStringGZIP(Writer.GetResult().data(), Writer.GetResult().size(), Compressed); if (res != Z_OK) { return false; } File.Write(Compressed.data(), Compressed.size()); File.Close(); return true; }
Bool HawkProfiler::Start(const AString& sAddr) { if (!m_bRunning) { if (sAddr.size()) m_sAddr = sAddr; GetProcessorNumber(); GetTotalMem(); GetCpuUsage(); GetMemUsage(); if(!m_sSocket.Create(AF_INET,SOCK_DGRAM,IPPROTO_UDP)) { HawkPrint("Profiler Init Socket Error."); return false; } m_sSocket.SetNoDelay(true); m_sSocket.SetBlocking(false); if(!m_sSocket.Bind(SocketAddr(m_sAddr))) { HawkPrint("Profiler Bind Socket Error."); return false; } m_bRunning = true; m_pThread = new HawkThread(hawk_ProfilerRoutine); m_pThread->Start(this); return true; } return false; }
Bool HsGateway::TrustSession(void* pSession, OctetsStream* pIBuffer) { if (pSession && pIBuffer) { //QQ平台网关校验信息过滤 if (m_iPlatform == 1) { if (pIBuffer->AvailableSize() >= TGW_BUFFER_SIZE) { AString sTgw = (Char*)pIBuffer->AvailableData(); #ifdef _DEBUG HawkFmtPrint("TGW: %s", sTgw.c_str()); #endif Bool bStart = HawkStringUtil::BeginWith<AString>(sTgw, "tgw_l7_forward"); Bool bEnd = HawkStringUtil::EndWith<AString>(sTgw, "\r\n\r\n"); if (bStart && bEnd) { UInt32 iCrc = HawkOSOperator::CalcCrc((const UChar*)sTgw.c_str(),(UInt32)sTgw.size()); UInt32* pCrc = (UInt32*)((Char*)pIBuffer->AvailableData() + (TGW_BUFFER_SIZE - sizeof(UInt32))); if (pCrc && iCrc == *pCrc) { pIBuffer->MoveNonius(TGW_BUFFER_SIZE); return true; } } } return false; } } return true; }
bool cSchematicFileSerializer::LoadFromSchematicFile(cBlockArea & a_BlockArea, const AString & a_FileName) { // Un-GZip the contents: AString Contents; cGZipFile File; if (!File.Open(a_FileName, cGZipFile::fmRead)) { LOG("Cannot open the schematic file \"%s\".", a_FileName.c_str()); return false; } int NumBytesRead = File.ReadRestOfFile(Contents); if (NumBytesRead < 0) { LOG("Cannot read GZipped data in the schematic file \"%s\", error %d", a_FileName.c_str(), NumBytesRead); return false; } File.Close(); // Parse the NBT: cParsedNBT NBT(Contents.data(), Contents.size()); if (!NBT.IsValid()) { LOG("Cannot parse the NBT in the schematic file \"%s\".", a_FileName.c_str()); return false; } return LoadFromSchematicNBT(a_BlockArea, NBT); }
status_t WifiDisplaySource::sendM16(int32_t sessionID) { AString request = "GET_PARAMETER rtsp://localhost/wfd1.0 RTSP/1.0\r\n"; AppendCommonResponse(&request, mNextCSeq); CHECK_EQ(sessionID, mClientSessionID); request.append( StringPrintf("Session: %d\r\n", mClientInfo.mPlaybackSessionID)); request.append("\r\n"); // Empty body status_t err = mNetSession->sendRequest(sessionID, request.c_str(), request.size()); if (err != OK) { return err; } registerResponseHandler( sessionID, mNextCSeq, &WifiDisplaySource::onReceiveM16Response); ++mNextCSeq; scheduleKeepAlive(sessionID); return OK; }
void cProtocolRecognizer::DataReceived(const char * a_Data, int a_Size) { if (m_Protocol == NULL) { if (!m_Buffer.Write(a_Data, a_Size)) { m_Client->Kick("Unsupported protocol version"); return; } if (!TryRecognizeProtocol()) { return; } // The protocol has just been recognized, dump the whole m_Buffer contents into it for parsing: AString Dump; m_Buffer.ResetRead(); m_Buffer.ReadAll(Dump); m_Protocol->DataReceived(Dump.data(), Dump.size()); } else { m_Protocol->DataReceived(a_Data, a_Size); } }
bool cPrefabPiecePool::LoadFromString(const AString & a_Contents, const AString & a_FileName, bool a_LogWarnings) { // If the contents start with GZip signature, ungzip and retry: if (a_Contents.substr(0, 3) == "\x1f\x8b\x08") { AString Uncompressed; auto res = UncompressStringGZIP(a_Contents.data(), a_Contents.size(), Uncompressed); if (res == Z_OK) { return LoadFromString(Uncompressed, a_FileName, a_LogWarnings); } else { CONDWARNING(a_LogWarnings, "Failed to decompress Gzip data in file %s: %d", a_FileName.c_str(), res); return false; } } // Search the first 8 KiB of the file for the format auto-detection string: auto Header = a_Contents.substr(0, 8192); if (Header.find("CubesetFormatVersion =") != AString::npos) { return LoadFromCubeset(a_Contents, a_FileName, a_LogWarnings); } CONDWARNING(a_LogWarnings, "Cannot load prefabs from file %s, unknown file format", a_FileName.c_str()); return false; }
void cLuaState::Push(const AString & a_String) { ASSERT(IsValid()); lua_pushlstring(m_LuaState, a_String.data(), a_String.size()); m_NumCurrentFunctionArgs += 1; }
bool cHTTPServer::Initialize(const AString & a_PortsIPv4, const AString & a_PortsIPv6) { // Read the HTTPS cert + key: AString CertFile = cFile::ReadWholeFile("webadmin/httpscert.crt"); AString KeyFile = cFile::ReadWholeFile("webadmin/httpskey.pem"); if (!CertFile.empty() && !KeyFile.empty()) { m_Cert.reset(new cX509Cert); int res = m_Cert->Parse(CertFile.data(), CertFile.size()); if (res == 0) { m_CertPrivKey.reset(new cCryptoKey); int res2 = m_CertPrivKey->ParsePrivate(KeyFile.data(), KeyFile.size(), ""); if (res2 != 0) { // Reading the private key failed, reset the cert: LOGWARNING("WebServer: Cannot read HTTPS certificate private key: -0x%x", -res2); m_Cert.reset(); } } else { LOGWARNING("WebServer: Cannot read HTTPS certificate: -0x%x", -res); } } // Notify the admin about the HTTPS / HTTP status if (m_Cert.get() == NULL) { LOGWARNING("WebServer: The server is running in unsecure HTTP mode."); } else { LOGINFO("WebServer: The server is running in secure HTTPS mode."); } // Open up requested ports: bool HasAnyPort; HasAnyPort = m_ListenThreadIPv4.Initialize(a_PortsIPv4); HasAnyPort = m_ListenThreadIPv6.Initialize(a_PortsIPv6) || HasAnyPort; if (!HasAnyPort) { return false; } return true; }
AString cLuaTCPLink::StartTLSServer( const AString & a_OwnCertData, const AString & a_OwnPrivKeyData, const AString & a_OwnPrivKeyPassword, const AString & a_StartTLSData ) { // Check preconditions: if (m_SslContext != nullptr) { return "TLS is already active on this link"; } if (a_OwnCertData.empty() || a_OwnPrivKeyData.empty()) { return "Provide the server certificate and private key"; } // Create the SSL context: m_SslContext.reset(new cLinkSslContext(*this)); m_SslContext->Initialize(false); // Create the peer cert: auto OwnCert = std::make_shared<cX509Cert>(); int res = OwnCert->Parse(a_OwnCertData.data(), a_OwnCertData.size()); if (res != 0) { m_SslContext.reset(); return Printf("Cannot parse server certificate: -0x%x", res); } auto OwnPrivKey = std::make_shared<cCryptoKey>(); res = OwnPrivKey->ParsePrivate(a_OwnPrivKeyData.data(), a_OwnPrivKeyData.size(), a_OwnPrivKeyPassword); if (res != 0) { m_SslContext.reset(); return Printf("Cannot parse server private key: -0x%x", res); } m_SslContext->SetOwnCert(OwnCert, OwnPrivKey); m_SslContext->SetSelf(cLinkSslContextWPtr(m_SslContext)); // Push the initial data: m_SslContext->StoreReceivedData(a_StartTLSData.data(), a_StartTLSData.size()); // Start the handshake: m_SslContext->Handshake(); return ""; }
cFastNBTWriter::cFastNBTWriter(const AString & a_RootTagName) : m_CurrentStack(0) { m_Stack[0].m_Type = TAG_Compound; m_Result.reserve(100 * 1024); m_Result.push_back(TAG_Compound); WriteString(a_RootTagName.data(), a_RootTagName.size()); }
status_t WifiDisplaySource::sendTrigger( int32_t sessionID, TriggerType triggerType) { AString body = "wfd_trigger_method: "; switch (triggerType) { case TRIGGER_SETUP: body.append("SETUP"); break; case TRIGGER_TEARDOWN: ALOGI("Sending TEARDOWN trigger."); body.append("TEARDOWN"); break; case TRIGGER_PAUSE: body.append("PAUSE"); break; case TRIGGER_PLAY: body.append("PLAY"); break; default: TRESPASS(); } body.append("\r\n"); AString request = "SET_PARAMETER rtsp://localhost/wfd1.0 RTSP/1.0\r\n"; AppendCommonResponse(&request, mNextCSeq); request.append("Content-Type: text/parameters\r\n"); request.append(AStringPrintf("Content-Length: %d\r\n", body.size())); request.append("\r\n"); request.append(body); status_t err = mNetSession->sendRequest(sessionID, request.c_str(), request.size()); if (err != OK) { return err; } registerResponseHandler( sessionID, mNextCSeq, &WifiDisplaySource::onReceiveM5Response); ++mNextCSeq; return OK; }
bool splitString(const AString &s, const AString &delimiter, AString *s1, AString *s2) { ssize_t pos = s.find(delimiter.c_str()); if (pos < 0) { return false; } *s1 = AString(s, 0, pos); *s2 = AString(s, pos + 1, s.size() - pos - 1); return true; }
void cProtocol125::SendEntityMetadata(const cEntity & a_Entity) { cCSLock Lock(m_CSPacket); WriteByte(PACKET_METADATA); WriteInt (a_Entity.GetUniqueID()); AString MetaData = GetEntityMetaData(a_Entity); SendData(MetaData.data(), MetaData.size()); Flush(); }
void cProtocol132::HandleEncryptionKeyResponse(const AString & a_EncKey, const AString & a_EncNonce) { // Decrypt EncNonce using privkey RSAES<PKCS1v15>::Decryptor rsaDecryptor(cRoot::Get()->GetServer()->GetPrivateKey()); time_t CurTime = time(NULL); CryptoPP::RandomPool rng; rng.Put((const byte *)&CurTime, sizeof(CurTime)); byte DecryptedNonce[MAX_ENC_LEN]; DecodingResult res = rsaDecryptor.Decrypt(rng, (const byte *)a_EncNonce.data(), a_EncNonce.size(), DecryptedNonce); if (!res.isValidCoding || (res.messageLength != 4)) { LOGD("Bad nonce length"); m_Client->Kick("Hacked client"); return; } if (ntohl(*((int *)DecryptedNonce)) != (unsigned)(uintptr_t)this) { LOGD("Bad nonce value"); m_Client->Kick("Hacked client"); return; } // Decrypt the symmetric encryption key using privkey: byte DecryptedKey[MAX_ENC_LEN]; res = rsaDecryptor.Decrypt(rng, (const byte *)a_EncKey.data(), a_EncKey.size(), DecryptedKey); if (!res.isValidCoding || (res.messageLength != 16)) { LOGD("Bad key length"); m_Client->Kick("Hacked client"); return; } { // Send encryption key response: cCSLock Lock(m_CSPacket); WriteByte((char)0xfc); WriteShort(0); WriteShort(0); Flush(); } StartEncryption(DecryptedKey); return; }
// static status_t M3UParser::parseByteRange( const AString &line, uint64_t curOffset, uint64_t *length, uint64_t *offset) { ssize_t colonPos = line.find(":"); if (colonPos < 0) { return ERROR_MALFORMED; } ssize_t atPos = line.find("@", colonPos + 1); AString lenStr; if (atPos < 0) { lenStr = AString(line, colonPos + 1, line.size() - colonPos - 1); } else { lenStr = AString(line, colonPos + 1, atPos - colonPos - 1); } lenStr.trim(); const char *s = lenStr.c_str(); char *end; *length = strtoull(s, &end, 10); if (s == end || *end != '\0') { return ERROR_MALFORMED; } if (atPos >= 0) { AString offStr = AString(line, atPos + 1, line.size() - atPos - 1); offStr.trim(); const char *s = offStr.c_str(); *offset = strtoull(s, &end, 10); if (s == end || *end != '\0') { return ERROR_MALFORMED; } } else { *offset = curOffset; } return OK; }
Air::U1 Converter::SplitFilePath( const AString& str, AString* strPath /*= NULL*/, AString* strFileName /*= NULL*/, AString* strExe /*= NULL*/ ) { if(str.empty()) return false; U32 uiStrSize = str.size(); S32 uiPoint = uiStrSize; S32 uiSlash = -1; for(S32 i=uiStrSize-1;i>-1;i--){ if(str[i] == '.' && uiPoint == uiStrSize){ uiPoint = i; } if( str[i] == '/' || str[i] == '\\'){ uiSlash = i; break; } } if( uiPoint != uiStrSize && strExe != NULL) { if(uiPoint!=uiStrSize-1) *strExe = &str[uiPoint+1]; } if( uiSlash != -1 && strPath != NULL) { if(uiSlash<uiStrSize){ strPath->resize(uiSlash+1); memcpy(&((*strPath)[0]),&str[0],uiSlash+1); }else{ *strPath = str; } } if(strFileName!=NULL){ U32 uiFileNameSize = uiPoint; U32 uiFileNameStart = 0; if(uiPoint==uiStrSize) uiFileNameSize--; if(uiSlash<uiStrSize){ if(uiSlash!=-1){ uiFileNameSize -= uiSlash+1; uiFileNameStart = uiSlash+1; } strFileName->resize(uiFileNameSize); memcpy(&((*strFileName)[0]),&str[uiFileNameStart],uiFileNameSize); } } return true; }
cPublicKey::cPublicKey(const AString & a_PublicKeyDER) { pk_init(&m_Pk); if (pk_parse_public_key(&m_Pk, (const Byte *)a_PublicKeyDER.data(), a_PublicKeyDER.size()) != 0) { ASSERT(!"Cannot parse PubKey"); return; } InitRnd(); }
//liluchangyou void ARTSPConnection::onSendResponse(const sp<AMessage> &msg) { AString response; sp<AMessage> notify; CHECK(msg->findString("response", &response)); // Find the boundary between headers and the body. ssize_t i = response.find("\r\n\r\n"); CHECK_GE(i, 0); LOGI(LOG_TAG,"response:\n%s", response.c_str()); size_t numBytesSent = 0; while (numBytesSent < response.size()) { ssize_t n = send(mSocket, response.c_str() + numBytesSent, response.size() - numBytesSent, 0); if (n == 0) { // Client closed the connection. LOGE(LOG_TAG,"Client unexpectedly closed the connection."); mState = DISCONNECTED; notify = new AMessage(kwhatCloseSession,mhandlerID); notify->setInt32("result",-1); notify->setInt32("sessionID",mSessionID); notify->post(); return; } else if (n < 0) { if (errno == EINTR) { continue; } mState = DISCONNECTED; LOGE(LOG_TAG,"Error sending rtsp response."); notify = new AMessage(kwhatCloseSession,mhandlerID); notify->setInt32("result",errno ); notify->setInt32("sessionID",mSessionID); notify->post(); return; } numBytesSent += (size_t)n; } }
// static void HTTPStream::RegisterSocketUser(int s, uid_t uid) { // Lower bits MUST be 0. static const uint64_t kTag = 0xdeadbeef00000000ll; AString line = StringPrintf("t %d %llu %d", s, kTag, uid); int fd = open("/proc/net/xt_qtaguid/ctrl", O_WRONLY); write(fd, line.c_str(), line.size()); close(fd); fd = -1; }
bool cSchematicFileSerializer::LoadFromSchematicString(cBlockArea & a_BlockArea, const AString & a_SchematicData) { // Uncompress the data: AString UngzippedData; if (UncompressStringGZIP(a_SchematicData.data(), a_SchematicData.size(), UngzippedData) != Z_OK) { LOG("%s: Cannot unGZip the schematic data.", __FUNCTION__); return false; } // Parse the NBT: cParsedNBT NBT(UngzippedData.data(), UngzippedData.size()); if (!NBT.IsValid()) { LOG("%s: Cannot parse the NBT in the schematic data.", __FUNCTION__); return false; } return LoadFromSchematicNBT(a_BlockArea, NBT); }
AString HawkOSOperator::SplitFileName(const AString& sFile) { AString sTmpFile = sFile; HawkStringUtil::Replace<AString>(sTmpFile,"\\","/"); Int32 iPos = (Int32)sTmpFile.find_last_of('/'); if (iPos > 0) { return sTmpFile.substr(iPos+1,sTmpFile.size()-iPos-1); } return sTmpFile; }
std::vector<AString> split(const std::string& str, const char& chr) { std::vector<AString> result; AString current = AString(""); for(unsigned int i = 0; i < str.size(); i++) { char c = str[i]; if (c == chr){ if (current.size() > 0) { result.push_back(current); current = AString(""); } } else current += c; } if (current.size() > 0) { result.push_back(current); current = AString(""); } return result; }
cCryptoKey::cCryptoKey(const AString & a_PublicKeyData) { pk_init(&m_Pk); m_CtrDrbg.Initialize("rsa_pubkey", 10); int res = ParsePublic(a_PublicKeyData.data(), a_PublicKeyData.size()); if (res != 0) { LOGWARNING("Failed to parse public key: -0x%x", res); ASSERT(!"Cannot parse PubKey"); return; } }
void cProtocolRecognizer::DataReceived(const char * a_Data, size_t a_Size) { if (m_Protocol == nullptr) { if (!m_Buffer.Write(a_Data, a_Size)) { m_Client->Kick("Unsupported protocol version"); return; } if (m_InPingForUnrecognizedVersion) { // We already know the verison; handle it here. UInt32 PacketLen; UInt32 PacketID; if (!m_Buffer.ReadVarInt32(PacketLen)) { return; } if (!m_Buffer.ReadVarInt32(PacketID)) { return; } ASSERT(PacketID == 0x01); // Ping packet ASSERT(PacketLen == 9); // Payload of the packet ID and a UInt64 Int64 Data; if (!m_Buffer.ReadBEInt64(Data)) { return; } cPacketizer Pkt(*this, 0x01); // Pong packet Pkt.WriteBEInt64(Data); return; } if (!TryRecognizeProtocol()) { return; } // The protocol has just been recognized, dump the whole m_Buffer contents into it for parsing: AString Dump; m_Buffer.ResetRead(); m_Buffer.ReadAll(Dump); m_Protocol->DataReceived(Dump.data(), Dump.size()); } else { m_Protocol->DataReceived(a_Data, a_Size); } }
cCryptoKey::cCryptoKey(const AString & a_PrivateKeyData, const AString & a_Password) { pk_init(&m_Pk); m_CtrDrbg.Initialize("rsa_privkey", 11); int res = ParsePrivate(a_PrivateKeyData.data(), a_PrivateKeyData.size(), a_Password); if (res != 0) { LOGWARNING("Failed to parse private key: -0x%x", res); ASSERT(!"Cannot parse PubKey"); return; } }
bool cByteBuffer::WriteBEUTF16String16(const AString & a_Value) { CHECK_THREAD; CheckValid(); PUTBYTES(2); AString UTF16BE; UTF8ToRawBEUTF16(a_Value.data(), a_Value.size(), UTF16BE); WriteBEShort((short)(UTF16BE.size() / 2)); PUTBYTES(UTF16BE.size()); WriteBuf(UTF16BE.data(), UTF16BE.size()); return true; }
void exportResultsToXML( const char *fileName, const CodecSettings &global_results, const KeyedVector<AString, CodecSettings> &encoder_results, const KeyedVector<AString, CodecSettings> &decoder_results) { if (global_results.size() == 0 && encoder_results.size() == 0 && decoder_results.size() == 0) { return; } AString overrides; overrides.append(getProfilingVersionString()); overrides.append("\n"); overrides.append("<MediaCodecs>\n"); if (global_results.size() > 0) { overrides.append(" <Settings>\n"); overrides.append(globalResultsToXml(global_results)); overrides.append(" </Settings>\n"); } if (encoder_results.size() > 0) { overrides.append(" <Encoders>\n"); overrides.append(codecResultsToXml(encoder_results)); overrides.append(" </Encoders>\n"); } if (decoder_results.size() > 0) { overrides.append(" <Decoders>\n"); overrides.append(codecResultsToXml(decoder_results)); overrides.append(" </Decoders>\n"); } overrides.append("</MediaCodecs>\n"); FILE *f = fopen(fileName, "wb"); if (f == NULL) { ALOGE("Failed to open %s for writing.", fileName); return; } if (fwrite(overrides.c_str(), 1, overrides.size(), f) != overrides.size()) { ALOGE("Failed to write to %s.", fileName); } fclose(f); }
void cHTTPFormParser::OnPartHeader(const AString & a_Key, const AString & a_Value) { if (NoCaseCompare(a_Key, "Content-Disposition") == 0) { size_t len = a_Value.size(); size_t ParamsStart = AString::npos; for (size_t i = 0; i < len; ++i) { if (a_Value[i] > ' ') { if (strncmp(a_Value.c_str() + i, "form-data", 9) != 0) { // Content disposition is not "form-data", mark the whole form invalid m_IsValid = false; return; } ParamsStart = a_Value.find(';', i + 9); break; } } if (ParamsStart == AString::npos) { // There is data missing in the Content-Disposition field, mark the whole form invalid: m_IsValid = false; return; } // Parse the field name and optional filename from this header: cNameValueParser Parser(a_Value.data() + ParamsStart, a_Value.size() - ParamsStart); Parser.Finish(); m_CurrentPartName = Parser["name"]; if (!Parser.IsValid() || m_CurrentPartName.empty()) { // The required parameter "name" is missing, mark the whole form invalid: m_IsValid = false; return; } m_CurrentPartFileName = Parser["filename"]; } }