void
    vita_iq_source_2_impl::handle_read(const boost::system::error_code& error,
                                 size_t bytes_transferred)
    {

      GR_LOG_WARN(d_logger, "handle_read.");
      if(!error) {
        {
          boost::lock_guard<gr::thread::mutex> lock(d_udp_mutex);
          // Make sure we never go beyond the boundary of the
          // residual buffer.  This will just drop the last bit of
          // data in the buffer if we've run out of room.
          if((int)(d_residual + bytes_transferred) >= (50*d_packetSize)) {
            char msg[100];
            sprintf(msg,"d_packetSize %d bytes_transferred %d",
                (int)d_packetSize, (int)bytes_transferred);
            GR_LOG_WARN(d_logger, msg);
            GR_LOG_WARN(d_logger, "TOO much data; dropping packet.");
          }
          else {
            // otherwise, copy received data into local buffer for
            // copying later.
            memcpy(d_residbuf+d_residual, d_rxbuf, bytes_transferred);
            d_residual += bytes_transferred;
          }
          d_cond_wait.notify_one();
        }
      }
      start_receive();
    }
Beispiel #2
0
void	Server::CallBack_handle_receive(boost::system::error_code const & error, std::size_t recv_count)
{
  if (!error || error == boost::asio::error::message_size)
    {
      ////////// THREAD SAFE//////////////////////
      // !!! to implement !!!
      // this lock should have a very high priority for locking
      // the main receiver thread shouldn t be waiting for all thread workers finishing to treat
      // packets
      ///////////////////////////////////////////////////////
      // MOVED THE LOCK INSIDE CLASS: ADD INT PARAMETER FOR LOCKING PRIORITY

      try {
	Packet * p = reinterpret_cast<Packet *>(_serverManager->Cond_new_Packet(*_remote_endpoint, *_recv_buffer, recv_count));
	_packetQueue->PushPacket(p);
	_pool->schedule(boost::bind(&Server::Thread_TreatPacket, this));
      }
      catch (std::runtime_error &e)
	{
	  std::cerr << e.what() << ":" << Packet_v1::peekComponentId(*_recv_buffer) << std::endl;
	  delete _recv_buffer;
	  _recv_buffer = 0;
	}
	start_receive();
      ////////////////////////////////////////////
    }
}
Beispiel #3
0
static inline void adapter_reset(struct net_device *dev)
{
	unsigned long timeout;
	elp_device *adapter = dev->priv;
	unsigned char orig_hcr = adapter->hcr_val;

	outb_control(0, dev);

	if (inb_status(dev->base_addr) & ACRF) {
		do {
			inb_command(dev->base_addr);
			timeout = jiffies + 2*HZ/100;
			while (time_before_eq(jiffies, timeout) && !(inb_status(dev->base_addr) & ACRF));
		} while (inb_status(dev->base_addr) & ACRF);
		set_hsf(dev, HSF_PCB_NAK);
	}
	outb_control(adapter->hcr_val | ATTN | DIR, dev);
	mdelay(10);
	outb_control(adapter->hcr_val & ~ATTN, dev);
	mdelay(10);
	outb_control(adapter->hcr_val | FLSH, dev);
	mdelay(10);
	outb_control(adapter->hcr_val & ~FLSH, dev);
	mdelay(10);

	outb_control(orig_hcr, dev);
	if (!start_receive(dev, &adapter->tx_pcb))
		printk(KERN_ERR "%s: start receive command failed \n", dev->name);
}
Beispiel #4
0
        void UdpOnce::handle_receive(const boost::system::error_code& error,
                std::size_t bytes_transferred) {
            if (socket_.get_io_service().stopped())
                return;

            if (!error || error == boost::asio::error::message_size) {
                UdpReceiveOtherServer reciver = *((UdpReceiveOtherServer*) recv_buffer_);
                BOOST_LOG_TRIVIAL(debug) << "handle_receive Udp Once, fileSize=" << reciver.freeSpace;

                {
                    //critial section
                    boost::lock_guard<boost::recursive_mutex> lock(m_guard);
                    std::string ip = this->remote_endpoint_.address().to_string();
                    //std::string localIp = listenAddress.address().to_string();
                    BOOST_LOG_TRIVIAL(debug) << "critical section;ip=" << ip;

                    //if (ip != localIp) {
                        ServersResponce responce = ServersResponce(ip, reciver.freeSpace);
                        this->servers_.push_back(responce);
                    //}
                }


                start_receive();
            }
        }
