void XSDParser::ParseInclude(void) { TToken tok; string name; for ( tok = GetNextToken(); tok == K_ATTPAIR || tok == K_XMLNS; tok = GetNextToken()) { if (IsAttribute("schemaLocation")) { name = m_Value; } } if (tok != K_ENDOFTAG) { ParseError("endoftag"); } if (name.empty()) { ParseError("schemaLocation"); } DTDEntity& node = m_MapEntity[CreateEntityId(name, DTDEntity::eEntity)]; if (node.GetName().empty()) { node.SetName(name); node.SetData(name); node.SetExternal(); PushEntityLexer(name); Reset(); ParseHeader(); } }
BOOL CVCAMetaParserIXML::ParseMetaData( unsigned char *pMetadata, int nLength ) { pMetadata[nLength] = '\0'; m_pDOMDoc = ixmlParseBuffer((char*)pMetadata); // puts(ixmlPrintDocument(m_pDOMDoc)); if(m_pDOMDoc) { ParseHeader(); ParseStab(); ParseObjects(); ParseEvents(); ParseCounts(); ParseBlobsImp(_XML_TAMPERMAP, &m_TamperInfo); ParseBlobsImp(_XML_SCENECHANGEMAP, &m_SceneChangeInfo); ParseBlobsImp(_XML_BLOBMAP, &m_BlobMap); ParseBlobsImp(_XML_STATBLOBMAP, &m_StationaryMap); ParseBlobsImp(_XML_SMOKEMAP,&m_SmokeMap); ParseBlobsImp(_XML_FIREMAP,&m_FireMap); ParseCE(); ixmlDocument_free(m_pDOMDoc); } else { printf("!!! Parsing Error\n"); } return TRUE; }
void Node::Parse(Scanner *pScanner, const ParserState& state) { Clear(); // an empty node *is* a possibility if(pScanner->empty()) return; // save location m_mark = pScanner->peek().mark; ParseHeader(pScanner, state); // is this an alias? if so, its contents are an alias to // a previously defined anchor if(m_alias) { // the scanner throws an exception if it doesn't know this anchor name const Node *pReferencedNode = pScanner->Retrieve(m_anchor); m_pIdentity = pReferencedNode; // mark the referenced node for the sake of the client code pReferencedNode->m_referenced = true; // use of an Alias object keeps the referenced content from // being deleted twice Content *pAliasedContent = pReferencedNode->m_pContent; if(pAliasedContent) m_pContent = new AliasContent(pAliasedContent); return; } // now split based on what kind of node we should be switch(pScanner->peek().type) { case Token::SCALAR: m_pContent = new Scalar; break; case Token::FLOW_SEQ_START: case Token::BLOCK_SEQ_START: m_pContent = new Sequence; break; case Token::FLOW_MAP_START: case Token::BLOCK_MAP_START: m_pContent = new Map; break; default: // std::stringstream str; // str << TokenNames[pScanner->peek().type]; // throw std::runtime_error(str.str()); break; } // Have to save anchor before parsing to allow for aliases as // contained node (recursive structure) if(!m_anchor.empty()) pScanner->Save(m_anchor, this); if(m_pContent) m_pContent->Parse(pScanner, state); }
operator MusicSequence() { if( utils::LibWide().isLogOn() ) clog << "=== Parsing SMDL ===\n"; //Set our iterator m_itread = m_itbeg;//m_src.begin(); //#FIXME: It might have been easier to just check for trk chunks and stop when none are left? We'd save a lot of iteration!! m_itEoC = DSE::FindNextChunk( m_itbeg, m_itend, DSE::eDSEChunks::eoc ); //Our end is either the eoc chunk, or the vector's end //Get the headers ParseHeader(); ParseSong(); DSE::DSE_MetaDataSMDL meta( MakeMeta() ); //Check version if( m_hdr.version == static_cast<uint16_t>(eDSEVersion::V415) ) { //Parse tracks and return return std::move( MusicSequence( ParseAllTracks(), std::move(meta) ) ); } else if( m_hdr.version == static_cast<uint16_t>(eDSEVersion::V402) ) { //Parse tracks and return return std::move( MusicSequence( ParseAllTracks(), std::move(meta) ) ); } else { #ifdef _DEBUG cerr << "SMDL_Parser::operator MusicSequence() : Unsupported DSE version!!"; assert(false); #endif throw runtime_error( "SMDL_Parser::operator MusicSequence() : Unsupported DSE version!!" ); } }
/***************************** * ScanHeader * Download the data until the header is finished * Returns: Success if return header has a 200 status */ uint32_t ScanHeader(int32_t sockDesc, std::map<std::string, std::string> & header_value, std::string & urlData ) { int32_t length = -1; std::string::size_type cut_at = 0; std::string header = ""; uint8_t rev[RCVBUFSIZE]; #if defined (__GAMECUBE__) || defined (__WII__) while ( ( length = net_recv(sockDesc, (char*)rev, RCVBUFSIZE, 0)) > 0 ) #else while ( ( length = recv(sockDesc, (char*)rev, RCVBUFSIZE, 0)) > 0 ) #endif { urlData.append((char*)rev, length); memset(rev, 0, RCVBUFSIZE); cut_at = urlData.find(http_split); if ( cut_at != urlData.npos ) { header = urlData.substr( 0, cut_at ); urlData.erase( 0, cut_at+4 ); return (ParseHeader( header, header_value ) == 200); } } return false; }
ECode CHttpAuthHeader::constructor( /* [in] */ const String& header) { if (header != NULL) { ParseHeader(header); } return NOERROR; }
bool HttpProtocol::ParseHeader( char* header,INT32 len ) { char tmp = 0; std::swap(header[len],tmp); bool result = ParseHeader(header); std::swap(header[len],tmp); return result; }
AnimParser::AnimParser(const uint8_t* data, uint32_t data_size) : data(data), data_size(data_size), ptr(data), size(data_size) { ParseHeader(); ParsePalette(); ParseFrames(); ParseFrameInfos(); ParseFrameSequences(); assert(size == 0); }
//============================================================================= // Parsing Request //============================================================================= //----------------------------------------------------------------------------- // Main Request Parsing // RFC2616 // generic-message = start-line // *(message-header CRLF) // CRLF // [ message-body ] // start-line = Request-Line | Status-Line //----------------------------------------------------------------------------- bool CWebserverRequest::HandleRequest(void) { std::string start_line = ""; // read first line do { start_line = Connection->sock->ReceiveLine(); if (!Connection->sock->isValid) return false; if (start_line == "") // Socket empty { log_level_printf(1, "HandleRequest: End of line not found\n"); Connection->Response.SendError(HTTP_INTERNAL_SERVER_ERROR); Connection->RequestCanceled = true; return false; } } while (start_line == "\r\n"); // ignore empty lines at begin on start-line start_line = trim(start_line); log_level_printf(1, "Request: %s\n", start_line.c_str()); UrlData["startline"] = start_line; if (!ParseStartLine(start_line)) return false; if (Connection->Method == M_GET || Connection->Method == M_HEAD) { std::string tmp_line; //read header (speed up: read rest of request in blockmode) tmp_line = Connection->sock->ReceiveBlock(); if (!Connection->sock->isValid) { Connection->Response.SendError(HTTP_INTERNAL_SERVER_ERROR); return false; } if (tmp_line == "") { Connection->Response.SendError(HTTP_INTERNAL_SERVER_ERROR); return false; } ParseHeader(tmp_line); } // Other Methods if (Connection->Method == M_DELETE || Connection->Method == M_PUT || Connection->Method == M_TRACE) { //todo: implement aprintf("HTTP Method not implemented :%d\n", Connection->Method); Connection->Response.SendError(HTTP_NOT_IMPLEMENTED); return false; } // handle POST (read header & body) if (Connection->Method == M_POST) { Connection->Response.Write("HTTP/1.1 100 Continue\r\n\r\n"); // POST Requests requires CONTINUE in HTTP/1.1 return HandlePost(); } // if you are here, something went wrong return true; }
void CHTTPClient::RequestComplete() { dwLastByte = ::XPlatGetMilliseconds(); bReadComplete = TRUE; // Header may be incomplete so try and get status anyway if (!bHeader) ParseHeader(); cRecvEvent.SetEvent(); };
bool cSatipRtsp::Setup(const char *uriP, int rtpPortP, int rtcpPortP) { debug1("%s (%s, %d, %d) [device %d]", __PRETTY_FUNCTION__, uriP, rtpPortP, rtcpPortP, tunerM.GetId()); bool result = false; if (handleM && !isempty(uriP)) { cString transport; long rc = 0; cTimeMs processing(0); CURLcode res = CURLE_OK; switch (modeM) { case cmMulticast: // RTP/AVP;multicast;destination=<IP multicast address>;port=<RTP port>-<RTCP port>;ttl=<ttl> transport = cString::sprintf("RTP/AVP;multicast;port=%d-%d", rtpPortP, rtcpPortP); break; default: case cmUnicast: // RTP/AVP;unicast;client_port=<client RTP port>-<client RTCP port> transport = cString::sprintf("RTP/AVP;unicast;client_port=%d-%d", rtpPortP, rtcpPortP); break; } // Setup media stream SATIP_CURL_EASY_SETOPT(handleM, CURLOPT_RTSP_STREAM_URI, uriP); SATIP_CURL_EASY_SETOPT(handleM, CURLOPT_RTSP_TRANSPORT, *transport); SATIP_CURL_EASY_SETOPT(handleM, CURLOPT_RTSP_REQUEST, (long)CURL_RTSPREQ_SETUP); // Set header callback for catching the session and timeout SATIP_CURL_EASY_SETOPT(handleM, CURLOPT_HEADERFUNCTION, cSatipRtsp::HeaderCallback); SATIP_CURL_EASY_SETOPT(handleM, CURLOPT_WRITEHEADER, this); SATIP_CURL_EASY_SETOPT(handleM, CURLOPT_WRITEFUNCTION, cSatipRtsp::DataCallback); SATIP_CURL_EASY_SETOPT(handleM, CURLOPT_WRITEDATA, this); SATIP_CURL_EASY_PERFORM(handleM); // Session id is now known - disable header parsing SATIP_CURL_EASY_SETOPT(handleM, CURLOPT_HEADERFUNCTION, NULL); SATIP_CURL_EASY_SETOPT(handleM, CURLOPT_WRITEHEADER, NULL); SATIP_CURL_EASY_SETOPT(handleM, CURLOPT_WRITEFUNCTION, NULL); SATIP_CURL_EASY_SETOPT(handleM, CURLOPT_WRITEDATA, NULL); if (headerBufferM.Size() > 0) { ParseHeader(); headerBufferM.Reset(); } if (dataBufferM.Size() > 0) { ParseData(); dataBufferM.Reset(); } result = ValidateLatestResponse(&rc); debug5("%s (%s, %d, %d) Response %ld in %" PRIu64 " ms [device %d]", __PRETTY_FUNCTION__, uriP, rtpPortP, rtcpPortP, rc, processing.Elapsed(), tunerM.GetId()); } return result; }
/***************************************************** * ApplyPatchToFileByHandles (MSPATCHA.2) */ BOOL WINAPI ApplyPatchToFileByHandles(HANDLE patch_file, HANDLE old_file, HANDLE new_file, ULONG apply_flags) { SAFE_READ Patch, OldFile; DWORD dwStatus; PATCH_HEADER Header; Patch.Root = Patch.Ptr = MapFile(patch_file, &Patch.Size); if (!Patch.Root) { SetLastError(ERROR_PATCH_CORRUPT); return FALSE; } /* Let's decode the header */ dwStatus = ParseHeader(&Patch, &Header); if (dwStatus != STATUS_SUCCESS) { UnmapViewOfFile(Patch.Root); SetLastError(dwStatus); return FALSE; } OldFile.Root = OldFile.Ptr = MapFile(old_file, &OldFile.Size); if (OldFile.Root) { DWORD dwCrc; /* Verify the input file */ dwCrc = RtlComputeCrc32(0, OldFile.Root, OldFile.Size); if (OldFile.Size == Header.OldSize && dwCrc == Header.OldCrc) { if (apply_flags & APPLY_OPTION_TEST_ONLY) dwStatus = STATUS_SUCCESS; else dwStatus = CreateNewFileFromPatch(&Header, &Patch, new_file); } else { dwStatus = ERROR_PATCH_WRONG_FILE; } UnmapViewOfFile(OldFile.Root); } else { dwStatus = GetLastError(); if (dwStatus == STATUS_SUCCESS) dwStatus = ERROR_PATCH_NOT_AVAILABLE; } UnmapViewOfFile(Patch.Root); SetLastError(dwStatus); return dwStatus == STATUS_SUCCESS; }
LinkLayerParser::State LinkLayerParser::ParseOneStep() { switch (state) { case(State::FindSync) : return ParseSync(); case(State::ReadHeader) : return ParseHeader(); case(State::ReadBody) : return ParseBody(); default: return state; } }
/*--------------------------------------------------------------------------------*/ ADMObject *XMLADMData::Parse(const std::string& type, void *userdata) { ADMHEADER header; ADMObject *obj; ParseHeader(header, type, userdata); // delete any existing object of the same ID UNLESS it's an ADMAudioTrack if ((obj = Create(type, header.id, header.name, (type != ADMAudioTrack::Type))) != NULL) { ParseValues(obj, userdata); PostParse(obj, userdata); obj->SetValues(); } return obj; }
void PacketStreamReader::Init() { lock_guard<decltype(_mutex)> lg(_mutex); if (!_stream.is_open()) throw runtime_error("Cannot open stream."); for (auto i : PANGO_MAGIC) { if (_stream.get() != i) throw runtime_error("Unrecognised file header."); if (!_stream.good()) throw runtime_error("Bad stream"); } SetupIndex(); ParseHeader(); while (_stream.peekTag() == TAG_ADD_SOURCE) ParseNewSource(); }
// parse and load a DXF file // currently pretty limited, but knows enough to handle 3DFACEs and LINEs bool DXFRenderer::Load(wxInputStream& stream) { Clear(); wxTextInputStream text(stream); wxString line1, line2; while (stream.CanRead()) { GetLines(text, line1, line2); if (line1 == "999") // comment continue; else if (line1 == "0" && line2 == "SECTION") { GetLines(text, line1, line2); if (line1 == "2") { if (line2 == "HEADER") { if (!ParseHeader(stream)) return false; } else if (line2 == "TABLES") { if (!ParseTables(stream)) return false; } else if (line2 == "ENTITIES") { if (!ParseEntities(stream)) return false; } } } } NormalizeEntities(); m_loaded = true; return true; }
int HTTPSession::AddData(unsigned char* buf, int len){ int ret = 0; //Do we need more memory if(currentFillLength + len > sessionBufLen){ if(sessionBufLen + 2048 > 8192){ //8k max return -9; } sessionBuf = (char*)realloc(sessionBuf, sessionBufLen + 2048); sessionBufLen = sessionBufLen + 2048; } //header ? memset(&sessionBuf[currentFillLength], 0, sessionBufLen - currentFillLength); memcpy(&sessionBuf[currentFillLength], buf, len); if(firstData){ ret = ParseHeader((unsigned char*)&sessionBuf[currentFillLength], len); if(ret < 0){ return ret; } } firstData = false; currentFillLength = currentFillLength + len; //Complete ? if(mContentlength <= 0){ return 0;//at the moment only CONTENT-LENGTH headers are supported, add also chunked-encoding;see UPnP architecture 4.3.2 } if(currentFillLength >= mContentlength + mHeaderlength){ mBody = sessionBuf + mHeaderlength; mBodyLen = currentFillLength - mHeaderlength; return 0; } return mContentlength + mHeaderlength - currentFillLength;//check todo }
// ----------------------------------------------------------------------------- // CUpnpHttpChunkParser::Parse // Decoding the chunked-encoded buffer // ----------------------------------------------------------------------------- // TInt CUpnpHttpChunkParser::Parse(TDes8& aBuffer, TInt& aPos) { TBool interrupt = EFalse; while(!interrupt) { switch(iContext) { case EUnknown: iContext = EHeader; break; case EHeader: interrupt = ParseHeader(aBuffer,aPos); break; case ELastChunk: interrupt = ParseLastChunk(aBuffer,aPos); break; case EBody: interrupt = ParseBody(aBuffer,aPos); break; case EEndChunkBody: iContext = EHeader; break; case EExtension: interrupt = ParseExtension(aBuffer,aPos); break; case ETrailer: interrupt = ParseTrailer(aBuffer,aPos); break; case EError: return iError; case EFinish: return KErrNone; default: return KErrUnknown; } } return KErrNone; }
PacketStreamReader::FrameInfo PacketStreamReader::_nextFrame() { while (1) { auto t = _stream.peekTag(); switch (t) { case TAG_PANGO_SYNC: SkipSync(); break; case TAG_ADD_SOURCE: ParseNewSource(); break; case TAG_SRC_JSON: //frames are sometimes preceded by metadata, but metadata must ALWAYS be followed by a frame from the same source. case TAG_SRC_PACKET: return _stream.peekFrameHeader(*this); case TAG_PANGO_STATS: ParseIndex(); break; case TAG_PANGO_FOOTER: //end of frames case TAG_END: return FrameInfo(); //none case TAG_PANGO_HDR: //shoudln't encounter this ParseHeader(); break; case TAG_PANGO_MAGIC: //or this SkipSync(); break; default: //or anything else pango_print_warn("Unexpected packet type: \"%s\". Resyncing()\n", tagName(t).c_str()); ReSync(); break; } } }
BOOL CVCAMetaParserMSXML::ParseMetaData( unsigned char *pMetadata, int nLength ) { CComBSTR sz( (char *)pMetadata ); VARIANT_BOOL vb; USES_CONVERSION; pMetadata[nLength] = '\0'; BSTR bstr = SysAllocString( A2W( (char *)pMetadata ) ); // sz = CComBSTR("<?xml version=\"1.0\"?>\n<vca>\n <vca_hdr>\n <frame_id>10</frame_id>\n </vca_hdr>\n</vca>\n"); // TRACE( (char *)pMetadata ); vb = m_pDOMDoc->loadXML( bstr); // FILE *pFile; // pFile = fopen( "C:\\vtmeta.txt", "a" ); // fwrite( pMetadata, strlen( (char *)pMetadata ), 1, pFile ); // fclose( pFile ); if( VARIANT_TRUE == vb ) { // Find the header ParseHeader(); ParseStab(); ParseObjects(); ParseEvents(); ParseCounts(); ParseBlobsImp(_XML_TAMPERMAP, &m_TamperInfo); ParseBlobsImp(_XML_SCENECHANGEMAP, &m_SceneChangeInfo); ParseBlobsImp(_XML_BLOBMAP, &m_BlobMap); ParseBlobsImp(_XML_STATBLOBMAP, &m_StationaryMap); ParseBlobsImp(_XML_SMOKEMAP,&m_SmokeMap); ParseBlobsImp(_XML_FIREMAP,&m_FireMap); ParseCE(); } else { // Loading the doc failed, find out why... MSXML2::IXMLDOMParseErrorPtr pErr = m_pDOMDoc->parseError; CString strLine, sResult; strLine.Format(_T(" ( line %u, column %u )"), pErr->Getline(), pErr->Getlinepos()); // Return validation results in message to the user. if (pErr->errorCode != S_OK) { sResult = CString("Validation failed on ") + CString ("\n=====================") + CString("\nReason: ") + CString( (char*)(pErr->Getreason())) + CString("\nSource: ") + CString( (char*)(pErr->GetsrcText())) + strLine + CString("\n"); ATLTRACE(sResult); // AfxMessageBox( (char *)pMetadata ); } } // memset( pMetadata, NULL, 2048 ); SysFreeString( bstr ); return TRUE; }
nsresult SnappyUncompressInputStream::ParseNextChunk(uint32_t* aBytesReadOut) { // There must not be any uncompressed data already in mUncompressedBuffer. MOZ_ASSERT(mUncompressedBytes == 0); MOZ_ASSERT(mNextByte == 0); nsresult rv; *aBytesReadOut = 0; // Lazily create our two buffers so we can report OOM during stream // operation. These allocations only happens once. The buffers are reused // until the stream is closed. if (!mUncompressedBuffer) { mUncompressedBuffer.reset(new (fallible) char[snappy::kBlockSize]); if (NS_WARN_IF(!mUncompressedBuffer)) { return NS_ERROR_OUT_OF_MEMORY; } } if (!mCompressedBuffer) { mCompressedBuffer.reset(new (fallible) char[CompressedBufferLength()]); if (NS_WARN_IF(!mCompressedBuffer)) { return NS_ERROR_OUT_OF_MEMORY; } } // We have no decompressed data and we also have not seen the start of stream // yet. Read and validate the StreamIdentifier chunk. Also read the next // header to determine the size of the first real data chunk. if (mNeedFirstStreamIdentifier) { const uint32_t firstReadLength = kHeaderLength + kStreamIdentifierDataLength + kHeaderLength; MOZ_ASSERT(firstReadLength <= CompressedBufferLength()); rv = ReadAll(mCompressedBuffer.get(), firstReadLength, firstReadLength, aBytesReadOut); if (NS_WARN_IF(NS_FAILED(rv)) || *aBytesReadOut == 0) { return rv; } rv = ParseHeader(mCompressedBuffer.get(), kHeaderLength, &mNextChunkType, &mNextChunkDataLength); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } if (NS_WARN_IF(mNextChunkType != StreamIdentifier || mNextChunkDataLength != kStreamIdentifierDataLength)) { return NS_ERROR_CORRUPTED_CONTENT; } size_t offset = kHeaderLength; mNeedFirstStreamIdentifier = false; size_t numRead; size_t numWritten; rv = ParseData(mUncompressedBuffer.get(), snappy::kBlockSize, mNextChunkType, &mCompressedBuffer[offset], mNextChunkDataLength, &numWritten, &numRead); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } MOZ_ASSERT(numWritten == 0); MOZ_ASSERT(numRead == mNextChunkDataLength); offset += numRead; rv = ParseHeader(&mCompressedBuffer[offset], *aBytesReadOut - offset, &mNextChunkType, &mNextChunkDataLength); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } return NS_OK; } // We have no compressed data and we don't know how big the next chunk is. // This happens when we get an EOF pause in the middle of a stream and also // at the end of the stream. Simply read the next header and return. The // chunk body will be read on the next entry into this method. if (mNextChunkType == Unknown) { rv = ReadAll(mCompressedBuffer.get(), kHeaderLength, kHeaderLength, aBytesReadOut); if (NS_WARN_IF(NS_FAILED(rv)) || *aBytesReadOut == 0) { return rv; } rv = ParseHeader(mCompressedBuffer.get(), kHeaderLength, &mNextChunkType, &mNextChunkDataLength); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } return NS_OK; } // We have no decompressed data, but we do know the size of the next chunk. // Read at least that much from the base stream. uint32_t readLength = mNextChunkDataLength; MOZ_ASSERT(readLength <= CompressedBufferLength()); // However, if there is enough data in the base stream, also read the next // chunk header. This helps optimize the stream by avoiding many small reads. uint64_t avail; rv = mBaseStream->Available(&avail); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } if (avail >= (readLength + kHeaderLength)) { readLength += kHeaderLength; MOZ_ASSERT(readLength <= CompressedBufferLength()); } rv = ReadAll(mCompressedBuffer.get(), readLength, mNextChunkDataLength, aBytesReadOut); if (NS_WARN_IF(NS_FAILED(rv)) || *aBytesReadOut == 0) { return rv; } size_t numRead; size_t numWritten; rv = ParseData(mUncompressedBuffer.get(), snappy::kBlockSize, mNextChunkType, mCompressedBuffer.get(), mNextChunkDataLength, &numWritten, &numRead); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } MOZ_ASSERT(numRead == mNextChunkDataLength); mUncompressedBytes = numWritten; // If we were unable to directly read the next chunk header, then clear // our internal state. We will have to perform a small read to get the // header the next time we enter this method. if (*aBytesReadOut <= mNextChunkDataLength) { mNextChunkType = Unknown; mNextChunkDataLength = 0; return NS_OK; } // We got the next chunk header. Parse it so that we are ready to for the // next call into this method. rv = ParseHeader(&mCompressedBuffer[numRead], *aBytesReadOut - numRead, &mNextChunkType, &mNextChunkDataLength); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } return NS_OK; }
int MsgHandler::Parse(const char * msg) { return ParseHeader(msg); }
PdbReader::PdbReader(const WCHAR *filePath) : data(file::ReadAll(filePath, &dataSize)) { if (!ParseHeader()) recOffsets.Reset(); }
//------------------------------------------------------------------------- bool CWebserverRequest::ParseRequest() { int ende; if(rawbuffer_len > 0 ) { if((ende = rawbuffer.find_first_of('\n')) == 0) { aprintf("ParseRequest: End of line not found\n"); Send500Error(); return false; } string zeile1 = rawbuffer.substr(0,ende-1); if(ParseFirstLine(zeile1)) { unsigned int i; for(i = 0; ((rawbuffer[i] != '\n') || (rawbuffer[i+2] != '\n')) && (i < rawbuffer.length());i++); int headerende = i; // dprintf("headerende: %d buffer_len: %d\n",headerende,rawbuffer_len); if(headerende == 0) { aprintf("ParseRequest: no headers found\n"); Send500Error(); return false; } string header = rawbuffer.substr(ende+1,headerende - ende - 2); ParseHeader(header); Host = HeaderList["Host"]; if(Method == M_POST) // TODO: Und testen ob content = formdata { string t = "multipart/form-data; boundary="; if(HeaderList["Content-Type"].compare(0,t.length(),t) == 0) { SocketWriteLn("Sorry, momentan broken\n"); /*Boundary = "--" + HeaderList["Content-Type"].substr(t.length(),HeaderList["Content-Type"].length() - t.length()); dprintf("Boundary: '%s'\n",Boundary.c_str()); if((headerende + 3) < rawbuffer_len) ParseBoundaries(rawbuffer.substr(headerende + 3,rawbuffer_len - (headerende + 3))); HandleUpload();*/ } else if(HeaderList["Content-Type"].compare("application/x-www-form-urlencoded") == 0) { dprintf("Form Daten in Parameter String\n"); if((headerende + 3) < rawbuffer_len) { string params = rawbuffer.substr(headerende + 3,rawbuffer_len - (headerende + 3)); if(params[params.length()-1] == '\n') params.substr(0,params.length() -2); ParseParams(params); } } dprintf("Method Post !\n"); } /* if(Method == M_POST) // TODO: Und testen ob content = formdata { if( (ende + 3) < rawbuffer + rawbuffer_len) { // Parent->Debug("Post Parameter vorhanden\n"); anfang = ende + 3; Param_String = string(anfang,rawbuffer + rawbuffer_len - anfang); dprintf("Post Param_String: %s\n",Param_String.c_str()); ParseParams(Param_String); } if(HeaderList->GetIndex("Content-Type") != -1) { dprintf("Content-Type: %s\n",HeaderList->GetValue(HeaderList->GetIndex("Content-Type"))); if(strcasecmp("application/x-www-form-urlencoded",HeaderList->GetValue(HeaderList->GetIndex("Content-Type"))) == 0) dprintf("Form Daten in Parameter String\n"); if(strstr(HeaderList->GetValue(HeaderList->GetIndex("Content-Type")),"multipart/form-data") != 0) { char * boundary; boundary = strstr(HeaderList->GetValue(HeaderList->GetIndex("Content-Type")),"boundary="); if(boundary) { boundary += strlen("boundary="); dprintf("boundary : %s\n",boundary); Upload = new TUpload(this); Upload->Boundary = new TString(boundary); Boundary = new TString(boundary); dprintf("Form Daten in Parameter String und Datei upload\nBoundary: %ld\n",Boundary); } } } } */ return true; } else { SocketWrite("HTTP/1.0 501 Not implemented\r\n"); SocketWrite("Content-Type: text/plain\r\n\r\n"); SocketWrite("501 : Request-Method not implemented.\n"); HttpStatus = 501; // dprintf("501 : Request-Method not implemented.\n"); return false; } } return false; }
void XSDParser::BuildDocumentTree(CDataTypeModule& module) { size_t lexerStackSize = m_StackLexer.size(); bool skipEof = false; ParseHeader(); CopyComments(module.Comments()); TToken tok; int emb=0; for (;;) { tok = GetNextToken(); switch ( tok ) { case K_INCLUDE: ParseInclude(); break; case K_ELEMENT: ParseElementContent(0, emb); break; case K_ATTRIBUTE: ParseAttributeContent(); break; case K_COMPLEXTYPE: case K_SIMPLETYPE: CreateTypeDefinition(DTDEntity::eType); break; case K_GROUP: CreateTypeDefinition(DTDEntity::eGroup); break; case K_ATTPAIR: break; case T_EOF: if (skipEof) { skipEof = false; break; } ParseError("Unexpected end-of-file", "keyword"); return; case K_ENDOFTAG: if (m_StackLexer.size() > lexerStackSize) { skipEof = true; break; } if (m_SrcType == eSchema) { ProcessNamedTypes(); } return; case K_IMPORT: ParseImport(); break; case K_ATTRIBUTEGROUP: CreateTypeDefinition(DTDEntity::eAttGroup); break; case K_ANNOTATION: m_Comments = &(module.Comments()); ParseAnnotation(); break; default: ParseError("Invalid keyword", "keyword"); return; } } }
/*=========================================================================*/ int SLPMessageParseBuffer(SLPBuffer buffer, SLPMessage message) /* Initializes a message descriptor by parsing the specified buffer. */ /* */ /* buffer - (IN) pointer the SLPBuffer to parse */ /* */ /* message - (OUT) set to describe the message from the buffer */ /* */ /* Returns - Zero on success, SLP_ERROR_PARSE_ERROR, or */ /* SLP_ERROR_INTERNAL_ERROR if out of memory. SLPMessage is */ /* invalid return is not successful. */ /* */ /* WARNING - If successful, pointers in the SLPMessage reference memory in*/ /* the parsed SLPBuffer. If SLPBufferFree() is called then the */ /* pointers in SLPMessage will be invalidated. */ /*=========================================================================*/ { int result; /* Get ready to parse */ SLPMessageFreeInternals(message); buffer->curpos = buffer->start; /* parse the header first */ result = ParseHeader(buffer,&(message->header)); if(result == 0) { #if defined(ENABLE_SLPv1) if(message->header.version == 1) return SLPv1MessageParseBuffer(buffer, &(message->header), message); #endif /* switch on the function id to parse the body */ switch(message->header.functionid) { case SLP_FUNCT_SRVRQST: result = ParseSrvRqst(buffer,&(message->body.srvrqst)); break; case SLP_FUNCT_SRVRPLY: result = ParseSrvRply(buffer,&(message->body.srvrply)); break; case SLP_FUNCT_SRVREG: result = ParseSrvReg(buffer,&(message->body.srvreg)); break; case SLP_FUNCT_SRVDEREG: result = ParseSrvDeReg(buffer,&(message->body.srvdereg)); break; case SLP_FUNCT_SRVACK: result = ParseSrvAck(buffer,&(message->body.srvack)); break; case SLP_FUNCT_ATTRRQST: result = ParseAttrRqst(buffer,&(message->body.attrrqst)); break; case SLP_FUNCT_ATTRRPLY: result = ParseAttrRply(buffer,&(message->body.attrrply)); break; case SLP_FUNCT_DAADVERT: result = ParseDAAdvert(buffer,&(message->body.daadvert)); break; case SLP_FUNCT_SRVTYPERQST: result = ParseSrvTypeRqst(buffer,&(message->body.srvtyperqst)); break; case SLP_FUNCT_SRVTYPERPLY: result = ParseSrvTypeRply(buffer,&(message->body.srvtyperply)); break; #if 0 case SLP_FUNCT_SAADVERT: result = ParseSAAdvert(buffer,&(message->body.saadvert)); break; #endif default: result = SLP_ERROR_MESSAGE_NOT_SUPPORTED; } } return result; }
DWORD LWParseConfigFile( PCSTR pszFilePath, PCFGSECTION* ppCfgSectionList, BOOLEAN bWindowsDoubleByteFormat ) { DWORD dwError = 0; PCFGSECTION pSectionList = NULL; PCFGSECTION pSection = NULL; PNVPAIR pNVPair = NULL; FILE* fp = NULL; CHAR staticBuffer[1024+1]; PSTR szBuf = NULL; DWORD dwLen = 0; PSTR pszTmp = NULL; PSTR pszName = NULL; PSTR pszValue = NULL; DWORD dwSignature = 0; /*DWORD nRead = 0;*/ BOOLEAN bEOF = FALSE; if ((fp = fopen(pszFilePath, "r")) == NULL) { dwError = errno; goto error; } if (fcntl(fileno(fp), F_SETFD, FD_CLOEXEC) < 0) { dwError = errno; BAIL_ON_MAC_ERROR(dwError); } if (bWindowsDoubleByteFormat) { dwError = ParseHeader(fp, &dwSignature); BAIL_ON_MAC_ERROR(dwError); if (dwSignature != 0xFEFF) { dwError = MAC_AD_ERROR_INVALID_TAG; BAIL_ON_MAC_ERROR(dwError); } } while (!bEOF) { LW_SAFE_FREE_STRING(szBuf); if (bWindowsDoubleByteFormat) { staticBuffer[0] = '\0'; dwError = ReadNextDoubleByteLine(fp, staticBuffer, 1024, &bEOF); BAIL_ON_MAC_ERROR(dwError); dwError = LwAllocateString(staticBuffer, &szBuf); BAIL_ON_MAC_ERROR(dwError); } else { dwError = ReadNextLine(fp, &szBuf, &bEOF); BAIL_ON_MAC_ERROR(dwError); } LwStripWhitespace(szBuf, TRUE, TRUE); if (!(dwLen=strlen(szBuf))) continue; /* Skip comments for now */ if (szBuf[0] == '#' || szBuf[0] == ';') continue; if (szBuf[0] == '[' && szBuf[dwLen-1] == ']') { if (pSection) { pSection->pNext = pSectionList; pSectionList = pSection; pSection = NULL; } dwError = LwAllocateMemory(sizeof(CFGSECTION), (PVOID*)&pSection); BAIL_ON_MAC_ERROR(dwError); szBuf[dwLen-1] = '\0'; dwError = LwAllocateString(szBuf+1, &pSection->pszName); BAIL_ON_MAC_ERROR(dwError); LwStripWhitespace(pSection->pszName, TRUE, TRUE); } else { if (!pSection) { dwError = MAC_AD_ERROR_NO_SUCH_ATTRIBUTE; BAIL_ON_MAC_ERROR(dwError); } if ((pszTmp = strchr(szBuf, '=')) == NULL) { continue; } if (pszTmp == szBuf) { dwError = MAC_AD_ERROR_INVALID_TAG; BAIL_ON_MAC_ERROR(dwError); } dwError = LwAllocateMemory(pszTmp-szBuf+1, (PVOID*)&pszName); BAIL_ON_MAC_ERROR(dwError); strncpy(pszName, szBuf, pszTmp-szBuf); pszTmp++; while (*pszTmp != '\0' && isspace((int)*pszTmp)) pszTmp++; if (*pszTmp != '\0') { dwError = LwAllocateString(pszTmp, &pszValue); BAIL_ON_MAC_ERROR(dwError); } dwError = LwAllocateMemory(sizeof(NVPAIR), (PVOID*)&pNVPair); BAIL_ON_MAC_ERROR(dwError); LwStripWhitespace(pszName, TRUE, TRUE); LwStripWhitespace(pszValue, TRUE, TRUE); pNVPair->pszName = pszName; pszName = NULL; pNVPair->pszValue = pszValue; pszValue = NULL; pNVPair->pNext = pSection->pNVPairList; pSection->pNVPairList = pNVPair; pNVPair = NULL; } } if (pSection) { pSection->pNext = pSectionList; pSectionList = pSection; pSection = NULL; } pSectionList = ReverseSectionsAndNVPairs(pSectionList); *ppCfgSectionList = pSectionList; fclose(fp); fp = NULL; cleanup: LW_SAFE_FREE_STRING(szBuf); if (fp) { fclose(fp); } LW_SAFE_FREE_STRING(pszName); LW_SAFE_FREE_STRING(pszValue); return dwError; error: *ppCfgSectionList = NULL; if (pSectionList) { LWFreeConfigSectionList(pSectionList); } if (pSection) { LWFreeSection(pSection); } if (pNVPair) { LWFreeNVPair(pNVPair); } goto cleanup; }
int WSClientParser::ParseData(char* buffer, int len) { switch_log_printf( SWITCH_CHANNEL_UUID_LOG(this->uuid), SWITCH_LOG_DEBUG, "WSClientParser::ParseData( " "this : %p, " "len : %d " // "buffer : \n%s\n" ") \n", this, len // buffer ); int ret = 0; // DataParser::ParseData(NULL, len); Lock(); switch( mState ) { case WSClientState_UnKnow:{ int lineNumber = 0; char line[HTTP_URL_MAX_PATH]; int lineLen = 0; const char* header = buffer; const char* sepHeader = strstr(buffer, HTTP_HEADER_SEP); const char* sep = NULL; if( sepHeader ) { switch_log_printf( SWITCH_CHANNEL_UUID_LOG(this->uuid), SWITCH_LOG_INFO, "WSClientParser::ParseData( " "[HandShake], " "this : %p, " "len : %d, " "buffer : \n%s\n" ") \n", this, len, buffer ); // Parse HTTP header separator ret = sepHeader - buffer + strlen(HTTP_HEADER_SEP); // Parse HTTP header line separator while( true ) { if( (sep = strstr(header, HTTP_LINE_SEP)) && sep != sepHeader ) { lineLen = sep - header; if( lineLen < sizeof(line) - 1 ) { memcpy(line, header, lineLen); line[lineLen] = '\0'; if( lineNumber == 0 ) { // Get First Line if( !ParseFirstLine(line) ) { break; } } else { ParseHeader(line); if( CheckHandShake() ) { break; } } } header += lineLen + strlen(HTTP_LINE_SEP); lineNumber++; } else { break; } } } if( mState == WSClientState_Handshake ) { if( mpCallback ) { mpCallback->OnWSClientParserHandshake(this); } } else { if( mpCallback ) { mpCallback->OnWSClientDisconected(this); } } }break; case WSClientState_Handshake:{ } case WSClientState_Data:{ // char temp[4096] = {0}; // char *p = temp; // unsigned char c; // for(int i = 0; i< len; i++) { // c = buffer[i]; // sprintf(p, "%c%c,", hex[c >> 4], hex[c & (16 - 1)]); // p += 3; // } // switch_log_printf( // SWITCH_CHANNEL_UUID_LOG(this->uuid), // SWITCH_LOG_INFO, // "WSClientParser::ParseData( " // "parser : %p, " // "hex : \n%s\n" // ") \n", // this, // temp // ); WSPacket* packet = (WSPacket *)buffer; // switch_log_printf( // SWITCH_CHANNEL_UUID_LOG(this->uuid), // SWITCH_LOG_INFO, // "WSClientParser::ParseData( " // "parser : %p, " // "packet->Fin : %s, " // "packet->RSV : %u, " // "packet->Opcode : %u, " // "packet->Mask : %s, " // "packet->Playload Length : %u, " // "packet->Extend Playload Length : %llu, " // "packet->Mask Key : %s " // ") \n", // this, // packet->baseHeader.IsFin()?"true":"false", // packet->baseHeader.GetRSVType(), // packet->baseHeader.GetOpcode(), // packet->baseHeader.IsMask()?"true":"false", // packet->baseHeader.GetPlayloadLength(), // packet->GetPlayloadLength(), // packet->GetMaskKey() // ); const char* data = (const char*)packet->GetData();//buffer;//packet->GetData(); int playloadLength = packet->GetPlayloadLength();//len;//packet->GetPlayloadLength(); ret = packet->GetHeaderLength() + playloadLength; if( mpCallback) { mpCallback->OnWSClientParserData(this, data, playloadLength); } }break; case WSClientState_Disconnected:{ ret = len; }break; default:{ break; } } Unlock(); return ret; }
PdbReader::PdbReader(IStream *stream) : data((char *)GetDataFromStream(stream, &dataSize)) { if (!ParseHeader()) recOffsets.Reset(); }
/*!*************************************************************************** @Function Parse @Output pReturnError error string @Return bool true for success parsing file @Description Parses a loaded PFX file. *****************************************************************************/ bool CPVRTPFXParser::Parse(CPVRTString * const pReturnError) { int nEndLine = 0; int nHeaderCounter = 0, nTexturesCounter = 0; unsigned int i,j,k; m_nNumVertShaders = 0; m_nNumFragShaders = 0; m_nNumEffects = 0; // Loop through the file for(unsigned int nLine=0; nLine < m_psContext->nNumLines; nLine++) { // Skip blank lines if(!*m_psContext->ppszEffectFile[nLine]) continue; if(strcmp("[HEADER]", m_psContext->ppszEffectFile[nLine]) == 0) { if(nHeaderCounter>0) { sprintf(errorMsg, "[HEADER] redefined on line %d\n", m_psContext->pnFileLineNumber[nLine]); *pReturnError = errorMsg; return false; } if(GetEndTag("HEADER", nLine, &nEndLine)) { if(ParseHeader(nLine, nEndLine, pReturnError)) nHeaderCounter++; else return false; } else { sprintf(errorMsg, "Missing [/HEADER] tag after [HEADER] on line %d\n", m_psContext->pnFileLineNumber[nLine]); *pReturnError = errorMsg; return false; } nLine = nEndLine; } else if(strcmp("[TEXTURES]", m_psContext->ppszEffectFile[nLine]) == 0) { if(nTexturesCounter>0) { sprintf(errorMsg, "[TEXTURES] redefined on line %d\n", m_psContext->pnFileLineNumber[nLine]); *pReturnError = errorMsg; return false; } if(GetEndTag("TEXTURES", nLine, &nEndLine)) { if(ParseTextures(nLine, nEndLine, pReturnError)) nTexturesCounter++; else return false; } else { sprintf(errorMsg, "Missing [/TEXTURES] tag after [TEXTURES] on line %d\n", m_psContext->pnFileLineNumber[nLine]); *pReturnError = errorMsg; return false; } nLine = nEndLine; } else if(strcmp("[VERTEXSHADER]", m_psContext->ppszEffectFile[nLine]) == 0) { if(GetEndTag("VERTEXSHADER", nLine, &nEndLine)) { if(m_nNumVertShaders >= m_nMaxVertShaders) { sprintf(errorMsg, "%d vertex shaders read, can't store any more, on line %d\n", m_nNumVertShaders, m_psContext->pnFileLineNumber[nLine]); *pReturnError = errorMsg; return false; } if(ParseShader(nLine, nEndLine, pReturnError, m_psVertexShader[m_nNumVertShaders], "VERTEXSHADER")) m_nNumVertShaders++; else { FREE(m_psVertexShader[m_nNumVertShaders].pszName); FREE(m_psVertexShader[m_nNumVertShaders].pszGLSLfile); FREE(m_psVertexShader[m_nNumVertShaders].pszGLSLcode); FREE(m_psVertexShader[m_nNumVertShaders].pszGLSLBinaryFile); return false; } } else { sprintf(errorMsg, "Missing [/VERTEXSHADER] tag after [VERTEXSHADER] on line %d\n", m_psContext->pnFileLineNumber[nLine]); *pReturnError = errorMsg; return false; } nLine = nEndLine; } else if(strcmp("[FRAGMENTSHADER]", m_psContext->ppszEffectFile[nLine]) == 0) { if(GetEndTag("FRAGMENTSHADER", nLine, &nEndLine)) { if(m_nNumFragShaders >= m_nMaxFragShaders) { sprintf(errorMsg, "%d fragment shaders read, can't store any more, on line %d\n", m_nNumFragShaders, m_psContext->pnFileLineNumber[nLine]); *pReturnError = errorMsg; return false; } if(ParseShader(nLine, nEndLine, pReturnError, m_psFragmentShader[m_nNumFragShaders], "FRAGMENTSHADER")) m_nNumFragShaders++; else { FREE(m_psFragmentShader[m_nNumFragShaders].pszName); FREE(m_psFragmentShader[m_nNumFragShaders].pszGLSLfile); FREE(m_psFragmentShader[m_nNumFragShaders].pszGLSLcode); FREE(m_psFragmentShader[m_nNumFragShaders].pszGLSLBinaryFile); return false; } } else { sprintf(errorMsg, "Missing [/FRAGMENTSHADER] tag after [FRAGMENTSHADER] on line %d\n", m_psContext->pnFileLineNumber[nLine]); *pReturnError = errorMsg; return false; } nLine = nEndLine; } else if(strcmp("[EFFECT]", m_psContext->ppszEffectFile[nLine]) == 0) { if(GetEndTag("EFFECT", nLine, &nEndLine)) { if(m_nNumEffects >= m_nMaxEffects) { sprintf(errorMsg, "%d effects read, can't store any more, on line %d\n", m_nNumEffects, m_psContext->pnFileLineNumber[nLine]); *pReturnError = errorMsg; return false; } if(ParseEffect(m_psEffect[m_nNumEffects], nLine, nEndLine, pReturnError)) m_nNumEffects++; else { for(i=0; i < m_psEffect[m_nNumEffects].nNumUniforms; ++i) { FREE(m_psEffect[m_nNumEffects].psUniform[i].pszName); FREE(m_psEffect[m_nNumEffects].psUniform[i].pszValue); } delete [] m_psEffect[m_nNumEffects].psUniform; for(i=0; i < m_psEffect[m_nNumEffects].nNumAttributes; ++i) { FREE(m_psEffect[m_nNumEffects].psAttribute[i].pszName); FREE(m_psEffect[m_nNumEffects].psAttribute[i].pszValue); } delete [] m_psEffect[m_nNumEffects].psAttribute; for(i=0; i < m_psEffect[m_nNumEffects].nNumTextures; ++i) { FREE(m_psEffect[m_nNumEffects].psTextures[i].pszName); } delete [] m_psEffect[m_nNumEffects].psTextures; FREE(m_psEffect[m_nNumEffects].pszFragmentShaderName); FREE(m_psEffect[m_nNumEffects].pszVertexShaderName); FREE(m_psEffect[m_nNumEffects].pszAnnotation); FREE(m_psEffect[m_nNumEffects].pszName); return false; } } else { sprintf(errorMsg, "Missing [/EFFECT] tag after [EFFECT] on line %d\n", m_psContext->pnFileLineNumber[nLine]); *pReturnError = errorMsg; return false; } nLine = nEndLine; } else { sprintf(errorMsg, "'%s' unexpected on line %d\n", m_psContext->ppszEffectFile[nLine], m_psContext->pnFileLineNumber[nLine]); *pReturnError = errorMsg; return false; } } if(m_nNumEffects < 1) { sprintf(errorMsg, "No [EFFECT] found. PFX file must have at least one defined.\n"); *pReturnError = errorMsg; return false; } if(m_nNumFragShaders < 1) { sprintf(errorMsg, "No [FRAGMENTSHADER] found. PFX file must have at least one defined.\n"); *pReturnError = errorMsg; return false; } if(m_nNumVertShaders < 1) { sprintf(errorMsg, "No [VERTEXSHADER] found. PFX file must have at least one defined.\n"); *pReturnError = errorMsg; return false; } for(i = 0; i < m_nNumEffects; ++i) { for(j = 0; j < m_psEffect[i].nNumTextures; ++j) { for(k = 0; k < m_nNumTextures; ++k) { if(strcmp(m_psEffect[i].psTextures[j].pszName, m_psTexture[k].pszName) == 0) break; } if(!m_nNumTextures || k == m_nNumTextures) { sprintf(errorMsg, "Error: TEXTURE '%s' is not defined in [TEXTURES].\n", m_psEffect[i].psTextures[j].pszName); *pReturnError = errorMsg; return false; } } } return true; }