/* Enviar msg erro: Tipo de Erro * Index **************************************** */ void send_ERROR( unsigned char error, unsigned char index ){ unsigned char *ptr; unsigned char t; unsigned int len; ptr = LENGTH_Build_ptr[1]; //LEN PDU *(ptr) = MSG_GET_RESPONSE+ASN_CONTEXT+ASN_FORMAT; //GetResponse ptr = parseHeader(ptr, &t, &len); //RID ptr = parseHeader(ptr, &t, &len); ptr += len; //ERROR ptr = parseHeader(ptr, &t, &len); *ptr = error; //ERROR_INDEX ptr += len; ptr = parseHeader(ptr, &t, &len); *ptr = index; sendtoUDP_socket(s, RX_ptr, SIZE_SNMP, IP_dest, PORT_dest); // Enviar data (UDP/IP RAW) }
int main(int argc, char *argv[]) { struct sockaddr_in si_me, si_other; int s, i, slen = sizeof(si_other) , numbytes; char buf[BUFLEN]; char *message; if (argc != 2){ fprintf(stderr,"usage: %s <port>\n", argv[0]); exit(1); } //create a UDP socket if ((s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1){ die("socket"); } // zero out the structure memset((char *) &si_me, 0, sizeof(si_me)); si_me.sin_family = AF_INET; si_me.sin_port = htons(atoi(argv[1])); si_me.sin_addr.s_addr = htonl(INADDR_ANY); //bind socket to port if( bind(s , (struct sockaddr*)&si_me, sizeof(si_me) ) == -1) die("bind"); //receive data if ((numbytes = recvfrom(s, buf, BUFLEN, 0, (struct sockaddr *) &si_other, &slen)) == -1) die("recvfrom()"); parseHeader(buf); //packet #2 if (strcmp(SYN_BIT, "1") == 0){ addHeader(0,1,"1","1", 100); strcpy(buf, header); if (sendto(s, buf, strlen(buf), 0, (struct sockaddr*) &si_other, slen) == -1) die("sendto()"); } if ((numbytes = recvfrom(s, buf, BUFLEN, 0, (struct sockaddr *) &si_other, &slen)) == -1) die("recvfrom()"); if ((numbytes = recvfrom(s, buf, BUFLEN, 0, (struct sockaddr *) &si_other, &slen)) == -1) die("recvfrom()"); message = parseHeader(buf); printf("server: received\n%s\n", message); //packet #5 addHeader(0,1,"1","1", 100); strcpy(buf, header); strcat(buf, "Okay! Sending you test.txt..."); if (sendto(s, buf, strlen(buf), 0, (struct sockaddr*) &si_other, slen) == -1) die("sendto()"); close(s); return 0; }
int main1(int argc, char * argv[]) { //test header parse char headerStr1[] = "Content-Length: 348"; char headerStr2[] = "Date: Tue, 15 Nov 1994 08:12:31 GMT"; Header * header1; Header * header2; header1 = (Header*) malloc(sizeof(Header)); header2 = (Header*) malloc(sizeof(Header)); if (header1 != NULL) { parseHeader(headerStr1, strlen(headerStr1), header1); printf("header1 name is %s\n header1 value is %s\n", header1->name, header1->value); } if (header2 != NULL) { parseHeader(headerStr2, strlen(headerStr2), header2); printf("header2 name is %s\n header2 value is %s\n", header2->name, header2->value); } free(header1); free(header2); //test request line parse char requestLine1[] = "GET http://www.w3.org/pub/WWW/TheProject.html HTTP/1.1"; char requestLine2[] = "GET /pub/WWW/TheProject.html HTTP/1.1"; RequestLine * line1; RequestLine * line2; line1 = (RequestLine*) malloc(sizeof(RequestLine)); line2 = (RequestLine*) malloc(sizeof(RequestLine)); if (line1) { parseHttpRequestLine(requestLine1, strlen(requestLine1), line1); printf("request line1's method is %s\n path is %s\n version is %s\n'", line1->method, line1->path, line1->version); } if (line2) { parseHttpRequestLine(requestLine2, strlen(requestLine2), line2); printf("request line2's method is %s\n path is %s\n version is %s\n'", line2->method, line2->path, line2->version); } free(line1); free(line2); //test formHeader Header *header; char headStr[1024]; header = (Header*) malloc(sizeof(Header)); strcpy(header->name,"Content-length"); strcpy(header->value,"123456"); formHeader(header,headStr,sizeof(headStr)); printf("headerStr is %s", headStr); return 0; }
static inline void parseHeaders(const String& headers, ResourceResponse& response) { int startPos = 0; int endPos; while ((endPos = headers.find('\n', startPos)) != -1) { ASSERT(startPos != endPos); parseHeader(headers.characters() + startPos, endPos - startPos, response); startPos = endPos + 1; } if (startPos != static_cast<int>(headers.length())) parseHeader(headers.characters(), headers.length(), response); }
HttpParser::status_t HttpParser::addBytes( const char* bytes, unsigned len ) { if ( _status != Incomplete ) { return _status; } // append the bytes to data. _data.append( bytes, len ); if ( _state < p_content ) { parseHeader(); } if ( _state == p_error ) { _status = Error; } else if ( _state == p_content ) { if ( _contentLength == 0 || _data.length() - _contentStart >= _contentLength ) { if ( parseRequestLine() ) { _status = Done; } else { _status = Error; } } } return _status; }
bool CProjectFileParser::parseXMLFile(QFile &f) { loaded = false; QXmlStreamReader reader; reader.setDevice( &f ); reader.readNext(); if( reader.atEnd() ) return false; while( !reader.atEnd() && !( reader.isStartElement() && ( reader.name() == "project" ) ) ) reader.readNext(); if( reader.atEnd() ) return false; while( !reader.atEnd() && !( reader.isStartElement() && ( reader.name() == "header" ) ) ) reader.readNext(); if( reader.atEnd() ) return false; if( !parseHeader( reader ) ) return false; if( !parseGUIFiles( reader ) ) return false; if( !parseMapFiles( reader ) ) return false; loaded = true; return true; }
TheoraVideoStream::TheoraVideoStream(love::filesystem::File *file) : demuxer(file) , headerParsed(false) , decoder(nullptr) , frameReady(false) , lastFrame(0) , nextFrame(0) { if (demuxer.findStream() != OggDemuxer::TYPE_THEORA) throw love::Exception("Invalid video file, video is not theora"); th_info_init(&videoInfo); frontBuffer = new Frame(); backBuffer = new Frame(); try { parseHeader(); } catch (love::Exception &ex) { delete backBuffer; delete frontBuffer; th_info_clear(&videoInfo); throw ex; } frameSync.set(new DeltaSync(), Acquire::NORETAIN); }
void VcfFile::openForRead(const char* filename, int nbuf) { reset(); iFile = ifopen(filename,"rb"); if ( iFile == NULL ) { throw VcfFileException("Failed opening file %s - %s",filename, strerror(errno)); } nBuffers = nbuf; nNumMarkers = 0; nHead = 0; if ( nBuffers == 0 ) { // infinite buffer size // do not set size of markers } else { vpVcfMarkers.resize( nBuffers ); for(int i=0; i < nBuffers; ++i) { VcfMarker* p = new VcfMarker; vpVcfMarkers[i] = p; } } parseMeta(); parseHeader(); if ( bUpgrade ) { upgradeMetaLines(); } }
bool WAVAudioFile::open() { // if already open if (m_inFile && (*m_inFile)) return true; m_inFile = new std::ifstream(m_fileName.toLocal8Bit(), std::ios::in | std::ios::binary); if (!(*m_inFile)) { m_type = UNKNOWN; return false; } // Get the file size and store it for comparison later m_fileSize = m_fileInfo->size(); try { parseHeader(); } catch (BadSoundFileException e) { RG_WARNING << "ERROR: WAVAudioFile::open(): parseHeader: " << e.getMessage(); return false; } return true; }
void EpwData::loadData(const openstudio::path &fn) { // Array was fully initialized in constructor std::ifstream myfile(openstudio::toString(fn).c_str()); if (myfile.is_open()) { size_t i = 0; size_t row = 0; while ( myfile.good() && row < 8760) { i++; std::string line; getline(myfile,line); if(i==1) { parseHeader(line); } else if(i > 8) { parseData(line,row++); } } myfile.close(); } else { throw std::runtime_error("Unable to open weather file: " + openstudio::toString(fn)); } }
int main(int argc, const char* argv[]) { char fileExt[64]; BGFunction* functions; if (argc != 3) { printf("usage: <input file> <output file>\nExample: bind_generator foo.h out.cs"); return 0; } functions = parseHeader(argv[1]); if (!getExt(fileExt, argv[2])) { printf("Unable to find file extension for %s", argv[2]); return -1; } // This is a bit hacky but like this because of extra params handling in tundra. Hopefully // this can be fixed by sending is some proper commandline args instead if (!strcmp(fileExt, ".c")) { if (!generate_exp(argv[2], functions)) return -1; } else if (!strcmp(fileExt, ".cs")) { generate_cs(argv[2], functions); } return 0; }
Loader::Loader(fs::DataFile& datafile, const string& filename) : m_datafile(datafile) { // Load configuration file std::vector<conftree::Node> nodes = conftree::parseMultiDocYAML(datafile, filename); // Sanity checks if(nodes.empty()) throw ResourceException(datafile.name(), filename, "Not a YAML file!"); if(nodes.size() > 2) throw ResourceException(datafile.name(), filename, "Resource file should contain at most two documents!"); if(nodes[0].type() != conftree::Node::MAP) throw ResourceException(datafile.name(), filename, "Resource file should contain a Map!"); if(nodes.size() > 1) { // Header present m_node = nodes[1]; parseHeader(datafile, nodes[0]); } else { // No header m_node = nodes[0]; } }
/** * @brief Parse socket data. * @param [in] s The socket from which to retrieve data. */ void HttpParser::parse(Socket s) { std::string line; line = s.readToDelim(lineTerminator); parseRequestLine(line); line = s.readToDelim(lineTerminator); while(!line.empty()) { m_headers.insert(parseHeader(line)); line = s.readToDelim(lineTerminator); } // Only PUT and POST requests have a body if (getMethod() != "POST" && getMethod() != "PUT") { return; } // We have now parsed up to and including the separator ... we are now at the point where we // want to read the body. There are two stories here. The first is that we know the exact length // of the body or we read until we can't read anymore. if (hasHeader(HttpRequest::HTTP_HEADER_CONTENT_LENGTH)) { std::string val = getHeader(HttpRequest::HTTP_HEADER_CONTENT_LENGTH); int length = std::atoi(val.c_str()); uint8_t data[length]; s.receive_cpp(data, length, true); m_body = std::string((char *)data, length); } else { uint8_t data[512]; int rc = s.receive_cpp(data, sizeof(data)); m_body = std::string((char *)data, rc); } ESP_LOGD(LOG_TAG, "Size of body: %d", m_body.length()); } // parse
MistarParser::MistarParser(string file,string indexForFile,string chrName,int start,int end){ //for rand() ins SingleAllele timeval time; gettimeofday(&time, NULL); srand( long((time.tv_sec * 1000) + (time.tv_usec / 1000)) ); // cout<<file<<endl; // cout<<indexForFile<<endl; // cout<<chrName<<endl; // cout<<start<<endl; // cout<<end<<endl; rt =new ReadTabix (file,indexForFile,chrName,start,end); string headertemp=rt->getHeader(); istringstream is(headertemp); //reading the header numberPopulations=0; populationNames=new vector<string>(); parseHeader(is); if(defline.empty()){ cerr << "Error: MistarParser cannot get definition line" <<endl; exit(1); } numberOfTimesHasDataWasCalled=-1; tabixMode = true; textMode = false; stringMode = false; }
int AppMessageParser::parse( uint8_t octet ) { int r = 0; AppMessage *msg = 0; // Is there room in the header buffer? if ( m_header_buffer.canPut() ) { // yes, try parse the header msg = parseHeader( octet ); } else { // is there octets we are expecting for the payload? if ( m_octets_left_in_payload ) { // yes, parse the payload msg = parsePayload( octet ); } } if ( msg ) { dispatchMsg( *msg ); r = 0; } if ( m_error_count > 0 ) { r = -1; } return r; }
bool BWFAudioFile::open() { // if already open if (m_inFile && (*m_inFile)) return true; m_inFile = new std::ifstream(m_fileName.toLocal8Bit(), std::ios::in | std::ios::binary); if (!(*m_inFile)) { m_type = UNKNOWN; return false; } // Get the file size and store it for comparison later // m_fileSize = m_fileInfo->size(); try { parseHeader(); } catch (BadSoundFileException s) { //throw(s); return false; } return true; }
bool CGarminTyp::decode(QDataStream& in, QMap<quint32, polygon_property>& polygons, QMap<quint32, polyline_property>& polylines, QList<quint32>& drawOrder, QMap<quint32, point_property>& points) { if(!parseHeader(in)) { return false; } if(!parseDrawOrder(in, drawOrder)) { return false; } if(!parsePolygon(in, polygons)) { return false; } if(!parsePolyline(in, polylines)) { return false; } if(!parsePoint(in, points)) { return false; } return true; }
void Lane::setHeaders(header_map headers) { _headers = std::move(headers); for (auto &h : _headers) parseHeader(h.first, h.second.first); }
void cgicc::Cgicc::parseMIME(const std::string& data) { // Find the header std::string end = "\r\n\r\n"; std::string::size_type headLimit = data.find(end, 0); // Detect error if(std::string::npos == headLimit) throw std::runtime_error("Malformed input"); // Extract the value - there is still a trailing CR/LF to be subtracted off std::string::size_type valueStart = headLimit + end.length(); std::string value = data.substr(valueStart, data.length() - valueStart - 2); // Parse the header - pass trailing CR/LF x 2 to parseHeader MultipartHeader head = parseHeader(data.substr(0, valueStart)); if(head.getFilename().empty()) fFormData.push_back(FormEntry(head.getName(), value)); else fFormFiles.push_back(FormFile(head.getName(), head.getFilename(), head.getContentType(), value)); }
void SUROpener::Parser::parseLine(QString line) { removeUselessBlanks(line); if (line.size() == 0) return; if (header(line)) parseHeader(line); else dispatch(line); }
XmlElement* XmlDocument::parseDocumentElement (String::CharPointerType textToParse, const bool onlyReadOuterDocumentElement) { input = textToParse; errorOccurred = false; outOfData = false; needToLoadDTD = true; if (textToParse.isEmpty()) { lastError = "not enough input"; } else if (! parseHeader()) { lastError = "malformed header"; } else if (! parseDTD()) { lastError = "malformed DTD"; } else { lastError.clear(); ScopedPointer<XmlElement> result (readNextElement (! onlyReadOuterDocumentElement)); if (! errorOccurred) return result.release(); } return nullptr; }
/* load XML from token stream */ Ref<XML> parseXML(Ref<Stream<int> > chars, std::string id, bool hasHeader = true, bool hasTail = false) { /* create lexer for XML file */ std::vector<std::string> symbols; symbols.push_back("<!--"); symbols.push_back("-->"); symbols.push_back("<?"); symbols.push_back("?>"); symbols.push_back("</"); symbols.push_back("/>"); symbols.push_back("<"); symbols.push_back(">"); symbols.push_back("="); Ref<Stream<Token> > cin = new TokenStream(chars,TokenStream::alpha + TokenStream::ALPHA + "_" + id, TokenStream::separators, symbols); if (hasHeader) parseHeader(cin); parseComments(cin); Ref<XML> xml = parseXML(cin); parseComments(cin); if (!hasTail) if (cin->peek() != Token::Eof()) THROW_RUNTIME_ERROR(cin->peek().Location().str()+": end of file expected"); return xml; }
String Communication::getUnpackedMessage(String message) { // Check Start of Header if (!checkStartOfHeader(message)) { return ""; } // Parse Header int message_size = parseHeader(message); if (message_size < 0) { return ""; } // Parse Text String unpacked_message = parseText(message); if (unpacked_message == "") { return ""; } // Check Message Size if (message_size != unpacked_message.length()) { return ""; } // Compute & Compare Checksums String incoming_checksum = parseFooter(message); String computed_checksum = getChecksum(unpacked_message); if (incoming_checksum != computed_checksum) { return ""; } // Received Valid Message return unpacked_message; }
bool KPBinaryIface::checkDir(const QString& possibleDir) { bool ret = false; QString possiblePath = path(possibleDir); kDebug() << "Testing " << possiblePath << "..."; QProcess process; process.setProcessChannelMode(QProcess::MergedChannels); process.start(possiblePath, m_binaryArguments); bool val = process.waitForFinished(); if (val && (process.error() != QProcess::FailedToStart)) { m_isFound = true; QString stdOut(process.readAllStandardOutput()); if (parseHeader(stdOut)) { m_pathDir = possibleDir; writeConfig(); kDebug() << "Found " << path() << " version: " << version(); ret = true; } else { // TODO: do something if the version is not right or not found } } emit signalBinaryValid(); return ret; }
void Document::_processBlocksItems(TokenPtr inTokenContainer) { if (!inTokenContainer->isContainer()) return; token::Container *tokens=dynamic_cast<token::Container*>(inTokenContainer.get()); assert(tokens!=0); TokenGroup processed; for (TokenGroup::const_iterator ii=tokens->subTokens().begin(), iie=tokens->subTokens().end(); ii!=iie; ++ii) { if ((*ii)->text()) { optional<TokenPtr> subitem; if (!subitem) subitem=parseHeader(ii, iie); if (!subitem) subitem=parseHorizontalRule(ii, iie); if (!subitem) subitem=parseListBlock(ii, iie); if (!subitem) subitem=parseBlockQuote(ii, iie); if (!subitem) subitem=parseCodeBlock(ii, iie); if (subitem) { _processBlocksItems(*subitem); processed.push_back(*subitem); if (ii==iie) break; continue; } else processed.push_back(*ii); } else if ((*ii)->isContainer()) { _processBlocksItems(*ii); processed.push_back(*ii); } } tokens->swapSubtokens(processed); }
rtError rtHttpResponse::parseHeaders(const rtString& data, std::map<rtString, rtString>& headerMap) { headerMap.clear(); if (data.isEmpty()) return RT_OK; int32_t len = data.length(); int32_t attr1 = 0, attr2; attr2 = data.find(attr1, '\n'); attr2 = -1 != attr2 ? attr2 : (attr1 < len ? len : -1); while (-1 != attr2) { rtString attribute = attr2 == attr1 ? "" : data.substring(attr1, attr2-attr1); rtString key, value; if (parseHeader(attribute, key, value) == RT_OK) { headerMap.insert(std::pair<rtString, rtString>(key, value)); } attr1 = attr2+1; attr2 = data.find(attr1, '\n'); attr2 = -1 != attr2 ? attr2 : (attr1 < len ? len : -1); } return RT_OK; }
bool FDPLoader::parse() { m_bindings.clear(); m_morphTargetsMeshInfos.clear(); m_faceEntityMeshInfo.clear(); // get the header DOMNodeList* nodes = m_pDoc->getElementsByTagName(XercesString("head")); if(!nodes || nodes->getLength() != 1) // sth wrong return false; if(!parseHeader(nodes->item(0)) ) return false; // get the source info nodes = m_pDoc->getElementsByTagName(XercesString("source")); if(!nodes || nodes->getLength() != 1) // sth wrong return false; parseSource(nodes->item(0)); // process fdp's now nodes = m_pDoc->getElementsByTagName(XercesString("fdp")); XMLSize_t sz = nodes->getLength(); for(XMLSize_t i = 0; i < sz; ++i) loadFDPItem(nodes->item(i)); return true; }
int Eiger::doRequest (const request_t *request, response_t *response, int timeout) { const char *functionName = "doRequest"; int status = EXIT_SUCCESS; int received, ret; struct timeval recvTimeout; fd_set fds; mSockMutex.lock(); if(mSockClosed) { if(connect()) { ERR("failed to reconnect socket"); status = EXIT_FAILURE; goto end; } } if(send(mSockFd, request->data, request->actualLen, 0) < 0) { status = EXIT_FAILURE; goto end; } recvTimeout.tv_sec = timeout; recvTimeout.tv_usec = 0; FD_ZERO(&fds); FD_SET(mSockFd, &fds); ret = select(mSockFd+1, &fds, NULL, NULL, &recvTimeout); if(ret <= 0) { ERR(ret ? "select() failed" : "timed out"); status = EXIT_FAILURE; goto end; } if((received = recv(mSockFd, response->data, response->dataLen, 0) < 0)) { status = EXIT_FAILURE; goto end; } response->actualLen = (size_t) received; status = parseHeader(response); if(response->reconnect) { close(mSockFd); mSockClosed = true; } end: mSockMutex.unlock(); return status; }
void ShoutCastIODevice::socketReadyRead(void) { // only read enough data to fill our buffer int available = DecoderIOFactory::DefaultBufferSize - m_buffer->readBufAvail(); QByteArray data = m_socket->read(available); m_bytesDownloaded += data.size(); m_buffer->write(data); // send buffer status event emit bufferStatus(m_buffer->readBufAvail(), DecoderIOFactory::DefaultBufferSize); if (!m_started && m_bytesDownloaded > DecoderIOFactory::DefaultPrebufferSize) { m_socket->setReadBufferSize(DecoderIOFactory::DefaultPrebufferSize); m_started = true; } // if we are waiting for the HEADER and we have enough data process that if (m_state == READING_HEADER) { if (parseHeader()) { if (m_response->getStatus() == 200) { switchToState(PLAYING); m_response_gotten = true; m_bytesTillNextMeta = m_response->getMetaint(); switchToState(STREAMING); } else if (m_response->getStatus() == 302 || m_response->getStatus() == 301) { if (++m_redirects > MAX_REDIRECTS) { LOG(VB_NETWORK, LOG_ERR, QString("Too many redirects")); switchToState(STOPPED); } else { LOG(VB_NETWORK, LOG_INFO, QString("Redirect to %1").arg(m_response->getLocation())); m_socket->close(); QUrl redirectURL(m_response->getLocation()); connectToUrl(redirectURL); return; } } else { LOG(VB_NETWORK, LOG_ERR, QString("Unknown response status %1") .arg(m_response->getStatus())); switchToState(STOPPED); } } } }
CRemoteControlMessage::CRemoteControlMessage(alt_u8* pMessage, int iLength) { parseHeader(pMessage, iLength); if(m_bValid) { m_bValid = false; parseMessage(pMessage+4, iLength-4); }}