void UdpServer::handle_receive(const boost::system::error_code& error, std::size_t bytes_transferred)
{
    if (!error)
    {
      try{
		  qDebug()<<"packet size is: " << bytes_transferred;
        //meta.size_ = bytes_transferred;
        //vbuffer_->Enqueue(meta);
      }
      catch(std::exception ex) {
        std::cout << "handle_receive: Error parsing incoming message:" << ex.what() <<std::endl;
      }
      catch (...) {
        std::cout << "handle_receive: Unknown error while parsing incoming message"<<std::endl;
        };

    }
    else
    {
       std::cout << "handle_receive: error: " << error.message() <<std::endl;
    }
    
    
    start_receive();
}
Beispiel #6
0
void NetworkManager::handle_receive(const boost::system::error_code& error, std::size_t bytes_transferred){
	if (!error)
	{
	   	ClientMessage message = ClientMessage(std::string(recv_buffer.data(), recv_buffer.data() + bytes_transferred),  get_client_id(remote_endpoint));
		if (!message.first.empty())
		{
			boost::mutex::scoped_lock lock(mutex);
			messages.push(message);
			if(timeLeft.find(message.second) != timeLeft.end())
				timeLeft[message.second] = (int) clock();
			else
				timeLeft[nextClientID + 1] = (int) clock();
			cout << message.first <<"\n";
		}
		else
		{
			cout << "empty message\n";
		}
	    receivedBytes += bytes_transferred;
	    receivedMessages++;
	}
	else
	{
		cout << "error!" <<"\n";
	}

	start_receive();
}
Beispiel #7
0
    void handle_receive(const boost::system::error_code& error, std::size_t recv_len){
        if (!error || error == boost::asio::error::message_size){

            if(recv_len > 5){

                int sequenceId = *((int32_t*) &recv_arr[0]);
                if(sequenceId == 0){
                    std::cout << "Reader placed\n";
                    audiobuf->readerIndex = BUFFER_SIZE-1;
                    //synchronized = true;
                }else{
                    if(sequenceId != audiobuf->lastSequenceId+1){
                        std::cout << "Packet loss/displacement\n";
                    }
                }
                audiobuf->lastSequenceId = sequenceId;
                int audioLen = recv_len-4;
                int writerIndex = sequenceId % BUFFER_SIZE;
                if(writerIndex == audiobuf->readerIndex){
                    audiobuf->readerIndex = (BUFFER_SIZE+writerIndex-1)%BUFFER_SIZE;
                    std::cout << "Synchronizing\n";
                }

                audiobuf->length[writerIndex] = audioLen;
                unsigned char* audio = &recv_arr[4];
                memcpy(audiobuf->buffer[writerIndex], audio, audioLen);

                //std::cout << "recv_len: " << recv_len << "\n";


                //std::cout <<  opus_packet_get_nb_samples(audio, recv_len, SAMPLE_RATE) << "\n";

                /*
                for(int i = 0; i<BUFFER_SIZE; i++){

                    if(sequenceId % BUFFER_SIZE == i){
                        std::cout << "+";
                    }else if(audiobuf->readerIndex == i){
                        std::cout << "-";
                    }else if(audiobuf->length[i] != 0){
                        std::cout << "=";
                    }else{
                        std::cout << " ";
                    }


                }
                std::cout << "\n";*/

                //std::cout << sequenceId << "\n";*/
                std::cout.flush();
            }
            /**/
            start_receive();
        }else{
            std::cout << error.message() << "\n";
        }

    }
