//////////////////////////////////////////////////////////////////////////////// /// This is the main communication engine. /// /// @IO /// At every timestep, a message is sent to the FPGA via TCP socket /// connection, then a message is retrieved from FPGA via the same /// connection. On the FPGA side, it's the reverse order -- receive and /// then send. Both DGI and FPGA receive functions will block until a /// message arrives, creating a synchronous, lock-step communication between /// DGI and the FPGA. We keep the timestep (a static member of CRtdsAdapter) /// very small so that how frequently send and receive get executed is /// dependent on how fast the FPGA runs. /// /// @Error_Handling /// Throws std::runtime_error if reading from or writing to socket fails. /// /// @pre Connection with FPGA is established. /// /// @post All values in the receive buffer are sent to the FPGA. All values in /// the send buffer are updated with data from the FPGA. /// /// @limitations This function uses synchronous communication. //////////////////////////////////////////////////////////////////////////////// void CRtdsAdapter::Run(const boost::system::error_code & e) { Logger.Trace << __PRETTY_FUNCTION__ << std::endl; if( e ) { if (e == boost::asio::error::operation_aborted) { return; } else { Logger.Fatal << "Run called with error: " << e.message() << std::endl; throw boost::system::system_error(e); } } // Always send data to FPGA first if( !m_txBuffer.empty() ) { boost::unique_lock<boost::shared_mutex> writeLock(m_txMutex); Logger.Debug << "Obtained the txBuffer mutex." << std::endl; EndianSwapIfNeeded(m_txBuffer); try { Logger.Debug << "Blocking for a socket write call." << std::endl; TimedWrite(m_socket, boost::asio::buffer(m_txBuffer, m_txBuffer.size() * sizeof(SignalValue)), CTimings::Get("DEV_SOCKET_TIMEOUT")); } catch(boost::system::system_error & e) { Logger.Fatal << "Send to FPGA failed: " << e.what(); throw; } EndianSwapIfNeeded(m_txBuffer); Logger.Debug << "Releasing the txBuffer mutex." << std::endl; } // Receive data from FPGA next if( !m_rxBuffer.empty() ) { // must be a unique_lock for endian swaps boost::unique_lock<boost::shared_mutex> writeLock(m_rxMutex); Logger.Debug << "Obtained the rxBuffer mutex." << std::endl; try { Logger.Debug << "Blocking for a socket read call." << std::endl; TimedRead(m_socket, boost::asio::buffer(m_rxBuffer, m_rxBuffer.size() * sizeof(SignalValue)), CTimings::Get("DEV_SOCKET_TIMEOUT")); } catch (boost::system::system_error & e) { Logger.Fatal << "Receive from FPGA failed: " << e.what(); throw; } EndianSwapIfNeeded(m_rxBuffer); if( m_buffer_initialized == false ) { m_buffer_initialized = true; for( unsigned int i = 0; i < m_rxBuffer.size(); i++ ) { if( m_rxBuffer[i] == NULL_COMMAND ) { m_buffer_initialized = false; } } if( m_buffer_initialized ) { Logger.Status << "Clientdata : " <<m_rxBuffer[0]<< std::endl; RevealDevices(); } } Logger.Debug << "Releasing the rxBuffer mutex." << std::endl; } // Start the timer; on timeout, this function is called again m_runTimer.expires_from_now( boost::posix_time::milliseconds(CTimings::Get("DEV_RTDS_DELAY"))); m_runTimer.async_wait(boost::bind(&CRtdsAdapter::Run, shared_from_this(), boost::asio::placeholders::error)); }
//executed from io-service thread void Cserial::error(int id, const boost::system::error_code& error) { //dummy ERROR("serial " << id << " had an error:" << error.message()); }
void ProtocolLogin::onError(const boost::system::error_code& error) { callLuaField("onError", error.message(), true); disconnect(); }
void ClientConnection::wrote( const boost::system::error_code& error, size_t bytes_transferred ) { if (error) LOGERROR(LT("Failed to write to "), this->socket->remote_endpoint(), LT(" - transferred "), bytes_transferred, LT(" bytes - "), error.message()); else { LOGTRACE(LT("Succesfully wrote "), this->outbox.front(), LT(" to "), this->socket->remote_endpoint()); boost::lock_guard<boost::mutex> scope_guard(this->outbox_mutex); this->outbox.pop_front(); } if( !this->outbox.empty() ) this->write(); }
void TCPConnection::ReportDebugMessage(const String &message, const boost::system::error_code &error) { String formattedMessage; formattedMessage.Format(_T("%s Remote IP: %s, Session: %d, Code: %d, Message: %s"), message.c_str(), SafeGetIPAddress().c_str(), GetSessionID(), error.value(), String(error.message()).c_str()); LOG_DEBUG(formattedMessage); }
// boost::asio::async_read 回调. void operator()( const boost::system::error_code &ec, int bytes_transferred ) { bool try_http_redirect = false; if( ec && (ec != boost::asio::error::eof )) { m_sender( boost::str( boost::format("@%s, 获取url有错 %s") % m_speaker % ec.message() ) ); return; } m_html_page->append_partial_html(std::string( &(*m_content)[0], bytes_transferred)); // 解析 <title> auto title = (*m_html_page)["title"].to_plain_text(); if (title.empty() && !ec) { m_httpstream->async_read_some(boost::asio::buffer(*m_content, 512), *this); return; }else if (ec == boost::asio::error::eof) { try_http_redirect = true; return; } // 获取charset auto charset = (*m_html_page).charset(); if(!try_http_redirect) { try { if( charset != "utf8" && charset != "utf" && charset != "utf-8" ) { title = boost::locale::conv::between( title, "UTF-8", charset ); } boost::trim( title ); title = html_unescape(title); // 将 &bnp 这种反格式化. m_sender( boost::str( boost::format("@%s ⇪ 标题: %s ") % m_speaker % title ) ); } catch( const std::runtime_error & ) { m_sender( boost::str( boost::format("@%s ⇪ 解码网页发生错误 ") % m_speaker ) ); } } else { // 解析是不是 html 重定向 auto dom_page = (*m_html_page)["meta [http-equiv][content][url]"]; auto cd = dom_page.get_children(); if (!cd.empty()) { auto url = cd[0]->get_attr("url"); if (m_redirect < 10 && !url.empty()) { urlpreview(io_service, m_sender, m_speaker, url, m_redirect + 1); }else { m_sender( boost::str( boost::format("@%s ⇪ url 无标题 ") % m_speaker ) ); } }else { // 还是没有 title ? m_sender( boost::str( boost::format("@%s, 获取url有错 %s") % m_speaker % ec.message() ) ); } } }
void on_disconnected(boost::system::error_code const& ec, uint32_t sock_id) { LogInfo("Client " << sock_id << " disconnected with error: " << ec.message() ); sockets_.erase(sock_id); // peers_.erase(std::find_if(peers_.begin(), peers_.end(), [sock_id](std::pair<id_type, uint32_t> p) { return p.second == sock_id; })); }
void CSapConnection::HandleRead(const boost::system::error_code& err,std::size_t dwTransferred) { SS_XLOG(XLOG_DEBUG,"CSapConnection::%s,id[%d],bytes_transferred[%d]\n",__FUNCTION__,m_nId,dwTransferred); if(!err) { gettimeofday_a(&m_AlivePoint,NULL); buffer_.inc_loc(dwTransferred); while(buffer_.top()>=m_pHeader+sizeof(SSapMsgHeader)) { SSapMsgHeader *ptrHeader=(SSapMsgHeader *)m_pHeader; unsigned int packetlen=ntohl(ptrHeader->dwPacketLen); if(packetlen<=MAX_SAP_PAKET_LEN&&packetlen>0&&(ptrHeader->byIdentifer==SAP_PACKET_REQUEST||ptrHeader->byIdentifer==SAP_PACKET_RESPONSE)) { if(buffer_.top()>=m_pHeader+packetlen) { ReadPacketCompleted(m_pHeader,packetlen); m_pHeader+=packetlen; } else { break; } } else { SS_XLOG(XLOG_WARNING,"CSapConnection::%s,id[%d],packetlen[%d],identifier[%d], will close this socket\n",__FUNCTION__,m_nId,packetlen,ptrHeader->byIdentifer); StopConnection(); return; } } if(m_pHeader!=buffer_.base()) { memmove(buffer_.base(),m_pHeader,buffer_.top()-m_pHeader); buffer_.reset_loc(buffer_.top()-m_pHeader); m_pHeader=buffer_.base(); } else if(buffer_.capacity()==0) { m_pHeader=buffer_.base(); SSapMsgHeader *ptrHeader=(SSapMsgHeader *)m_pHeader; unsigned int packetlen=ntohl(ptrHeader->dwPacketLen); buffer_.add_capacity(SAP_ALIGN(packetlen)); m_pHeader=buffer_.base(); } m_socket.async_read_some(boost::asio::buffer(buffer_.top(),buffer_.capacity()), MakeSapAllocHandler(m_allocReader,boost::bind(&CSapConnection::HandleRead, shared_from_this(), boost::asio::placeholders::error,boost::asio::placeholders::bytes_transferred))); } else { SS_SLOG(XLOG_WARNING,"CSapConnection::"<<__FUNCTION__<<",id["<<m_nId<<"],error:" <<err.message()<<"\n"); StopConnection(); } }
void CSapConnection::HandleWrite(const boost::system::error_code& err) { SS_XLOG(XLOG_DEBUG,"CSapConnection::%s,id[%d]\n",__FUNCTION__,m_nId); SSapMsgHeader *pHeader=NULL; unsigned int dwServiceId=0; unsigned int dwMsgId=0; if(err) { SS_SLOG(XLOG_WARNING,"CSapConnection::"<<__FUNCTION__<<",id["<<m_nId<<"],error:" <<err.message()<<"\n"); while(!m_queue.empty()) { SSapMsgHeader *pHeader=(SSapMsgHeader *)(m_queue.front().pBuffer); unsigned int dwServiceId=ntohl(pHeader->dwServiceId); unsigned int dwMsgId=ntohl(pHeader->dwMsgId); if(!(dwServiceId==0&&dwMsgId==0)) { if(pHeader->byIdentifer==SAP_PACKET_REQUEST && m_pSession!=NULL) { SSapMsgHeader stSendFailResponse; stSendFailResponse.byIdentifer=SAP_PACKET_RESPONSE; stSendFailResponse.byHeadLen=sizeof(SSapMsgHeader); stSendFailResponse.dwPacketLen=htonl(sizeof(SSapMsgHeader)); stSendFailResponse.byVersion=0x1; stSendFailResponse.dwCode=htonl(ERROR_SOS_SEND_FAIL); stSendFailResponse.dwServiceId=pHeader->dwServiceId; stSendFailResponse.dwMsgId=pHeader->dwMsgId; stSendFailResponse.dwSequence=pHeader->dwSequence; m_pSession->OnReceiveSosAvenueResponse(m_nId,&stSendFailResponse,sizeof(stSendFailResponse),m_strRemoteIp,m_dwRemotePort); } free((void *)(m_queue.front().pBuffer)); } m_queue.pop_front(); m_nQueueLen--; } HandleStop(); return; } pHeader=(SSapMsgHeader *)(m_queue.front().pBuffer); dwServiceId=ntohl(pHeader->dwServiceId); dwMsgId=ntohl(pHeader->dwMsgId); if(!(dwServiceId==0&&dwMsgId==0)) { free((void *)(m_queue.front().pBuffer)); } m_queue.pop_front(); m_nQueueLen--; if (!m_queue.empty()) { boost::asio::async_write(m_socket, boost::asio::buffer(m_queue.front().pBuffer,m_queue.front().nLen), MakeSapAllocHandler(m_allocWrite,boost::bind(&CSapConnection::HandleWrite, shared_from_this(), boost::asio::placeholders::error))); } }
void ssl_connection::handle_handshake(const boost::system::error_code& error) { if (!error) connection::start(); else { handler_->log_error(__FILE__, __LINE__, _T("Failed to establish secure connection: ") + to_wstring(error.message())); //ConnectionManager_.stop(shared_from_this()); } }
void Connection::handle_read(const boost::system::error_code& e, std::size_t bytes_transferred) { if (!e) { #ifdef DEBUG_LOGGING BOOST_LOG_TRIVIAL(debug) << "in handle read with no error"; #endif boost::tribool result; result = requestParser->parse(request_.get(), buffer_.data(), bytes_transferred); if (result) { #ifdef DEBUG_LOGGING BOOST_LOG_TRIVIAL(debug) << "in result"; #endif reply_ = Response_ptr(factory->produceResponse()); requestHandler->handleRequest(request_.get(), reply_.get()); std::ostream ostream(&outBuff); reply_->parseIntoOstream(&ostream); #ifdef DEBUG_LOGGING BOOST_LOG_TRIVIAL(debug) << "Sending reply to: " << socket().remote_endpoint().address().to_string() << " size: " << reply_->getSize() << " status: " << reply_->status(); #endif boost::asio::async_write(socket_, outBuff, strand_.wrap( boost::bind(&Connection::handle_write, shared_from_this(), boost::asio::placeholders::error))); } else if (!result) { #ifdef DEBUG_LOGGING BOOST_LOG_TRIVIAL(debug) << "in not result"; #endif #ifdef DEBUG_LOGGING BOOST_LOG_TRIVIAL(debug) << "Result not parsed"; #endif reply_ = Response_ptr(factory->produceResponse()); requestHandler->badRequestResponse(reply_.get()); std::ostream ostream(&outBuff); reply_->parseIntoOstream(&ostream); boost::asio::async_write(socket_, outBuff, strand_.wrap( boost::bind(&Connection::handle_write, shared_from_this(), boost::asio::placeholders::error))); } else { #ifdef DEBUG_LOGGING BOOST_LOG_TRIVIAL(debug) << "in else"; #endif socket_.async_read_some(boost::asio::buffer(buffer_), strand_.wrap( boost::bind(&Connection::handle_read, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred))); } } else { #ifdef DEBUG_LOGGING BOOST_LOG_TRIVIAL(debug) << "Error in handle_read: " << e.message(); #endif } }
//---------------------------------------------------------------------------------- void TNetControlTCP::SendEvent(const boost::system::error_code& error,size_t bytes_transferred) { if(error) GetLogger(STR_NAME_NET_TRANSPORT)-> WriteF_time("SendEvent TCP error=%s.\n",error.message().data()); }
void Acceptor::HandleAccept(int reference, boost::shared_ptr<boost::asio::ip::tcp::socket> socket, const boost::system::error_code& error) { LogDebug("Acceptor::HandleAccept (%p) (id:%u) (new socket %p)", this, m_acceptorId, socket.get()); lua_State* L = LuaNode::GetLuaVM(); lua_rawgeti(L, LUA_REGISTRYINDEX, reference); luaL_unref(L, LUA_REGISTRYINDEX, reference); lua_getfield(L, 1, "callback"); assert(lua_type(L, -1) == LUA_TFUNCTION); //An acceptor must have a callback" if(!error) { // Get the remote endpoint, dealing with the case the connection is already closed when we get here. boost::system::error_code ec; const boost::asio::ip::tcp::endpoint& endpoint = socket->remote_endpoint(ec); if(ec) { if(ec == boost::asio::error::not_connected) { LogWarning("Acceptor::HandleAccept (%p) (id:%u) (new socket %p) - Socket was already closed when accepted. %s", this, m_acceptorId, socket.get(), ec.message().c_str()); } else { LogWarning("Acceptor::HandleAccept (%p) (id:%u) (new socket %p) - Error retrieving remote endpoint. %s", this, m_acceptorId, socket.get(), ec.message().c_str()); } LogInfo("Acceptor::HandleAccept - Retrying accept operation"); lua_settop(L, 1); // leave only 'self' on the stack Accept(L); return; } boost::asio::ip::address address = endpoint.address(); lua_pushnil(L); lua_newtable(L); int peer = lua_gettop(L); lua_pushstring(L, "socket"); Socket* luasocket = new Socket(L, socket); Socket::push(L, luasocket, true); // now Socket is the owner lua_rawset(L, peer); const std::string& sAddress = address.to_string(); lua_pushstring(L, "address"); lua_pushlstring(L, sAddress.c_str(), sAddress.length()); lua_rawset(L, peer); lua_pushstring(L, "port"); lua_pushnumber(L, endpoint.port()); lua_rawset(L, peer); LuaNode::GetLuaVM().call(2, LUA_MULTRET); } else { if(error != boost::asio::error::operation_aborted) { LogError("Acceptor::HandleAccept (%p) (id:%u) (new socket %p) - %s", this, m_acceptorId, socket.get(), error.message().c_str()); } int ret = BoostErrorToCallback(L, error); LuaNode::GetLuaVM().call(ret, LUA_MULTRET); } lua_settop(L, 0); }
void SIPWebSocketConnection::handleRead(const boost::system::error_code& e, std::size_t bytes_transferred, OSS_HANDLE userData) /// Handle completion of a read operation. { if (e || bytes_transferred <=0) { OSS_LOG_DEBUG("SIPWebSocketConnection::handleRead Exception " << e.message()); if (++_readExceptionCount >= 5) { OSS_LOG_ERROR("SIPWebSocketConnection::handleRead has reached maximum exception count. Bailing out."); boost::system::error_code ignored_ec; _connectionManager.stop(shared_from_this()); } } OSS_LOG_DEBUG("SIPWebSocketConnection::handleRead STARTING new connection"); std::string* buffer = reinterpret_cast<std::string*>(userData); // // set the last read address // if (!_lastReadAddress.isValid()) { boost::system::error_code ec; EndPoint ep = _pServerConnection->get_raw_socket().remote_endpoint(ec); if (!ec) { boost::asio::ip::address ip = ep.address(); _lastReadAddress = OSS::Net::IPAddress(ip.to_string(), ep.port()); } else { OSS_LOG_WARNING("SIPWebSocketConnection::handleRead() Exception " << ec.message()); } } // // Reset the read exception count // _readExceptionCount = 0; _bytesRead = bytes_transferred; if (!_pRequest) { _pRequest = SIPMessage::Ptr(new SIPMessage()); } boost::tribool result; const char* begin = buffer->data(); const char* end = buffer->data() + bytes_transferred; boost::tuple<boost::tribool, const char*> ret = _pRequest->consume(begin, end); result = ret.get<0>(); const char* tail = ret.get<1>(); if (result) { // // Message has been read in full // dispatchMessage(_pRequest->shared_from_this(), shared_from_this()); if (tail >= end) { // // The end of the SIPMessage is reached so we can simply reset the // request buffer and start the read operation all over again // _pRequest.reset(); // // We are done // return; } else { // // This should not happen as there is one full message per read. // The tail is within the range of the end of the read buffer. // OSS_ASSERT(false); } } else if (!result) { _pRequest.reset(); } else { // // This should not happen as there is one full message per read. // Partial message? // OSS_ASSERT(false); } }
// Report a failure void fail(boost::system::error_code ec, char const* what) { std::cerr << what << ": " << ec.message() << "\n"; }
void CSapConnection::HandleResolve(const boost::system::error_code& err,tcp::resolver::iterator endpoint_iterator,unsigned int dwLocalPort) { if (!err) { if(dwLocalPort!=0) { boost::system::error_code ec; m_socket.open(tcp::v4(),ec); if(ec) { SS_SLOG(XLOG_WARNING,"CSapConnection::"<<__FUNCTION__<<",id["<<m_nId<<"],open socket error:" <<ec.message()<<"\n"); ConnectFinish(-1); return; } m_socket.set_option(boost::asio::ip::tcp::acceptor::reuse_address(true),ec); m_socket.set_option(boost::asio::ip::tcp::no_delay(true),ec); m_socket.bind(tcp::endpoint(tcp::v4(),dwLocalPort),ec); if(ec) { SS_SLOG(XLOG_WARNING,"CSapConnection::"<<__FUNCTION__<<",id["<<m_nId<<"],bind port error:" <<ec.message()<<"\n"); ConnectFinish(-1); return; } } tcp::endpoint endpoint = *endpoint_iterator; SS_XLOG(XLOG_DEBUG,"CSapConnection::%s,id[%d],addr[%s:%d]\n",__FUNCTION__,m_nId,endpoint.address().to_string() .c_str() ,endpoint.port()); m_socket.async_connect(endpoint, MakeSapAllocHandler(m_allocReader, boost::bind(&CSapConnection::HandleConnected, shared_from_this(), boost::asio::placeholders::error, ++endpoint_iterator))); } else { SS_SLOG(XLOG_WARNING,"CSapConnection::"<<__FUNCTION__<<",id["<<m_nId<<"],error:" <<err.message()<<"\n"); ConnectFinish(-2); } }
static void on_hello_response(const std::string& name, fscp::server& server, const fscp::server::ep_type& sender, const boost::system::error_code& ec, const boost::posix_time::time_duration& duration) { mutex::scoped_lock lock(output_mutex); if (ec) { std::cout << "[" << name << "] Received no HELLO response from " << sender << " after " << duration << ": " << ec.message() << std::endl; } else { std::cout << "[" << name << "] Received HELLO response from " << sender << " after " << duration << ": " << ec.message() << std::endl; server.async_introduce_to(sender, boost::bind(&simple_handler, name, "async_introduce_to()", _1)); std::cout << "[" << name << "] Sending a presentation message to " << sender << std::endl; } }
void CSapConnection::HandleConnected(const boost::system::error_code& err,tcp::resolver::iterator endpoint_iterator) { SS_XLOG(XLOG_DEBUG,"CSapConnection::%s,id[%d]\n",__FUNCTION__,m_nId); if (!err) { gettimeofday_a(&m_HeartBeatPoint,NULL); gettimeofday_a(&m_AlivePoint,NULL); ConnectFinish(0); m_isConnected=true; SetRemoteAddr(); AsyncRead(); } else if (endpoint_iterator != tcp::resolver::iterator()) { boost::system::error_code ignore_ec; m_socket.close(ignore_ec); tcp::endpoint endpoint = *endpoint_iterator; m_socket.async_connect(endpoint, MakeSapAllocHandler(m_allocReader,boost::bind(&CSapConnection::HandleConnected, shared_from_this(), boost::asio::placeholders::error, ++endpoint_iterator))); } else { //SS_SLOG(XLOG_WARNING,"CSapConnection::"<<__FUNCTION__<<",id["<<m_nId<<"],addr[], error:" <<err.message()<<"\n"); SS_XLOG(XLOG_WARNING,"CSapConnection::%s, id[%d], error:%s\n", __FUNCTION__,m_nId,(err.message()).c_str()); ConnectFinish(-3); } }
void LocalForwarder::getHeadersHandle(const boost::system::error_code& e) { if (e) { LOG_ACPROXY_ERROR("get http request header error ", e.message()); //conn_->close(); return; } LOG_ACPROXY_INFO("start reading http request headers..."); char buf[1024]; // XXX auto fd = socket_->native_handle(); ssize_t sz = ::recv(fd, buf, sizeof(buf), MSG_PEEK); LOG_ACPROXY_DEBUG("sz of read http request header = ", sz); if (sz < 0) { const int err = errno; if (err == EAGAIN || err == EWOULDBLOCK) { LOG_ACPROXY_INFO("read http request header again..."); getHeaders(); return; } LOG_ACPROXY_INFO("read http request header error"); //conn_->close(); return; } else if (sz == 0) { LOG_ACPROXY_INFO("client close socket"); //conn_->close(); return; } const char* pos = (const char*)::memmem(buf, sz, "\r\n\r\n", 4); bool found = pos; ssize_t diff = (found ? pos - buf + 4 : sz); if (!found) { // \r | \n\r\n if (headers.size() >= 1 && headers.back() == '\r' && sz >= 3 && buf[0] == '\n' && buf[1] == '\r' && buf[2] == '\n') { found = true; diff = 3; } // \r\n | \r\n if (headers.size() >= 2 && headers[headers.size() - 2] == '\r' && headers[headers.size() - 1] == '\n' && sz >= 2 && buf[0] == '\r' && buf[1] == '\n') { found = true; diff = 2; } // \r\n\r | \n if (headers.size() >= 3 && headers[headers.size() - 3] == '\r' && headers[headers.size() - 2] == '\n' && headers[headers.size() - 1] == '\r' && sz >= 1 && buf[0] == '\n') { found = true; diff = 1; } } // consume ::recv(fd, buf, diff, 0); headers.insert(headers.end(), buf, buf + diff); if (found) { Http::RequestHeaderGrammar<decltype(headers)::iterator> grammar; bool res = phrase_parse(headers.begin(), headers.end(), grammar, boost::spirit::qi::ascii::blank, request_); if (!res) { LOG_ACPROXY_ERROR("parse http request header error"); //conn_->close(); return; } request_.rewrite(); request_.setKeepAlive(false); // cache layer if (request_.method == "GET" || request_.method == "HEAD") { std::string key = keygen(request_.getHost(), request_.getPort(), request_.uri, request_.method); auto& cache = getGlobalCache(); if (boost::optional<std::string> resp = cache.get(key)) { LOG_ACPROXY_INFO("hit, found in cache!"); finish(resp.value()); return; } if (auto c = conn_.lock()) { c->getRemoteForwarder()->setCacheKey(key); } else { LOG_ACPROXY_WARNING("connection object is freed"); return; } } // LOG_ACPROXY_DEBUG("request = \n", request_.toBuffer()); if (!request_.hasResponseBody()) { if (auto c = conn_.lock()) { c->getRemoteForwarder()->setResponseBody(false); } else { LOG_ACPROXY_WARNING("connection object is freed"); return; } } std::string host = request_.getHost(); int port = request_.getPort(); if (auto c = conn_.lock()) { res = c->getRemoteForwarder()->connect(host, port); } else { LOG_ACPROXY_WARNING("connection object is freed"); return; } if (!res) { if (auto c = conn_.lock()) { c->report("failure", {{"host", boost::asio::ip::host_name()}}, std::time(0)); } // XXX Maybe shutdowning socket is better LOG_ACPROXY_INFO("connection timeout, close it"); //send("HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n"); //conn_->close(); return; } LOG_ACPROXY_DEBUG("connection complete"); if (!request_.isConnectMethod()) { // forward header to server if (auto c = conn_.lock()) { c->getRemoteForwarder()->send(request_.toBuffer()); } else { LOG_ACPROXY_WARNING("connection object is freed"); return; } } else { // no parse response header, get rawdata and forward instead if (auto c = conn_.lock()) { c->getRemoteForwarder()->setParseResponseHeader(false); } else { LOG_ACPROXY_WARNING("connection object is freed"); return; } // send a fake 200 response in tunnel mode send("HTTP/1.1 200 Connection Established\r\n\r\n"); } if (request_.hasContentBody()) { getBody(); } } else { // request header is incomplete, read again LOG_ACPROXY_INFO("http request header incomplete, read again"); getHeaders(); } if (auto c = conn_.lock()) { c->update(); } else { LOG_ACPROXY_WARNING("connection object is freed"); return; } }
static void event_callback(void* data, std::shared_ptr<socket_info> tcp_socket, curl_socket_t curl_socket, CURL* curl, int action, const boost::system::error_code &err) { asyn_http_object* aho = (asyn_http_object*)data; if (err) { log_wrap::net().e("function : ", __FUNCTION__, ", socket : ", curl_socket, ", action : ", action, " error : ", err.message()); CURLMcode code = curl_multi_socket_action(aho->curlm, tcp_socket->socket.native_handle(), CURL_CSELECT_ERR, &aho->still_running); } else { CURLMcode code = curl_multi_socket_action(aho->curlm, tcp_socket->socket.native_handle(), action, &aho->still_running); } check_multi_curl(data); if (aho->still_running <= 0) { timer.cancel(); } else { int action_continue = (tcp_socket->mask) & action; if (action_continue) { set_socket(tcp_socket, curl_socket, curl, action_continue, data); } } }
void on_error(boost::system::error_code const& ec, uint32_t sock_id) { LogError("TCP error: " << ec.message()); sockets_.erase(sock_id); // peers_.erase(std::find_if(peers_.begin(), peers_.end(), [sock_id](std::pair<id_type, uint32_t> p) { return p.second == sock_id; })); }
void MergeDispatcher::handle_buffer( boost::system::error_code const & ec) { LOG_DEBUG("[handle_buffer] ec:"<<ec.message()); response(ec); }
void TCPConnection::HandshakeFailed_(const boost::system::error_code& error) { // The SSL handshake failed. This may happen for example if the user who has connected // to the TCP/IP port disconnects immediately without sending any data. String sMessage; sMessage.Format(_T("TCPConnection - TLS/SSL handshake failed. Session Id: %d, Remote IP: %s, Error code: %d, Message: %s"), session_id_, SafeGetIPAddress().c_str(), error.value(), String(error.message()).c_str()); LOG_TCPIP(sMessage); OnHandshakeFailed(); }
void onErrorServerHandle(IServer *server, const boost::system::error_code& error) { long serverId = server->getId(); NetLib::instance().destroyServer(serverId); sLog.outError("server error serverId:%ld error:%s \n", serverId, error.message().c_str()); }
void WebSocket::_async_read( usr_ptr u, char* request, const boost::system::error_code& error, size_t bytes_transferred ) { if( !error ) { if( u->handshaken ) { // bitch has handshaken. Lets process him :) size_t start = 0; size_t offset = 0; while( offset < bytes_transferred ) offset += u->ftype->unpackFrame( (unsigned char*)(request + offset), bytes_transferred - offset ); if( u->ftype->disconnect( ) ) { log( "Request from client " + itoa( u->uid ) + " to disconnect" ); _disconnect( u ); delete[ ] request; return; } else { std::string response; std::string req = u->ftype->data( ); size_t b; switch( _processable->process( req, response ) ) { case RESPOND: unsigned char* frame; b = u->ftype->packFrame( response, frame, false ); _async_send( u, std::string( (char*)frame, b ) ); delete[ ] frame; break; case BROADCAST: _async_broadcast( response ); break; default: break; } } // std::cout << "Frames in request: " << framecount << std::endl; } else {// lets shake hands, mr client log( "Handshaking with client " + itoa( u->uid ) ); _handshake( u, std::string( request, bytes_transferred ) ); } // request = new char[ _maxBytes ]; u->sock->async_receive( boost::asio::buffer( request, _maxBytes ), boost::bind( &WebSocket::_async_read, this, u, request, _1, _2 ) ); } else if( error == boost::asio::error::eof ) { delete[ ] request; log( "Client " + itoa( u->uid ) + " closed the connection (eof)." ); // u->sock->close( ); _disconnect( u ); } else { delete[ ] request; log( "Error: " + error.message( ) ); } }
void onErrorClientHandle(IClient *client, const boost::system::error_code& error) { long clientId = client->getId(); NetLib::instance().destroyClient(clientId); sLog.outError("client error clientId:%ld error:%s \n", clientId, error.message().c_str()); }
void c_tun_device_apple::handle_read(const boost::system::error_code &error, size_t length) { if (error || (length < 1)) throw std::runtime_error("TUN read error, length = " + std::to_string(length) + " error message: " + error.message()); m_readed_bytes = length; // continue reading m_stream_handle_ptr->async_read_some(boost::asio::buffer(m_buffer), [this](const boost::system::error_code &error, size_t length) { handle_read(error, length); }); // lambda }
void ServerNetworkComm::callback_read( TCPConnection::Ptr conn, const boost::system::error_code & error ) { if( !error ) { std::string error_msg; ClientInfo& info = m_clients[conn]; SignalFrame & buffer = info.buffer; std::string target = buffer.node.attribute_value( "target" ); std::string receiver = buffer.node.attribute_value( "receiver" ); std::string clientid = buffer.node.attribute_value( "clientid" ); std::string frameid = buffer.node.attribute_value( "frameid" ); // check if the client is attempting to register if( target == "client_registration" ) { if( !info.uuid.empty() ) error_msg = "This client has already been registered."; else { info.uuid = clientid; // Build and send the reply SignalFrame reply = buffer.create_reply(); SignalOptions & roptions = reply.options(); roptions.add("accepted", true); roptions.flush(); this->init_send(conn, buffer ); // tell listeners a new client has arrived SignalFrame frame("new_client_connected", "cpath:/", "cpath:/"); frame.options().add( "clientid", clientid ); call_signal( "new_client_connected", frame ); } } else { if( info.uuid.empty() ) error_msg = "The signal came from an unregistered client."; else if( info.uuid != clientid ) error_msg = "The client id '" + info.uuid + "' (used for registration) " + "and '" + clientid + "' (used for identification) do not match."; else ServerRoot::instance().process_signal(target, receiver, clientid, frameid, buffer); } if( !error_msg.empty() ) this->send_frame_rejected( conn, frameid, SERVER_CORE_PATH, error_msg ); init_read( info ); } else if( error != boost::asio::error::eof ) CFerror << "Could not read from [" << conn->socket().remote_endpoint() << "]: " << error.message() << CFendl; if( error ) { std::string uuid = m_clients[conn].uuid; conn->disconnect(); m_clients.erase( conn ); if( error == boost::asio::error::eof ) CFinfo << "Cliemt [" << uuid << "] has disconnected. (" << m_clients.size() << " left)." << CFendl; } }
//------------------------------------------------------------- // void NetServer::onErrorHandle(ISessionPtr session, const boost::system::error_code& error) { uint64 sessionId = session->getId(); this->closeSession(sessionId); sLog.outError("session error session:%lld server:%lld error:%s \n", sessionId, this->m_nId, error.message().c_str()); }
static void sended( const boost::system::error_code & ec ) { std::cout << ec.message() << std::endl; }