Example #1
0
TEST(libmcrouter, listenSock) {
  /* Create a listen socket, pass it to a child mcrouter and
     check that communication through the socket works */
  using namespace facebook::memcache;

  ListenSocket listenSock;

  std::vector<std::string> args{MCROUTER_INSTALL_PATH "mcrouter/mcrouter",
        "--listen-sock-fd", folly::to<std::string>(listenSock.getSocketFd()),
        "--config-str", configString };
  auto testArgs = defaultTestCommandLineArgs();
  args.insert(args.end(), testArgs.begin(), testArgs.end());
  folly::Subprocess mcr(args);

  SCOPE_EXIT {
    mcr.terminate();
    mcr.wait();
  };

  const std::string kSetRequest = "set testkey 0 0 1\r\nv\r\n";
  const std::string kStoredReply = "STORED\r\n";
  const std::string kGetRequest = "get testkey\r\n";
  const std::string kGetReply = "VALUE testkey 0 1\r\nv\r\nEND\r\n";

  ClientSocket mcrSock(listenSock.getPort());
  EXPECT_EQ(kStoredReply, mcrSock.sendRequest(kSetRequest));
  EXPECT_EQ(kGetReply, mcrSock.sendRequest(kGetRequest));

  ClientSocket mcSock(memcacheLocal->getPort());
  EXPECT_EQ(kGetReply, mcSock.sendRequest(kGetRequest));
}
Example #2
0
bool InspIRCd::BindPort(ConfigTag* tag, const irc::sockets::sockaddrs& sa, std::vector<ListenSocket*>& old_ports)
{
	for (std::vector<ListenSocket*>::iterator n = old_ports.begin(); n != old_ports.end(); ++n)
	{
		if ((**n).bind_sa == sa)
		{
			// Replace tag, we know addr and port match, but other info (type, ssl) may not.
			ServerInstance->Logs.Log("SOCKET", LOG_DEFAULT, "Replacing listener on %s from old tag at %s with new tag from %s",
				sa.str().c_str(), (*n)->bind_tag->getTagLocation().c_str(), tag->getTagLocation().c_str());
			(*n)->bind_tag = tag;
			(*n)->ResetIOHookProvider();

			old_ports.erase(n);
			return true;
		}
	}

	ListenSocket* ll = new ListenSocket(tag, sa);
	if (ll->GetFd() < 0)
	{
		ServerInstance->Logs.Log("SOCKET", LOG_DEFAULT, "Failed to listen on %s from tag at %s: %s",
			sa.str().c_str(), tag->getTagLocation().c_str(), strerror(errno));
		delete ll;
		return false;
	}

	ServerInstance->Logs.Log("SOCKET", LOG_DEFAULT, "Added a listener on %s from tag at %s", sa.str().c_str(), tag->getTagLocation().c_str());
	ports.push_back(ll);
	return true;
}
Example #3
0
void umbrellaBinaryReply(std::string data, mc_res_t expectedResult) {
  ListenSocket sock;

  std::thread serverThread([&sock, &data] {
    auto sockFd = ::accept(sock.getSocketFd(), nullptr, nullptr);
    // Don't read anything, just reply with a serialized reply.
    size_t n = folly::writeFull(sockFd, data.data(), data.size());
    CHECK(n == data.size());
  });

  TestClient client("localhost", sock.getPort(), 200, mc_umbrella_protocol);
  client.sendGet("test", expectedResult);
  client.waitForReplies();
  serverThread.join();
}
Example #4
0
    void run ()
    {
        SocketHandler h;

        // Launch the RA listener socket
        ListenSocket<RASocket> RAListenSocket (h);
        bool usera = sConfig.GetBoolDefault ("Ra.Enable", false);

        if (usera)
        {
            port_t raport = sConfig.GetIntDefault ("Ra.Port", 3443);
            std::string stringip = sConfig.GetStringDefault ("Ra.IP", "0.0.0.0");
            ipaddr_t raip;
            if (!Utility::u2ip (stringip, raip))
                sLog.outError ("MaNGOS RA can not bind to ip %s", stringip.c_str ());
            else if (RAListenSocket.Bind (raip, raport))
                sLog.outError ("MaNGOS RA can not bind to port %d on %s", raport, stringip.c_str ());
            else
            {
                h.Add (&RAListenSocket);

                sLog.outString ("Starting Remote access listner on port %d on %s", raport, stringip.c_str ());
            }
        }

        // Socket Selet time is in microseconds , not miliseconds!!
        uint32 socketSelecttime = sWorld.getConfig (CONFIG_SOCKET_SELECTTIME);

        // if use ra spend time waiting for io, if not use ra ,just sleep
        if (usera)
        {
            while (!World::IsStopped())
            {
                h.Select (0, socketSelecttime);
                checkping ();
            }
        }
        else
        {
            while (!World::IsStopped())
            {
                ACE_Based::Thread::Sleep(static_cast<unsigned long> (socketSelecttime / 1000));
                checkping ();
            }
        }
    }