Beispiel #8
0
/* Check to see if the receiver needs restarting, and kick it if so */
static inline void prime_rx(struct net_device *dev)
{
	elp_device *adapter = dev->priv;
	while (adapter->rx_active < ELP_RX_PCBS && netif_running(dev)) {
		if (!start_receive(dev, &adapter->itx_pcb))
			break;
	}
}
Beispiel #9
0
UdpServer::UdpServer(asio::io_service& io_service, int type, int port) : socket_(io_service, udp::endpoint(udp::v4(), port))
{
	this->type = type;
	this->port = port;

	start_receive();
	debug->notification(1, type, "Created UDP Socket (listening on port %i)", port);
}
Beispiel #10
0
void		Server::Run()
{
  std::cerr << "* ";
  Time::Print();
  std::cerr << " Server started..." << std::endl;
  
  start_receive();
  _io_service->run();
}
Beispiel #11
0
 UdpBroatcast::UdpBroatcast(boost::asio::io_service& io_service,
         udp::endpoint& listenAddress) :
 socket_(io_service, listenAddress) {
     socket_.set_option(boost::asio::ip::udp::socket::reuse_address(true));
     boost::asio::socket_base::broadcast option(true);
     socket_.set_option(option);
     recv_buffer_ = new char[sizeof (UdpBroatcastRecive)];
     start_receive();
 }
Beispiel #12
0
void SerialConnection::service_io_thread(void) {
	///asio::read(*port_, asio::buffer(response_adu));

	recv_raw_data_.clear();
	start_receive();

	while (true) {
		io_.run();
	}
}
Beispiel #13
0
void NLSocket::start_receive()
{
    socket_.async_receive_from
        (asio::buffer(recv_buffer_), remote_endpoint_,
         [this](const std::error_code &error, std::size_t bytes_xferred)
         {
             process_receive(bytes_xferred, 0, 0);
             start_receive();
         });
}
Beispiel #14
0
void UdpServer::handle_receive(const system::error_code& error, size_t bytes_transferred)
{
	if(!error && bytes_transferred > 0)
	{
		ProcessData(DataToPacket(bytes_transferred));
		socket_.async_send_to(asio::buffer(send_data, send_data.size()), remote_endpoint_,
								boost::bind(&UdpServer::handle_send, this, asio::placeholders::error, asio::placeholders::bytes_transferred));
		start_receive();
	}
}
Beispiel #15
0
        void UdpBroatcast::handle_receive(const boost::system::error_code& error,
                std::size_t bytes_transferred) {
            BOOST_LOG_TRIVIAL(debug) << "broat cast recive";
            if (!error || error == boost::asio::error::message_size) {
                UdpBroatcastRecive reciver = *((UdpBroatcastRecive*) recv_buffer_); //hack преобразование из байтов в стурктуру
                sendFreeSpaceRequest(reciver);

                start_receive();
            }
        }
