/// <summary>Read the full method from the supplied buffer.</summary> void Method::ReadMethod(IMAGE_COR_ILMETHOD* pMethod) { BYTE* pCode; auto fatImage = static_cast<COR_ILMETHOD_FAT*>(&pMethod->Fat); if (!fatImage->IsFat()) { #ifdef TRACE_ENABLED ATLTRACE(_T("TINY")); #endif auto tinyImage = static_cast<COR_ILMETHOD_TINY*>(&pMethod->Tiny); m_header.CodeSize = tinyImage->GetCodeSize(); pCode = tinyImage->GetCode(); #ifdef TRACE_ENABLED ATLTRACE(_T("TINY(%X) => (%d + 1) : %d"), m_header.CodeSize, m_header.CodeSize, m_header.MaxStack); #endif } else { memcpy(&m_header, pMethod, fatImage->Size * sizeof(DWORD)); pCode = fatImage->GetCode(); #ifdef TRACE_ENABLED ATLTRACE(_T("FAT(%X) => (%d + 12) : %d"), m_header.CodeSize, m_header.CodeSize, m_header.MaxStack); #endif } SetBuffer(pCode); ReadBody(); }
VOID ccBoostWebServerSession::ReadHeaderComplete(CONST boost::system::error_code& e, std::size_t nBytesTransferred) { if (!e) { // 스트림에서 스트링으로 size_t currentSize = m_request_buffer.size(); m_requestHeader.assign( boost::asio::buffers_begin(m_request_buffer.data()), boost::asio::buffers_begin(m_request_buffer.data()) + currentSize ); // 헤더에서 컨텐츠렝쓰를 구한다. std::regex rgxContentLength(".*Content-Length: (\\w+).*"); std::smatch matchContentLength; if (!std::regex_search(m_requestHeader, matchContentLength, rgxContentLength)) { // 컨텐츠렝쓰가 존재하지 않으면 바로 Handle로 이동 Handle(); } else { // 컨텐츠렝쓰가 존재하면 ReadBody로 이동 size_t contentSize = boost::lexical_cast<size_t>(matchContentLength[1]); ReadBody(contentSize); } } else { Disconnect(); } }
bool RINEX_NavigationMessage::_Read(std::ifstream &ifs) { std::string buf; if (ifs == 0) { return false; } else { // Do nothing } if (false == ReadHeader(ifs, leapSecond)) { return false; } else { // Do nothing } if (false == ReadBody(ifs, leapSecond)) { return false; } else { // Do nothing } return true; }
void URLLoaderHandler::OnOpen(int32_t result) { if (result != PP_OK) { ReportResultAndDie(url_, "pp::URLLoader::Open() failed", false); return; } // Here you would process the headers. A real program would want to at least // check the HTTP code and potentially cancel the request. // pp::URLResponseInfo response = loader_.GetResponseInfo(); // Try to figure out how many bytes of data are going to be downloaded in // order to allocate memory for the response body in advance (this will // reduce heap traffic and also the amount of memory allocated). // It is not a problem if this fails, it just means that the // url_response_body_.insert() call in URLLoaderHandler::AppendDataBytes() // will allocate the memory later on. int64_t bytes_received = 0; int64_t total_bytes_to_be_received = 0; if (url_loader_.GetDownloadProgress(&bytes_received, &total_bytes_to_be_received)) { if (total_bytes_to_be_received > 0) { url_response_body_.reserve(total_bytes_to_be_received); } } // We will not use the download progress anymore, so just disable it. url_request_.SetRecordDownloadProgress(false); // Start streaming. ReadBody(); }
bool HTTPBodyResultMapper::DoFinalPutStream(const char *key, std::istream &is, Context &ctx) { StartTrace(HTTPBodyResultMapper.DoFinalPutStream); DAAccessTimer(HTTPBodyResultMapper.DoFinalPutStream, "", ctx); String body; ReadBody(body, is, ctx); Anything anyVal(body); return DoFinalPutAny(key, anyVal, ctx); }
void GetURLHandler::OnOpen(int32_t result) { if (result != PP_OK) { status = STATUS_ERROR; return; } // Here you would process the headers. A real program would want to at least // check the HTTP code and potentially cancel the request. // pp::URLResponseInfo response = loader_.GetResponseInfo(); // Start streaming. ReadBody(); }
void TCPConnection::CallBack_Read_Head(const boost::system::error_code &ec,size_t size) { if ( !ec ) { ReadBody(); } else if ( size == 0 || ec == boost::asio::error::eof || ec == boost::asio::error::shut_down) { Logger::GetLogger()->Debug("Client head Disconnected"); Server::GetInstance()->GetPlayerLogin()->SavePlayerOfflineData(shared_from_this() ); Server::GetInstance()->GetPlayerLogin()->DeleteNameSock(shared_from_this() ); SessionMgr::Instance()->RemoveSession(shared_from_this()); m_read_lock.unlock(); } }
void GetURLHandler::OnRead(int32_t result) { if (result == PP_OK) { // Streaming the file is complete. status = STATUS_COMPLETED; instance_->HandleMessage("package_finished"); instance_->HandleMessage(0); printf("completed!\n"); } else if (result > 0) { // The URLLoader just filled "result" number of bytes into our buffer. // Save them and perform another read. AppendDataBytes(buffer_, result); ReadBody(); } else { // A read error occurred. status = STATUS_ERROR; ERR_FAIL_COND(result < 0); } }
void URLLoaderHandler::OnRead(int32_t result) { if (result == PP_OK) { // Streaming the file is complete, delete the read buffer since it is // no longer needed. delete[] buffer_; buffer_ = NULL; ReportResultAndDie(url_, url_response_body_, true); } else if (result > 0) { // The URLLoader just filled "result" number of bytes into our buffer. // Save them and perform another read. AppendDataBytes(buffer_, result); ReadBody(); } else { // A read error occurred. ReportResultAndDie( url_, "pp::URLLoader::ReadResponseBody() result<0", false); } }
/*---------------------------------------------------------------------- | Test2 +---------------------------------------------------------------------*/ static bool Test2(PLT_TaskManager* task_manager, const char* url, NPT_Size& size) { NPT_LOG_INFO("########### TEST 2 ######################"); /* reset output param first */ size = 0; PLT_RingBufferStreamReference ringbuffer_stream(new PLT_RingBufferStream()); NPT_OutputStreamReference output_stream(ringbuffer_stream); NPT_InputStreamReference input_stream(ringbuffer_stream); PLT_Downloader downloader(task_manager, url, output_stream); downloader.Start(); while (1) { switch(downloader.GetState()) { case PLT_DOWNLOADER_SUCCESS: ringbuffer_stream->SetEos(); /* fallthrough */ case PLT_DOWNLOADER_DOWNLOADING: { NPT_Size bytes_read; NPT_Result res = ReadBody(downloader, input_stream, bytes_read); if (NPT_FAILED(res)) { return (res==NPT_ERROR_EOS)?true:false; } size += bytes_read; } break; case PLT_DOWNLOADER_ERROR: return false; default: NPT_System::Sleep(NPT_TimeInterval(0, 10000)); break; } }; return false; }
/// <summary>Read the full method from the supplied buffer.</summary> void Method::ReadMethod(IMAGE_COR_ILMETHOD* pMethod) { BYTE* pCode; COR_ILMETHOD_FAT* fatImage = (COR_ILMETHOD_FAT*)&pMethod->Fat; if(!fatImage->IsFat()) { ATLTRACE(_T("TINY")); COR_ILMETHOD_TINY* tinyImage = (COR_ILMETHOD_TINY*)&pMethod->Tiny; m_header.CodeSize = tinyImage->GetCodeSize(); pCode = tinyImage->GetCode(); ATLTRACE(_T("TINY(%X) => (%d + 1) : %d"), m_header.CodeSize, m_header.CodeSize, m_header.MaxStack); } else { memcpy(&m_header, pMethod, fatImage->Size * sizeof(DWORD)); pCode = fatImage->GetCode(); ATLTRACE(_T("FAT(%X) => (%d + 12) : %d"), m_header.CodeSize, m_header.CodeSize, m_header.MaxStack); } SetBuffer(pCode); ReadBody(); }
static void InternalCallback(struct mg_connection *connection, const struct mg_request_info *request) { MongooseServer* that = reinterpret_cast<MongooseServer*>(request->user_data); MongooseOutputStream stream(connection); HttpOutput output(stream, that->IsKeepAliveEnabled()); // Check remote calls if (!that->IsRemoteAccessAllowed() && request->remote_ip != LOCALHOST) { output.SendUnauthorized(ORTHANC_REALM); return; } // Extract the HTTP headers IHttpHandler::Arguments headers; for (int i = 0; i < request->num_headers; i++) { std::string name = request->http_headers[i].name; std::transform(name.begin(), name.end(), name.begin(), ::tolower); headers.insert(std::make_pair(name, request->http_headers[i].value)); } // Extract the GET arguments IHttpHandler::GetArguments argumentsGET; if (!strcmp(request->request_method, "GET")) { HttpToolbox::ParseGetArguments(argumentsGET, request->query_string); } // Compute the HTTP method, taking method faking into consideration HttpMethod method = HttpMethod_Get; if (!ExtractMethod(method, request, headers, argumentsGET)) { output.SendStatus(HttpStatus_400_BadRequest); return; } // Authenticate this connection if (that->IsAuthenticationEnabled() && !IsAccessGranted(*that, headers)) { output.SendUnauthorized(ORTHANC_REALM); return; } // Apply the filter, if it is installed const IIncomingHttpRequestFilter *filter = that->GetIncomingHttpRequestFilter(); if (filter != NULL) { std::string username = GetAuthenticatedUsername(headers); char remoteIp[24]; sprintf(remoteIp, "%d.%d.%d.%d", reinterpret_cast<const uint8_t*>(&request->remote_ip) [3], reinterpret_cast<const uint8_t*>(&request->remote_ip) [2], reinterpret_cast<const uint8_t*>(&request->remote_ip) [1], reinterpret_cast<const uint8_t*>(&request->remote_ip) [0]); if (!filter->IsAllowed(method, request->uri, remoteIp, username.c_str())) { output.SendUnauthorized(ORTHANC_REALM); return; } } // Extract the body of the request for PUT and POST // TODO Avoid unneccessary memcopy of the body std::string body; if (method == HttpMethod_Post || method == HttpMethod_Put) { PostDataStatus status; IHttpHandler::Arguments::const_iterator ct = headers.find("content-type"); if (ct == headers.end()) { // No content-type specified. Assume no multi-part content occurs at this point. status = ReadBody(body, connection, headers); } else { std::string contentType = ct->second; if (contentType.size() >= multipartLength && !memcmp(contentType.c_str(), multipart, multipartLength)) { status = ParseMultipartPost(body, connection, headers, contentType, that->GetChunkStore()); } else { status = ReadBody(body, connection, headers); } } switch (status) { case PostDataStatus_NoLength: output.SendStatus(HttpStatus_411_LengthRequired); return; case PostDataStatus_Failure: output.SendStatus(HttpStatus_400_BadRequest); return; case PostDataStatus_Pending: output.SendBody(); return; default: break; } } // Decompose the URI into its components UriComponents uri; try { Toolbox::SplitUriComponents(uri, request->uri); } catch (OrthancException) { output.SendStatus(HttpStatus_400_BadRequest); return; } LOG(INFO) << EnumerationToString(method) << " " << Toolbox::FlattenUri(uri); bool found = false; try { if (that->HasHandler()) { found = that->GetHandler().Handle(output, method, uri, headers, argumentsGET, body.c_str(), body.size()); } } catch (OrthancException& e) { // Using this candidate handler results in an exception LOG(ERROR) << "Exception in the HTTP handler: " << e.What(); try { switch (e.GetErrorCode()) { case ErrorCode_InexistentFile: case ErrorCode_InexistentItem: case ErrorCode_UnknownResource: output.SendStatus(HttpStatus_404_NotFound); break; case ErrorCode_BadRequest: case ErrorCode_UriSyntax: output.SendStatus(HttpStatus_400_BadRequest); break; default: output.SendStatus(HttpStatus_500_InternalServerError); } } catch (OrthancException&) { // An exception here reflects the fact that an exception was // triggered after the status code was sent by the HTTP handler. } return; } catch (boost::bad_lexical_cast&) { LOG(ERROR) << "Exception in the HTTP handler: Bad lexical cast"; output.SendStatus(HttpStatus_400_BadRequest); return; } catch (std::runtime_error&) { LOG(ERROR) << "Exception in the HTTP handler: Presumably a bad JSON request"; output.SendStatus(HttpStatus_400_BadRequest); return; } if (!found) { output.SendStatus(HttpStatus_404_NotFound); } }
static PostDataStatus ParseMultipartPost(std::string &completedFile, struct mg_connection *connection, const IHttpHandler::Arguments& headers, const std::string& contentType, ChunkStore& chunkStore) { std::string boundary = "--" + contentType.substr(multipartLength); std::string postData; PostDataStatus status = ReadBody(postData, connection, headers); if (status != PostDataStatus_Success) { return status; } /*for (IHttpHandler::Arguments::const_iterator i = headers.begin(); i != headers.end(); i++) { std::cout << "Header [" << i->first << "] = " << i->second << "\n"; } printf("CHUNK\n");*/ typedef IHttpHandler::Arguments::const_iterator ArgumentIterator; ArgumentIterator requestedWith = headers.find("x-requested-with"); ArgumentIterator fileName = headers.find("x-file-name"); ArgumentIterator fileSizeStr = headers.find("x-file-size"); if (requestedWith != headers.end() && requestedWith->second != "XMLHttpRequest") { return PostDataStatus_Failure; } size_t fileSize = 0; if (fileSizeStr != headers.end()) { try { fileSize = boost::lexical_cast<size_t>(fileSizeStr->second); } catch (boost::bad_lexical_cast) { return PostDataStatus_Failure; } } typedef boost::find_iterator<std::string::iterator> FindIterator; typedef boost::iterator_range<char*> Range; //chunkStore.Print(); try { FindIterator last; for (FindIterator it = make_find_iterator(postData, boost::first_finder(boundary)); it!=FindIterator(); ++it) { if (last != FindIterator()) { Range part(&last->back(), &it->front()); Range content = boost::find_first(part, "\r\n\r\n"); if (/*content != Range()*/!content.empty()) { Range c(&content.back() + 1, &it->front() - 2); size_t chunkSize = c.size(); if (chunkSize > 0) { const char* chunkData = &c.front(); if (fileName == headers.end()) { // This file is stored in a single chunk completedFile.resize(chunkSize); if (chunkSize > 0) { memcpy(&completedFile[0], chunkData, chunkSize); } return PostDataStatus_Success; } else { return chunkStore.Store(completedFile, chunkData, chunkSize, fileName->second, fileSize); } } } } last = it; } } catch (std::length_error) { return PostDataStatus_Failure; } return PostDataStatus_Pending; }