Example #5
0
int main (int argc, char **argv)
{
	ListenSocket *listen;
	time_t rawtime;
	struct tm *timeinfo;
	char *timestr;


	enable_logging_of (LOG_INFO);
	enable_logging_of (LOG_WARNING);
	enable_logging_of (LOG_ERROR);
//	enable_logging_of (LOG_SOCKET);
//	enable_logging_of (LOG_LISTENSOCKET);
//	enable_logging_of (LOG_CLIENTSOCKET);		
//	enable_logging_of (LOG_CONTROLLER);
//	enable_logging_of (LOG_LOWERHCI);		
	enable_logging_of (LOG_LINKLAYER);
	enable_logging_of (LOG_LLSM);
//	enable_logging_of (LOG_PHYSICALLAYER);

	time (&rawtime);
	srand (rawtime);
	timeinfo = localtime (&rawtime);
	timestr = asctime (timeinfo);
	timestr[24] = 0;

	log (LOG_INFO, "-----------------------------------------------------------------------------");
	log (LOG_INFO, "%s%s", "Bluetooth Low Energy Virtual Controller Server @ ", timestr);
	log (LOG_INFO, "-----------------------------------------------------------------------------");
	
	start_background_monitor ((void *) argv[0]);
	start_physical_layer_simulation ();

	listen = new ListenSocket (0xb1ee);
	listen->set_callback (on_connection);
	
	while (Socket::poll ())
	{
	}
}
Example #6
0
int InspIRCd::BindPorts(FailedPortList &failed_ports)
{
	int bound = 0;
	std::vector<ListenSocket*> old_ports(ports.begin(), ports.end());

	ConfigTagList tags = ServerInstance->Config->ConfTags("bind");
	for(ConfigIter i = tags.first; i != tags.second; ++i)
	{
		ConfigTag* tag = i->second;
		std::string porttag = tag->getString("port");
		std::string Addr = tag->getString("address");

		if (strncasecmp(Addr.c_str(), "::ffff:", 7) == 0)
			this->Logs->Log("SOCKET", LOG_DEFAULT, "Using 4in6 (::ffff:) isn't recommended. You should bind IPv4 addresses directly instead.");

		irc::portparser portrange(porttag, false);
		int portno = -1;
		while (0 != (portno = portrange.GetToken()))
		{
			irc::sockets::sockaddrs bindspec;
			if (!irc::sockets::aptosa(Addr, portno, bindspec))
				continue;
			std::string bind_readable = bindspec.str();

			bool skip = false;
			for (std::vector<ListenSocket*>::iterator n = old_ports.begin(); n != old_ports.end(); ++n)
			{
				if ((**n).bind_desc == bind_readable)
				{
					(*n)->bind_tag = tag; // Replace tag, we know addr and port match, but other info (type, ssl) may not
					(*n)->ResetIOHookProvider();

					skip = true;
					old_ports.erase(n);
					break;
				}
			}
			if (!skip)
			{
				ListenSocket* ll = new ListenSocket(tag, bindspec);

				if (ll->GetFd() > -1)
				{
					bound++;
					ports.push_back(ll);
				}
				else
				{
					failed_ports.push_back(std::make_pair(bind_readable, strerror(errno)));
					delete ll;
				}
			}
		}
	}

	std::vector<ListenSocket*>::iterator n = ports.begin();
	for (std::vector<ListenSocket*>::iterator o = old_ports.begin(); o != old_ports.end(); ++o)
	{
		while (n != ports.end() && *n != *o)
			n++;
		if (n == ports.end())
		{
			this->Logs->Log("SOCKET", LOG_DEFAULT, "Port bindings slipped out of vector, aborting close!");
			break;
		}

		this->Logs->Log("SOCKET", LOG_DEFAULT, "Port binding %s was removed from the config file, closing.",
			(**n).bind_desc.c_str());
		delete *n;

		// this keeps the iterator valid, pointing to the next element
		n = ports.erase(n);
	}

	return bound;
}
Example #7
0
bool 
Server::mainloop( Object* root ) {

    std::lock_guard<std::mutex> slock( static_lock );
    instance_in_mainloop =this;

    ListenSocket sock;
    sock.setBlocking( false );

    if( !sock.bind( _portnum ) || !sock.listen()  ) {
        log << "Could not bind to port " << _portnum << std::endl;
        log << strerror( errno ) << std::endl;
        exit( 1 );
    }

    log << VOXOWL_VERSION_FULL_NAME << " listening to port " << _portnum << std::endl;

    connection_list_t::iterator it;
    while( !_stop ) {

        // Cleanup any closed connections
       /* We cannot do this because it's thread-unsafe. We delete everything
        * on exit, which may also be a potential problem. FIXME
        for( it = connection_list.begin(); it != connection_list.end(); ) {
            if( !(*it)->socket->isOpen() ) {
                delete (*it);
                it =connection_list.erase( it );
            }
            else
                it++;
        }*/

        // Wait for one second at a time
        if( !sock.poll( 1 ) ) {
            continue;
        }

        // It seems a new connection attempt is being made
        ClientSocket *csock;
        if( ( csock = sock.accept() ) ) {
            std::lock_guard<std::mutex> lock( write_lock );
            log << "Accepting new connection" << std::endl;
            Connection *c = new Connection( &connections );
            c->socket =csock;
            c->pbuffer =new PacketBuffer();
            c->pbuffer->setOutgoingPacketHandler( &connectionSendFunc );
            if( !data_connection )
                setDataConnection( c );
            c->thread =new std::thread( connectionMain, c, this );
            connection_list.push_back( c );
        }
        else
            break;

    }

    log << "Stopping server, waiting for connections to close." << std::endl;

    for( it = connection_list.begin(); it != connection_list.end(); it++ ) {
        if( (*it)->socket->isOpen() )
            (*it)->socket->close();
        delete (*it);
    }

    log << "All connections terminated." << std::endl;

    instance_in_mainloop =0;
    return true;
}