Beispiel #16
0
void c_UDPasync::handle_receive (const boost::system::error_code &error, std::size_t bytes_transferred) {
	if (!error) {
		std::string message(recv_buffer.data(), recv_buffer.data() + bytes_transferred);
		incomingMessages.push(message);
		statistics.register_received_message(bytes_transferred);
	} else {
		Log::Error("c_UDPasync::handle_receive:", error);
	}

	start_receive();
}
Beispiel #17
0
void Receiver::handle_receive_from(const boost::system::error_code& err,
    size_t bytes_recvd)
{
    // Send the raw data to the handler
    if (!err && bytes_recvd > 0) {
        m_handler(m_data);
    }

    // Start new accept
    start_receive();
}
Beispiel #18
0
void c_UDPasync::run_service () {
	start_receive();
	while (!io_service.stopped()) {
		try {
			io_service.run();
		} catch (const std::exception &e) {
			Log::Warning("Client: network exception: ", e.what());
		} catch (...) {
			Log::Error("Unknown exception in client network thread");
		}
	}
}
Beispiel #19
0
void server::handle_receive(const boost::system::error_code& error, std::size_t bytes_recvd)
{
  //std::cout << boost::this_thread::get_id() << ": ";

  // Is error
  if (error || bytes_recvd == 0)
  {
    std::cout << "Unknown error" << std::endl;
    return start_receive();
  }

  // Data is not netflow version 5
  if (packet.hdr.get_version() != 5)
  {
    std::cout << "Error: received unknwon packet version" << std::endl;    
    return start_receive();
  }

  // Push packet
  packets.push_front(packet);

  start_receive();
}
Beispiel #20
0
void NetworkManager::run_service()
{
    start_receive();
    while (!io_service.stopped()){
        try {
            io_service.run();
        } catch( const std::exception& e ) {
            //LogMessage::error("NetworkManager network exception: ",e.what());
        }
        catch(...) {
            //LogMessage::error("Unknown exception in server network thread");
        }
    }
    //LogMessage::Debug("NetworkManager network thread stopped");
};
Beispiel #21
0
NLSocket::NLSocket(asio::io_service &io_service)
: socket_(io_service), nlseq_(g_random_prng())
{
    initialized_ = false;
    socket_.open(nl_protocol(NETLINK_ROUTE));
    socket_.bind(nl_endpoint<nl_protocol>(RTMGRP_LINK));
    socket_.non_blocking(true);

    request_links();
    request_addrs();
    initialized_ = true;

    // Begin the main asynchronous receive loop.
    start_receive();
}
void UdpServer::run_service()
{
    start_receive();
    while (!io_service.stopped()){
        try {
            io_service.run();
        } catch( const std::exception& e ) {
            std::cout << "Server network exception: " << e.what() <<std::endl;
        }
        catch(...) {
          std::cout << "Unknown exception in server network thread" << std::endl;
        }
    }
    std::cout << "Server network thread stopped" << std::endl;
};
Beispiel #23
0
    sAudioReceiver(boost::asio::io_service& io_service, sAudioBuffer* audiobuf, char* host, int port) : audiobuf(audiobuf), socket(io_service), ping_interval(boost::posix_time::seconds(1)) {
        printf("Creating sAudioReceiver on %s:%d\n", host, port);
        socket.open(boost::asio::ip::udp::v4());

        receiver_endpoint = boost::asio::ip::udp::endpoint(boost::asio::ip::address::from_string(host), port);


        std::string thx("ihazo");
        std::copy(thx.begin(), thx.end(), send_arr.begin());
        printf("Created sAudioReceiver\n");
        send_request();
        start_receive();
        printf("Sent request\n");

        ping_timer = new boost::asio::deadline_timer(socket.get_io_service(), ping_interval);
        start_timer();
    }
