Example #1
0
void connection_manager::start(connection_ptr c)
{
	connections_.insert(c);

	boost::system::error_code ec;
	boost::asio::ip::tcp::endpoint endpoint = c->socket().remote_endpoint(ec);
	if (ec) {
		// Prevent the exception to be thrown to run to avoid the server to be locked (still listening but no more connection or stop).
		// If the exception returns to WebServer to also create a exception loop.
		_log.Log(LOG_ERROR,"Getting error '%s' while getting remote_endpoint in connection_manager::start", ec.message().c_str());
		stop(c);
		return;
	}

	std::string s = endpoint.address().to_string();
	if (s.substr(0, 7) == "::ffff:") {
		s = s.substr(7);
	}
	if (connectedips_.find(s) == connectedips_.end())
	{
		//ok, this could get a very long list when running for years
		connectedips_.insert(s);
		_log.Log(LOG_STATUS,"Incoming connection from: %s", s.c_str());
	}

	c->start();
}
Example #2
0
 void send_messages(
     connection_ptr connection
 )
 {
     // Check if sending has been completed....
     if (connection->send())
     {
         error_code ec;
         util::unique_function_nonser<
             void(
                 error_code const&
               , parcelset::locality const&
               , connection_ptr
             )
         > postprocess_handler;
         std::swap(postprocess_handler, connection->postprocess_handler_);
         postprocess_handler(
             ec, connection->destination(), connection);
     }
     else
     {
         std::unique_lock<mutex_type> l(connections_mtx_);
         connections_.push_back(std::move(connection));
     }
 }
Example #3
0
    /// Handler callback for start_accept
    void handle_accept(connection_ptr con, lib::error_code const & ec) {
        if (ec) {
            con->terminate(ec);

            if (ec == error::operation_canceled) {
                endpoint_type::m_elog.write(log::elevel::info,
                    "handle_accept error: "+ec.message());
            } else {
                endpoint_type::m_elog.write(log::elevel::rerror,
                    "handle_accept error: "+ec.message());
            }
        } else {
            con->start();
        }

        lib::error_code start_ec;
        start_accept(start_ec);
        if (start_ec == error::async_accept_not_listening) {
            endpoint_type::m_elog.write(log::elevel::info,
                "Stopping acceptance of new connections because the underlying transport is no longer listening.");
        } else if (start_ec) {
            endpoint_type::m_elog.write(log::elevel::rerror,
                "Restarting async_accept loop failed: "+ec.message());
        }
    }
	void on_close(connection_ptr con) {
		m_con = connection_ptr();
		con->stop_heartbeat();

		con->alog().at(log::alevel::DEVEL)<<"client was disconnected sid "<<  con->m_endpoint.m_strSid <<log::endl;

	}
 void on_open(connection_ptr connection) {
     if (connection->get_resource() == "/admin") {
         connection->set_handler(m_admin_handler);
     } else {
         connection->set_handler(m_broadcast_handler);
     }
 }
Example #6
0
 void validate(connection_ptr con)
 {
   // The key validation step we need to do is on the subprotocols the
   // client requested.  This should include "sip", in which case we'll
   // select "sip" too.  If "sip" was not offered, we offer nothing and the
   // connection will probably fail.
   LOG_DEBUG("Validating incoming web socket connection");
   const std::vector<std::string>& subprotocols = con->get_subprotocols();
   if (std::find(subprotocols.begin(), subprotocols.end(), SUBPROTOCOL) != subprotocols.end())
   {
     LOG_DEBUG("Client requested subprotocol sip - agreeing");
     con->select_subprotocol("sip");
   }
   else
   {
     // Build a comma-separated list of subprotocols ready to log.
     std::stringstream ss;
     std::copy(subprotocols.begin(), subprotocols.end(), std::ostream_iterator<std::string>(ss, ","));
     std::string str = ss.str();
     if (!str.empty())
     {
       // The above added a trailing comma.  Strip it.
       str = str.substr(0, str.length() - 1);
     }
     LOG_INFO("Client requested subprotocols %s - connection will probably fail", str.c_str());
   }
 }