Beispiel #24
0
void EventLogger::bind(const std::string &addr)
{
    // We have to make sure our bind happens within the context of the main thread.
    assert(std::this_thread::get_id() == g_main_thread_id);

    m_log.info() << "Opening UDP socket..." << std::endl;
    auto addresses = resolve_address(addr, 7197, g_loop);

    if(addresses.size() == 0) {
        m_log.fatal() << "Failed to bind to EventLogger address " << addr << "\n";
        exit(1);
    }

    m_local = addresses.front();

    m_socket = g_loop->resource<uvw::UDPHandle>();
    m_socket->bind(m_local);
    start_receive();
}
Beispiel #25
0
void Server::handle_receive(const boost::system::error_code& error,
		std::size_t read_size/*bytes_transferred*/) {
#ifdef DEBUG
	std::cout << "received a message on port "
			  << socket_.local_endpoint().port()
			  << " (" << read_size << " bytes)"
			  << std::endl;
#endif /* DEBUG */
	recv_buffer_.resize(read_size);

	if (error)
		throw boost::system::system_error(error);
	// parse the frame and determine what to do with it
	Dispatcher::dispatch(socket_.local_endpoint().port(), recv_buffer_, socket_);

	recv_buffer_.resize(UDP_MAX_FRAME_SIZE);

	start_receive(); /* make oneself ready for the next packet */
}
Beispiel #26
0
server::server(const std::string& address, std::size_t port, std::size_t thread_cnt, std::size_t buffer_size, std::size_t update_int)
  :  socket(io_service, boost::asio::ip::udp::endpoint(boost::asio::ip::address::from_string(address), port)),
     zone_timer(io_service, boost::posix_time::seconds(update_int)),
     abonent_timer(io_service, boost::posix_time::seconds(update_int)),
     thread_cnt(thread_cnt),
     update_int(update_int),
     buffer_size(buffer_size),
     flows_cnt(0),
     bytes_cnt(0),
     running (true),
     packets(buffer_size)
{
  // Setup
  setup();

  // Start recv
  start_receive();

  // Start update
  zone_timer.async_wait(boost::bind(&server::handle_update_zones, this));
  abonent_timer.async_wait(boost::bind(&server::handle_update_abonents, this));
}
Beispiel #27
0
void SerialConnection::receiver_complete(const boost::system::error_code& error,
											size_t bytes_transferred) {
	if (recv_raw_data_.size() == 0)
		start_frame();

	recv_raw_data_.push_back(recv_byte_);

	start_receive();

	if (recv_timer_->expires_from_now(boost::posix_time::milliseconds(rtu_silence_interval_ms_)) > 0)
	{
		// We managed to cancel the timer. Start new asynchronous wait.
		recv_timer_->async_wait(boost::bind(&SerialConnection::timer_expired,
												this,
												boost::asio::placeholders::error));
	}
	else
	{
		// Too late, timer has already expired!
		recv_timer_->async_wait(boost::bind(&SerialConnection::timer_expired,
												this,
												boost::asio::placeholders::error));
	}
}
void ClientICMP::measure_latency()
{
	start_send();
	start_receive();
}
Beispiel #29
0
void send_handler_done (BSocksClient *o)
{
    DebugObject_Access(&o->d_obj);
    ASSERT(o->buffer)
    
    switch (o->state) {
        case STATE_SENDING_HELLO: {
            BLog(BLOG_DEBUG, "sent hello");
            
            // allocate buffer for receiving hello
            bsize_t size = bsize_fromsize(sizeof(struct socks_server_hello));
            if (!reserve_buffer(o, size)) {
                goto fail;
            }
            
            // receive hello
            start_receive(o, (uint8_t *)o->buffer, size.value);
            
            // set state
            o->state = STATE_SENT_HELLO;
        } break;
        
        case STATE_SENDING_REQUEST: {
            BLog(BLOG_DEBUG, "sent request");
            
            // allocate buffer for receiving reply
            bsize_t size = bsize_add(
                bsize_fromsize(sizeof(struct socks_reply_header)),
                bsize_max(bsize_fromsize(sizeof(struct socks_addr_ipv4)), bsize_fromsize(sizeof(struct socks_addr_ipv6)))
            );
            if (!reserve_buffer(o, size)) {
                goto fail;
            }
            
            // receive reply header
            start_receive(o, (uint8_t *)o->buffer, sizeof(struct socks_reply_header));
            
            // set state
            o->state = STATE_SENT_REQUEST;
        } break;
        
        case STATE_SENDING_PASSWORD: {
            BLog(BLOG_DEBUG, "send password");
            
            // allocate buffer for receiving reply
            bsize_t size = bsize_fromsize(2);
            if (!reserve_buffer(o, size)) {
                goto fail;
            }
            
            // receive reply header
            start_receive(o, (uint8_t *)o->buffer, size.value);
            
            // set state
            o->state = STATE_SENT_PASSWORD;
        } break;
        
        default:
            ASSERT(0);
    }
    
    return;
    
fail:
    report_error(o, BSOCKSCLIENT_EVENT_ERROR);
}
Beispiel #30
0
void recv_handler_done (BSocksClient *o, int data_len)
{
    ASSERT(data_len >= 0)
    ASSERT(data_len <= o->control.recv_total - o->control.recv_len)
    DebugObject_Access(&o->d_obj);
    
    o->control.recv_len += data_len;
    
    if (o->control.recv_len < o->control.recv_total) {
        do_receive(o);
        return;
    }
    
    switch (o->state) {
        case STATE_SENT_HELLO: {
            BLog(BLOG_DEBUG, "received hello");
            
            struct socks_server_hello imsg;
            memcpy(&imsg, o->buffer, sizeof(imsg));
            
            if (ntoh8(imsg.ver) != SOCKS_VERSION) {
                BLog(BLOG_NOTICE, "wrong version");
                goto fail;
            }
            
            size_t auth_index;
            for (auth_index = 0; auth_index < o->num_auth_info; auth_index++) {
                if (o->auth_info[auth_index].auth_type == ntoh8(imsg.method)) {
                    break;
                }
            }
            
            if (auth_index == o->num_auth_info) {
                BLog(BLOG_NOTICE, "server didn't accept any authentication method");
                goto fail;
            }
            
            const struct BSocksClient_auth_info *ai = &o->auth_info[auth_index];
            
            switch (ai->auth_type) {
                case SOCKS_METHOD_NO_AUTHENTICATION_REQUIRED: {
                    BLog(BLOG_DEBUG, "no authentication");
                    
                    auth_finished(o);
                } break;
                
                case SOCKS_METHOD_USERNAME_PASSWORD: {
                    BLog(BLOG_DEBUG, "password authentication");
                    
                    if (ai->password.username_len == 0 || ai->password.username_len > 255 ||
                        ai->password.password_len == 0 || ai->password.password_len > 255
                    ) {
                        BLog(BLOG_NOTICE, "invalid username/password length");
                        goto fail;
                    }
                    
                    // allocate password packet
                    bsize_t size = bsize_fromsize(1 + 1 + ai->password.username_len + 1 + ai->password.password_len);
                    if (!reserve_buffer(o, size)) {
                        goto fail;
                    }
                    
                    // write password packet
                    char *ptr = o->buffer;
                    *ptr++ = 1;
                    *ptr++ = ai->password.username_len;
                    memcpy(ptr, ai->password.username, ai->password.username_len);
                    ptr += ai->password.username_len;
                    *ptr++ = ai->password.password_len;
                    memcpy(ptr, ai->password.password, ai->password.password_len);
                    ptr += ai->password.password_len;
                    
                    // start sending
                    PacketPassInterface_Sender_Send(o->control.send_if, (uint8_t *)o->buffer, size.value);
                    
                    // set state
                    o->state = STATE_SENDING_PASSWORD;
                } break;
                
                default: ASSERT(0);
            }
        } break;
        
        case STATE_SENT_REQUEST: {
            BLog(BLOG_DEBUG, "received reply header");
            
            struct socks_reply_header imsg;
            memcpy(&imsg, o->buffer, sizeof(imsg));
            
            if (ntoh8(imsg.ver) != SOCKS_VERSION) {
                BLog(BLOG_NOTICE, "wrong version");
                goto fail;
            }
            
            if (ntoh8(imsg.rep) != SOCKS_REP_SUCCEEDED) {
                BLog(BLOG_NOTICE, "reply not successful");
                goto fail;
            }
            
            int addr_len;
            switch (ntoh8(imsg.atyp)) {
                case SOCKS_ATYP_IPV4:
                    addr_len = sizeof(struct socks_addr_ipv4);
                    break;
                case SOCKS_ATYP_IPV6:
                    addr_len = sizeof(struct socks_addr_ipv6);
                    break;
                default:
                    BLog(BLOG_NOTICE, "reply has unknown address type");
                    goto fail;
            }
            
            // receive the rest of the reply
            start_receive(o, (uint8_t *)o->buffer + sizeof(imsg), addr_len);
            
            // set state
            o->state = STATE_RECEIVED_REPLY_HEADER;
        } break;
        
        case STATE_SENT_PASSWORD: {
            BLog(BLOG_DEBUG, "received password reply");
            
            if (o->buffer[0] != 1) {
                BLog(BLOG_NOTICE, "password reply has unknown version");
                goto fail;
            }
            
            if (o->buffer[1] != 0) {
                BLog(BLOG_NOTICE, "password reply is negative");
                goto fail;
            }
            
            auth_finished(o);
        } break;
        
        case STATE_RECEIVED_REPLY_HEADER: {
            BLog(BLOG_DEBUG, "received reply rest");
            
            // free buffer
            BFree(o->buffer);
            o->buffer = NULL;
            
            // free control I/O
            free_control_io(o);
            
            // init up I/O
            init_up_io(o);
            
            // set state
            o->state = STATE_UP;
            
            // call handler
            o->handler(o->user, BSOCKSCLIENT_EVENT_UP);
            return;
        } break;
        
        default:
            ASSERT(0);
    }
    
    return;
    
fail:
    report_error(o, BSOCKSCLIENT_EVENT_ERROR);
}