Example #7
0
void chat_server_handler::on_message(connection_ptr con, message_ptr msg) {
    if (msg->get_opcode() != websocketpp::frame::opcode::text) {
        return;
    }
    
    std::cout << "message from client " << con << ": " << msg->get_payload() << std::endl;
    
    
    
    // check for special command messages
    if (msg->get_payload() == "/help") {
        // print command list
        con->send(encode_message("server","avaliable commands:<br />&nbsp;&nbsp;&nbsp;&nbsp;/help - show this help<br />&nbsp;&nbsp;&nbsp;&nbsp;/alias foo - set alias to foo",false));
        return;
    }
    
    if (msg->get_payload().substr(0,7) == "/alias ") {
        std::string response;
        std::string alias;
        
        if (msg->get_payload().size() == 7) {
            response = "you must enter an alias.";
            con->send(encode_message("server",response));
            return;
        } else {
            alias = msg->get_payload().substr(7);
        }
        
        response = m_connections[con] + " is now known as "+alias;

        // store alias pre-escaped so we don't have to do this replacing every time this
        // user sends a message
        
        // escape json characters
        boost::algorithm::replace_all(alias,"\\","\\\\");
        boost::algorithm::replace_all(alias,"\"","\\\"");
        
        // escape html characters
        boost::algorithm::replace_all(alias,"&","&amp;");
        boost::algorithm::replace_all(alias,"<","&lt;");
        boost::algorithm::replace_all(alias,">","&gt;");
        
        m_connections[con] = alias;
        
        // set alias
        send_to_all(serialize_state());
        send_to_all(encode_message("server",response));
        return;
    }
    
    // catch other slash commands
    if ((msg->get_payload())[0] == '/') {
        con->send(encode_message("server","unrecognized command"));
        return;
    }
    
    // create json message to send based on msg
    send_to_all(encode_message(m_connections[con],msg->get_payload()));
}
 void on_message(connection_ptr con, message_ptr msg) {        
     if (con->get_resource() == "/getcasecount") {
         std::cout << "detected " << msg->get_payload() << " test cases." << std::endl;
         m_case_count = atoi(msg->get_payload().c_str());
     } else {
         con->send(msg->get_payload(),msg->get_opcode());
     }
 }
Example #9
0
void RecordServer::remove_connection(connection_ptr conn)
{
	context_ptr context(boost::any_cast<context_ptr>(conn->get_context()));
	//sub_conns_.erase(context->id());
	conn->set_context(context_ptr(nullptr));

	connections_.erase(conn->get_id());
	LOG(INFO)<<__func__<<",conn size"<<connections_.size()<<", connid="<<conn->get_id();
}
	inline void server::handle_accept(const boost::system::error_code& e) {
	    if (!e) {
		new_connection_->start();
		new_connection_.reset(new connection(io_service_, request_handler_));
		acceptor_.async_accept(new_connection_->socket(),
				       boost::bind(&server::handle_accept, this,
						   boost::asio::placeholders::error));
	    }
	}
void socketio_server_handler::validate(connection_ptr con) {
    std::stringstream err;

    // We only know about the chat resource
    if (con->get_resource() != resource_name_) {
        err << "Request for unknown resource " << con->get_resource();
        throw(websocketpp::http::exception(err.str(),websocketpp::http::status_code::NOT_FOUND));
    }

}
Example #12
0
void chat_server_handler::validate(connection_ptr con) {
    std::stringstream err;
    
    // we only know about the chat resource
    if (con->get_resource() != "/chat") {
        err << "request for unknown resource " << con->get_resource();
        throw(websocketpp::http::exception(err.str(),websocketpp::http::status_code::not_found));
    }
    
    // require specific origin example
    if (con->get_origin() != "http://zaphoyd.com") {
        err << "request from unrecognized origin: " << con->get_origin();
        throw(websocketpp::http::exception(err.str(),websocketpp::http::status_code::forbidden));
    }
}
Example #13
0
  void start_listening() {
    using boost::asio::ip::tcp;
    system::error_code error;
    service_.reset();  // this allows repeated cycles of run -> stop ->
                       // run
    tcp::resolver resolver(service_);
    tcp::resolver::query query(address_, port_);
    tcp::resolver::iterator endpoint_iterator = resolver.resolve(query, error);
    if (error) {
      BOOST_NETWORK_MESSAGE("Error resolving '" << address_ << ':' << port_);
      return;
    }
    tcp::endpoint endpoint = *endpoint_iterator;
    acceptor.open(endpoint.protocol(), error);
    if (error) {
      BOOST_NETWORK_MESSAGE("Error opening socket: " << address_ << ":"
                                                     << port_);
      return;
    }
    socket_options_base::acceptor_options(acceptor);
    acceptor.bind(endpoint, error);
    if (error) {
      BOOST_NETWORK_MESSAGE("Error binding socket: " << address_ << ":"
                                                     << port_);
      return;
    }
    acceptor.listen(asio::socket_base::max_connections, error);
    if (error) {
      BOOST_NETWORK_MESSAGE("Error listening on socket: '"
                            << error << "' on " << address_ << ":" << port_);
      return;
    }
    new_connection.reset(new connection(service_, handler, *thread_pool, ctx_));
    acceptor.async_accept(
#ifdef BOOST_NETWORK_ENABLE_HTTPS
        new_connection->socket().next_layer(),
#else
        new_connection->socket(),
#endif
        boost::bind(&async_server_base<Tag, Handler>::handle_accept, this,
                    boost::asio::placeholders::error));
    listening = true;
    scoped_mutex_lock stopping_lock(stopping_mutex_);
    stopping = false;  // if we were in the process of stopping, we revoke
                       // that command and continue listening
    BOOST_NETWORK_MESSAGE("Now listening on socket: '" << address_ << ":"
                                                       << port_ << "'");
  }
Example #14
0
	// handle appelé après lecture
	void handle_read(const boost::system::error_code& e, connection_ptr conn)	{
		if (!e)	{	// lecture des informations
			db::DataBaseType<MySQL> dbMySQL("root", "", "mycloud") ;
			string idMySQL;

			for(model::info i : infos)	{
				idMySQL = dbMySQL.getUser(i.getAddressMail(), i.getPwd());
			}
			if(idMySQL == "1"){
				cout << "Connexion réussi" << endl;

				File file("/home/steven/server/",idMySQL);

				std::string path="/home/steven/server/" + idMySQL + "referencement.xml";
				std::ifstream input(path.c_str());
				std::stringstream data_in;
				data_in << input.rdbuf();
				input.close();

				conn->socket().send(boost::asio::buffer(data_in.str()));
			}else{
				cout << "Connexion échoué" << endl;
			}



		} else {
			std::cerr << e.message() << std::endl;
		}
	}
  /// Handle completion of a accept operation.
  void handle_accept(const asio::error_code& e, connection_ptr conn)
  {
    if (!e)
    {
      // Successfully accepted a new connection. Send the list of stocks to the
      // client. The connection::async_write() function will automatically
      // serialize the data structure for us.
      conn->async_write(stocks_,
          boost::bind(&server::handle_write, this,
            asio::placeholders::error, conn));

      // Start an accept operation for a new connection.
      connection_ptr new_conn(new connection(acceptor_.io_service()));
      acceptor_.async_accept(new_conn->socket(),
          boost::bind(&server::handle_accept, this,
            asio::placeholders::error, new_conn));
    }
    else
    {
      // An error occurred. Log it and return. Since we are not starting a new
      // accept operation the io_service will run out of work to do and the
      // server will exit.
      std::cerr << e.message() << std::endl;
    }
  }
Example #16
0
void http_client::handle_connect(const boost::system::error_code& error, connection_ptr conn, tcp::resolver::iterator resolve_itor)
{
	if(error) {
		std::cerr << "HANDLE_CONNECT_ERROR: " << error << std::endl;
		if(endpoint_iterator_ == resolve_itor) {
			++endpoint_iterator_;
		}
		//ASSERT_LOG(endpoint_iterator_ != tcp::resolver::iterator(), "COULD NOT RESOLVE TBS SERVER: " << resolve_itor->endpoint().address().to_string() << ":" << resolve_itor->endpoint().port());
		if(endpoint_iterator_ == tcp::resolver::iterator()) {
			resolution_state_ = RESOLUTION_NOT_STARTED;
			--in_flight_;
			conn->error_handler("Error establishing connection");
			return;
		}

		async_connect(conn);

		return;
	}
#if defined(_MSC_VER)
	conn->socket.set_option(boost::asio::ip::tcp::no_delay(true));
#endif

	//we've connected okay, mark DNS resolution as good.
	if(resolution_state_ != RESOLUTION_DONE) {
		resolution_state_ = RESOLUTION_DONE;

		//all those connections waiting on DNS resolution can now connect.
		foreach(const connection_ptr conn, connections_waiting_on_dns_) {
			async_connect(conn);
		}
Example #17
0
 /* ===================================================== */   
 void handle_get_name_inv( const connection_ptr& con,  chan_data& cdat, const get_name_inv_message& msg )
 {
     name_inv_message reply;
     reply.name_trxs = _trx_broadcast_mgr.get_inventory( cdat.trxs_mgr );
     cdat.trxs_mgr.update_known( reply.name_trxs );
     con->send( network::message(reply,_chan_id) );
 }
 void handle_get_trx_block( const connection_ptr& c, chan_data& cdat, get_trx_block_message msg )
 { try {
     // TODO: throttle attempts to query blocks by a single connection
     uint32_t blk_num = _db->fetch_block_num( msg.block_id );
     trx_block blk    = _db->fetch_trx_block( blk_num );
     c->send( network::message(trx_block_message( blk ), _chan_id ) );
 } FC_RETHROW_EXCEPTIONS( warn, "", ("msg",msg) ) } // provide stack trace for errors
Example #19
0
 void on_close(connection_ptr con)
 {
     const QString reason = QString::fromStdString(con->get_remote_close_reason());
     pimpl->onClose(reason);
     qDebug() << "Connection Closed";
     m_con = connection_ptr();
 }
Example #20
0
void protobuf_codec::handle_message(connection_ptr& conn) const
{
	loki::buffer* buffer = conn->get_buffer();
	while (buffer->data_size() >= MSG_NAME_LENGTH_SIZE + MIN_MSG_NAME_SIZE + MSG_HEADER_LENGTH)	
	{
		const uint32_t flag = buffer->get<uint32_t>();
		const uint32_t msg_len = flag & 0x0000ffff;
		if (msg_len + MSG_HEADER_LENGTH > buffer->data_size())
		{
			//message not enough, wait
			break;
		}
		if (msg_len > MAX_MSG_LENGTH || msg_len < MSG_NAME_LENGTH_SIZE + MIN_MSG_NAME_SIZE)
		{
			LOG(ERROR)<<"message length error "<<msg_len<<",readable="<<buffer->data_size();
			conn->close();
			break;
		}

		char buff[MAX_MSG_LENGTH];
		size_t len = sizeof(buff);
		LOG(INFO)<<__func__<<", flag="<<flag;
		bool ret = conn->restore_msg((const char*)buffer->data_ptr() + MSG_HEADER_LENGTH, flag, buff, len);
		if (!ret)
		{
			LOG(ERROR)<<"restore msg error";
			conn->close();
			break;
		}

		uint32_t errorcode = 0;
		MessagePtr message = parse(buff, len, errorcode);
		if (errorcode == 0 && message)
		{
			callback_(conn, message);
			buffer->consume(MSG_HEADER_LENGTH + msg_len);
		}
		else
		{
			LOG(ERROR)<<"Parse message error ,errorcode="<<errorcode;
			conn->close();
			break;
		}
	}
}
Example #21
0
 void on_open(connection_ptr connection) {
     if (!m_timer) {
         m_timer.reset(new boost::asio::deadline_timer(connection->get_io_service(),boost::posix_time::seconds(0)));
         m_timer->expires_from_now(boost::posix_time::milliseconds(250));
         m_timer->async_wait(boost::bind(&type::on_timer,this,boost::asio::placeholders::error));
     }
 
     m_connections.insert(connection);
 }
Example #22
0
void chat_server_handler::on_open(connection_ptr con) {
    std::cout << "client " << con << " joined the lobby." << std::endl;
    m_connections.insert(std::pair<connection_ptr,std::string>(con,get_con_id(con)));

    // send user list and signon message to all clients
    send_to_all(serialize_state());
    con->send(encode_message("server","welcome, use the /alias command to set a name, /help for a list of other commands."));
    send_to_all(encode_message("server",m_connections[con]+" has joined the chat."));
}
Example #23
0
    void on_open(connection_ptr con) {
        // now it is safe to use the connection
        std::cout << "connection ready" << std::endl;

        received = false;

        std::string SIP_msg="OPTIONS sip:[email protected] SIP/2.0\r\nVia: SIP/2.0/WS df7jal23ls0d.invalid;rport;branch=z9hG4bKhjhs8ass877\r\nMax-Forwards: 70\r\nTo: <sip:[email protected]>\r\nFrom: Alice <sip:[email protected]>;tag=1928301774\r\nCall-ID: a84b4c76e66710\r\nCSeq: 63104 OPTIONS\r\nContact: <sip:[email protected]>\r\nAccept: application/sdp\r\nContent-Length: 0\r\n\r\n";
        con->send(SIP_msg.c_str());
    }
void server_handler<endpoint>::http(connection_ptr connection) {
    std::stringstream foo;
    
    foo << "<html><body><p>" 
        << m_broadcast_handler->get_connection_count()
        << " current connections.</p></body></html>";
    
    connection->set_body(foo.str());
}
Example #25
0
 /**
  * Sends a close signal to every connection with the specified code and 
  * reason. The default code is 1001/Going Away and the default reason is
  * blank. 
  * 
  * @param code The WebSocket close code to send to remote clients as the
  * reason that the connection is being closed.
  * @param reason The WebSocket close reason to send to remote clients as the
  * text reason that the connection is being closed. Must be valid UTF-8.
  */
 void close_all(close::status::value code = close::status::GOING_AWAY, 
                const std::string& reason = "")
 {
     boost::lock_guard<boost::recursive_mutex> lock(m_lock);
     
     m_alog->at(log::alevel::ENDPOINT) 
     << "Endpoint received signal to close all connections cleanly with code " 
     << code << " and reason " << reason << log::endl;
     
     // TODO: is there a more elegant way to do this? In some code paths 
     // close can call terminate immediately which removes the connection
     // from m_connections, invalidating the iterator.
     typename std::set<connection_ptr>::iterator it;
     
     for (it = m_connections.begin(); it != m_connections.end();) {
         const connection_ptr con = *it++;
         con->close(code,reason);
     }
 }
Example #26
0
          /* ===================================================== 
           *  When a new node connects it must locate the best block chain that extends the
           *  current known chain.  
           **/   
          void request_block_headers( const connection_ptr& con )
          { try {
              ilog( "requesting block headers from ${ep}", ("ep",con->remote_endpoint() ));
              chan_data& cdat = get_channel_data(con);
              if( cdat.requested_headers ) 
                  return;

              get_headers_message  request;
              const std::vector<name_id_type>& ids = _name_db.get_header_ids();
              uint32_t delta = 1;
              for( int32_t i = ids.size() - 1; i >= 0;  )
              {
                 request.locator_hashes.push_back(ids[i]);
                 i -= delta;
                 delta *= 2;
              }
              cdat.requested_headers = fc::time_point::now();
              con->send( network::message(request,_chan_id) );
          } FC_RETHROW_EXCEPTIONS( warn, "") }
Example #27
0
	/// handle appelé après acceptation
	void handle_accept(const boost::system::error_code& e, connection_ptr conn)	{
		if (!e)	{	// acceptation réussie
			// lecture des informations
			conn->async_read(infos, boost::bind(&server::handle_read, this, boost::asio::placeholders::error, conn));
		}
		// démarrage d'une nouvelle connection
		connection_ptr new_conn(new connection(acceptor_.get_io_service()));
		acceptor_.async_accept(new_conn->socket(), boost::bind(&server::handle_accept, this, boost::asio::placeholders::error, new_conn));

	}
Example #28
0
void SceneClientManager::on_sync_error(connection_ptr conn)
{
	SceneClientPtr context = loki::conn_cast<SceneClient>(conn);
	if (!context) return ;
	LOG(INFO)<<__func__<<",id="<<context->id()<<",name="<<context->name()<<",type="<<context->type()<<",ip="<<context->ip()<<",port="<<context->port(); 
	if (conn->is_connected())
		sceneclients_.erase(context->id());
	context->timer_.expires_from_now(boost::posix_time::seconds(5));
	context->timer_.async_wait(boost::bind(&connection::async_connect, conn, context->ip(), context->port()));
}
Example #29
0
bool ConnectService::process(message_ptr const & message, connection_ptr const & connection)
{
	static Engine& engine = Engine::get_instance();
	if (message->type != MessageType::PING) return false;

	uint32_t id;
	_dec_declare2_(req, message->get_content_data(), message->get_content_size());
	_dec_get_var32_(req, id);
	if (!_dec_valid_(req))
	{
		DLOG(ERROR) << "Bad Ping format";
		return true;
	}

	NodeConf* config = (NodeConf*) engine.get_component(COMP_SERVERCONF).get();
	servernode_map::iterator it = config->nodes.find(id);
	if (it != config->nodes.end())
	{
		servernode_ptr node = it->second;
		connection->asyn = true;
		connection->authenticated = true;
		connection->data = node.get();
		connection->type = CT_S2S;
		node->connection = connection;
		node->state = READY;

		_enc_declare_(rep, 64);
		_enc_put_msg_header_(rep, MessageType::REPLY, message->id, 0);
		_enc_put_var32_(rep, ErrorCode::OK);
		_enc_update_msg_size_(rep);
		connection->send(_enc_data_(rep), _enc_size_(rep));
	}
	else
	{
		_enc_declare_(rep, 64);
		_enc_put_msg_header_(rep, MessageType::REPLY, message->id, 0);
		_enc_put_var32_(rep, ErrorCode::IS_NOT_FOUND);
		_enc_update_msg_size_(rep);
		connection->send(_enc_data_(rep), _enc_size_(rep));
	}
	return true;
}
          void handle_get_full_block( const connection_ptr& c, chan_data& cdat, get_full_block_message msg )
          { try {
              // TODO: throttle attempts to query blocks by a single connection
              // this request must hit the DB... cost in proof of work is proportional to age to prevent
              // cache thrashing attacks and allowing us to keep newer blocks in the cache 
              // penalize connections that request too many full blocks...
              uint32_t blk_num = _db->fetch_block_num( msg.block_id );
              full_block blk   = _db->fetch_full_block( blk_num );
              c->send( network::message(full_block_message( blk ), _chan_id ) );

          } FC_RETHROW_EXCEPTIONS( warn, "", ("msg",msg) ) } // provide stack trace for errors