Exemplo n.º 1
0
string NetHelper::generateNetKey(const InetAddress &inet)
{
	char buffer[256] = {0};
	sprintf(buffer, "%08X%04X", inet.getIP(), inet.getPort());

	return buffer;
}
Exemplo n.º 2
0
Demarc::Port Demarc::pick(const InetAddress &to) const
	throw()
{
	Mutex::Lock _l(_ports_m);
	try {
		std::vector< std::map< Port,DemarcPortObj >::const_iterator > possibilities;
		for(std::map< Port,DemarcPortObj >::const_iterator pe(_ports.begin());pe!=_ports.end();++pe) {
			switch (pe->second.type) {
				case PORT_TYPE_UDP_SOCKET_V4:
					if (to.isV4())
						possibilities.push_back(pe);
					break;
				case PORT_TYPE_UDP_SOCKET_V6:
					if (to.isV6())
						possibilities.push_back(pe);
					break;
				default:
					break;
			}
		}
		if (possibilities.size())
			return possibilities[_r->prng->next32() % possibilities.size()]->first;
		else return NULL_PORT;
	} catch ( ... ) {
		return NULL_PORT;
	}
}
Exemplo n.º 3
0
bool SocketTest::netaddressTest()
{
    InetAddress google("www.google.com");
    TEST_ASSERT(google.isValid())
    const SRL::byte* rawip = google.getAddress();
    String ip = String::Format("%u.%u.%u.%u", rawip[0], rawip[1], rawip[2], rawip[3]);
    TEST_ASSERT(google.getHostAddress() == ip)
    TEST_ASSERT(google.getHostName().endsWith("google.com"))
    
    InetAddress googlecopy;
    TEST_ASSERT(!googlecopy.isValid())
    googlecopy = google;
    TEST_ASSERT(googlecopy.isValid())
    const SRL::byte* rawip2 = google.getAddress();
    String ip2 = String::Format("%u.%u.%u.%u", rawip2[0], rawip2[1], rawip2[2], rawip2[3]);
    TEST_ASSERT(googlecopy.getHostAddress() == ip2)
    TEST_ASSERT(googlecopy.getHostName().endsWith("google.com"))    
    TEST_THROWS(new InetAddress("gg"), Net::Errors::InvalidAddressException)
    
    InetAddress local("localhost");
    TEST_ASSERT(local.isValid())
    TEST_ASSERT(local.getHostAddress() == "127.0.0.1")
    TEST_ASSERT(local.getHostName() == "localhost")
    
    
	return true;
}
Exemplo n.º 4
0
void Bayonne::addTrap4(const char *addr)
{
	char abuf[128];
	char *tok;
	socklen_t alen = sizeof(sockaddr_in);
	InetAddress ia;
	int on = 1;

	setString(abuf, sizeof(abuf), addr);
	addr = strtok_r(abuf, " ;,\r\n\t", &tok);
	if(trap_so4 == INVALID_SOCKET)
	{
		trap_so4 = socket(AF_INET, SOCK_DGRAM, 0);
		setsockopt(trap_so4, SOL_SOCKET, SO_BROADCAST, (char*)(LPCTSTR)&on, sizeof(on));
	}

	while(addr && trap_count4 < 8)
	{
		ia = addr;
		memset(&trap_addr4[trap_count4], 0, alen);
		trap_addr4[trap_count4].sin_family = AF_INET;
		trap_addr4[trap_count4].sin_port = htons(162);
		trap_addr4[trap_count4].sin_addr = ia.getAddress();	
		++trap_count4;
		addr = strtok_r(NULL, " ;,\r\n\t", &tok);
	}
}
Exemplo n.º 5
0
	/**
	 * Derive the multicast group used for address resolution (ARP/NDP) for an IP
	 *
	 * @param ip IP address (port field is ignored)
	 * @return Multicat group for ARP/NDP
	 */
	static inline MulticastGroup deriveMulticastGroupForAddressResolution(const InetAddress &ip)
		throw()
	{
		if (ip.isV4()) {
			// IPv4 wants braodcast MACs, so we shove the V4 address itself into
			// the Multicast Group ADI field. Making V4 ARP work is basically why
			// ADI was added, as well as handling other things that want mindless
			// Ethernet broadcast to all.
			return MulticastGroup(MAC((unsigned char)0xff),Utils::ntoh(*((const uint32_t *)ip.rawIpData())));
		} else if (ip.isV6()) {
			// IPv6 is better designed in this respect. We can compute the IPv6
			// multicast address directly from the IP address, and it gives us
			// 24 bits of uniqueness. Collisions aren't likely to be common enough
			// to care about.
			const unsigned char *a = (const unsigned char *)ip.rawIpData();
			MAC m;
			m.data[0] = 0x33;
			m.data[1] = 0x33;
			m.data[2] = 0xff;
			m.data[3] = a[13];
			m.data[4] = a[14];
			m.data[5] = a[15];
			return MulticastGroup(m,0);
		}
		return MulticastGroup();
	}
Exemplo n.º 6
0
bool BSDEthernetTap::addIp(const InetAddress &ip)
{
	if (!ip)
		return false;

	std::vector<InetAddress> allIps(ips());
	if (std::find(allIps.begin(),allIps.end(),ip) != allIps.end())
		return true; // IP/netmask already assigned

	// Remove and reconfigure if address is the same but netmask is different
	for(std::vector<InetAddress>::iterator i(allIps.begin());i!=allIps.end();++i) {
		if ((i->ipsEqual(ip))&&(i->netmaskBits() != ip.netmaskBits())) {
			if (___removeIp(_dev,*i))
				break;
		}
	}

	long cpid = (long)vfork();
	if (cpid == 0) {
		::execl("/sbin/ifconfig","/sbin/ifconfig",_dev.c_str(),ip.isV4() ? "inet" : "inet6",ip.toString().c_str(),"alias",(const char *)0);
		::_exit(-1);
	} else if (cpid > 0) {
		int exitcode = -1;
		::waitpid(cpid,&exitcode,0);
		return (exitcode == 0);
	}
	return false;
}
Exemplo n.º 7
0
        void Acceptor::handleRead()
        {
            loop_->assertInLoopThread();
            InetAddress peerAddr;
            int connfd = acceptSocket_.accept( &peerAddr );
            if (connfd >= 0)
            {
                MDLog( "peerIp:%s, peerPort:%s", peerAddr.toIp( ).c_str(), peerAddr.toIpPort().c_str());
                if (newConnectionCallback_)
                {
                    newConnectionCallback_( connfd, peerAddr );
                }
                else
                {
                    sockets::close( connfd );
                }
            }
            else
            {

                if (errno == EAGAIN)
                {
                    return;
                }

                MDError( "accept error [%d]", errno );
            }
        }
	/**
	 * Load and initialize cluster definition and GeoIP data if any
	 *
	 * @param myAddress My ZeroTier address
	 * @param pathToClusterFile Path to cluster definition file
	 * @throws std::runtime_error Invalid cluster definition or unable to load data
	 */
	ClusterDefinition(uint64_t myAddress,const char *pathToClusterFile)
	{
		std::string cf;
		if (!OSUtils::readFile(pathToClusterFile,cf))
			return;

		char myAddressStr[64];
		Utils::snprintf(myAddressStr,sizeof(myAddressStr),"%.10llx",myAddress);

		std::vector<std::string> lines(OSUtils::split(cf.c_str(),"\r\n","",""));
		for(std::vector<std::string>::iterator l(lines.begin());l!=lines.end();++l) {
			std::vector<std::string> fields(OSUtils::split(l->c_str()," \t","",""));
			if ((fields.size() < 5)||(fields[0][0] == '#')||(fields[0] != myAddressStr))
				continue;

			// <address> geo <CSV path> <ip start column> <ip end column> <latitutde column> <longitude column>
			if (fields[1] == "geo") {
				if ((fields.size() >= 7)&&(OSUtils::fileExists(fields[2].c_str()))) {
					int ipStartColumn = Utils::strToInt(fields[3].c_str());
					int ipEndColumn = Utils::strToInt(fields[4].c_str());
					int latitudeColumn = Utils::strToInt(fields[5].c_str());
					int longitudeColumn = Utils::strToInt(fields[6].c_str());
					if (_geo.load(fields[2].c_str(),ipStartColumn,ipEndColumn,latitudeColumn,longitudeColumn) <= 0)
						throw std::runtime_error(std::string("failed to load geo-ip data from ")+fields[2]);
				}
				continue;
			}

			// <address> <ID> <name> <backplane IP/port(s)> <ZT frontplane IP/port(s)> <x,y,z>
			int id = Utils::strToUInt(fields[1].c_str());
			if ((id < 0)||(id > ZT_CLUSTER_MAX_MEMBERS))
				throw std::runtime_error(std::string("invalid cluster member ID: ")+fields[1]);
			MemberDefinition &md = _md[id];

			md.id = (unsigned int)id;
			if (fields.size() >= 6) {
				std::vector<std::string> xyz(OSUtils::split(fields[5].c_str(),",","",""));
				md.x = (xyz.size() > 0) ? Utils::strToInt(xyz[0].c_str()) : 0;
				md.y = (xyz.size() > 1) ? Utils::strToInt(xyz[1].c_str()) : 0;
				md.z = (xyz.size() > 2) ? Utils::strToInt(xyz[2].c_str()) : 0;
			}
			Utils::scopy(md.name,sizeof(md.name),fields[2].c_str());
			md.clusterEndpoint.fromString(fields[3]);
			if (!md.clusterEndpoint)
				continue;
			std::vector<std::string> zips(OSUtils::split(fields[4].c_str(),",","",""));
			for(std::vector<std::string>::iterator zip(zips.begin());zip!=zips.end();++zip) {
				InetAddress i;
				i.fromString(*zip);
				if (i)
					md.zeroTierEndpoints.push_back(i);
			}

			_ids.push_back((unsigned int)id);
		}

		std::sort(_ids.begin(),_ids.end());
	}
Exemplo n.º 9
0
int UdpSocket::send(const std::vector<uint8_t>& data, InetAddress destination)
{
    int ret = sendto(listenSocket, &data[0], data.size(), 0,
            destination.getAddress(), sizeof(*destination.getAddress()));
    if (ret == SOCKET_ERROR && errno != ECONNREFUSED) {
        setInetError("Can't send UDP packet");
        return -1;
    }
    return 0;
}
Exemplo n.º 10
0
bool SockDgram::Open(const InetAddress &local_addr, const InetAddress &remote_addr)
{
		assert(!IsValid());
		if(!Open(local_addr))
		{
				return false;
		}

		return (::connect(m_sock, remote_addr.Saddr(), remote_addr.Length()) == 0);
}
Exemplo n.º 11
0
//TODO: timeout retry 
int TcpSocket::Connect(InetAddress& addr)
{
    if(-1 == ::connect(sockfd_, (SA *)&addr.GetAddr(), sizeof(addr.GetAddr())))
    {
 
        FILE_LOG(logERROR)<<" connect error";
        return -1;
    }

    return 0;
}
Exemplo n.º 12
0
cvg_bool TcpSocket::getRemoteAddress(IAddress &addr) {
	InetAddress *iaddr = dynamic_cast<InetAddress *>(&addr);
	if (iaddr == NULL)
		throw cvgException("[TcpSocket] The address provided to getRemoteAddress() is not of type InetAddress");

	struct sockaddr_in addrIn;
	socklen_t addrLen = sizeof(struct sockaddr_in);
	if (getpeername(descriptor, (struct sockaddr *)&addrIn, &addrLen) != 0)
		throw cvgException("[TcpSocket] Unable to get remote address");
	iaddr->fromAddr(addrIn);

}
Exemplo n.º 13
0
void TargetParser::parse(string input, char separator)
{
    if(input.size() == 0)
    {
        return;
    }
    
    std::stringstream ss(input);
    std::string targetStr;
    while (std::getline(ss, targetStr, separator))
    {
        // Ignore strings smaller than 6 chars
        if (targetStr.size() < 6)
            continue;
    
        size_t pos = targetStr.find('/');
        // Target is a single IP
        if(pos == std::string::npos)
        {
            InetAddress target;
            try
            {
                target.setInetAddress(targetStr);
                parsedIPs.push_back(target);
            }
            catch (InetAddressException &e)
            {
                ostream *out = env->getOutputStream();
                (*out) << "Malformed/Unrecognized destination IP address or host name \"" + targetStr + "\"" << endl;
                continue;
            }
        }
        // Target is a whole address block
        else
        {
            std::string prefix = targetStr.substr(0, pos);
            unsigned char prefixLength = (unsigned char) std::atoi(targetStr.substr(pos + 1).c_str());
            try
            {
                InetAddress blockPrefix(prefix);
                NetworkAddress block(blockPrefix, prefixLength);
                parsedIPBlocks.push_back(block);
            }
            catch (InetAddressException &e)
            {
                ostream *out = env->getOutputStream();
                (*out) << "Malformed/Unrecognized address block \"" + targetStr + "\"" << endl;
                continue;
            }
        }
    }
}
Exemplo n.º 14
0
Demarc::Port Demarc::send(Demarc::Port fromPort,const InetAddress &to,const void *data,unsigned int len,int hopLimit) const
	throw()
{
	_ports_m.lock();

	std::map< Port,DemarcPortObj >::const_iterator pe(_ports.find(fromPort));
	if (pe == _ports.end()) {
		try {
			std::vector< std::map< Port,DemarcPortObj >::const_iterator > possibilities;
			for(pe=_ports.begin();pe!=_ports.end();++pe) {
				switch (pe->second.type) {
					case PORT_TYPE_UDP_SOCKET_V4:
						if (to.isV4())
							possibilities.push_back(pe);
						break;
					case PORT_TYPE_UDP_SOCKET_V6:
						if (to.isV6())
							possibilities.push_back(pe);
						break;
					default:
						break;
				}
			}
			if (possibilities.size())
				pe = possibilities[_r->prng->next32() % possibilities.size()];
			else {
				_ports_m.unlock();
				return NULL_PORT;
			}
		} catch ( ... ) {
			_ports_m.unlock();
			return NULL_PORT;
		}
	}

	switch (pe->second.type) {
		case PORT_TYPE_UDP_SOCKET_V4:
		case PORT_TYPE_UDP_SOCKET_V6:
			_ports_m.unlock();
			if (((UdpSocket *)pe->second.obj)->send(to,data,len,hopLimit))
				return pe->first;
			return NULL_PORT;
		default:
			break;
	}

	_ports_m.unlock();
	return NULL_PORT;
}
Exemplo n.º 15
0
    void Socket::connect(const InetAddress &host, const int &port)
    {
        sockaddr_in addr;

        memset(&addr, 0, sizeof(addr));
        addr.sin_family=AF_INET;
        addr.sin_port=htons(port);
        addr.sin_addr=*((in_addr*)host.getPtr());

        if (::connect(*((socket_t*)m_sock), (sockaddr *)&addr, sizeof(addr)))
		{
			int error=errnox;
			Error_send("Unable to connect to %s:%d with error %d\n", host.getName().c_str(), port, error);
		}
    }
Exemplo n.º 16
0
bool SockDgram::Open(const InetAddress &local_addr)
{
		assert(!IsValid());
		if(!SockDgram::Open())
		{
				return false;
		}

		if(::bind(m_sock, local_addr.Saddr(), local_addr.Length()) != 0)
		{
				return false;
		}
		
		return true;
}
Exemplo n.º 17
0
void Socket::bind( const InetAddress &addr)
{
	if( -1 == ::bind(m_sockfd, (const struct sockaddr *)addr.get_sockaddr_in(), sizeof( addr )) )
	{
		MY_LOG_ERROR("Socket::bind() error ");
	}
}
Exemplo n.º 18
0
    void TcpServer::newConnection(int sockfd, const InetAddress& peerAddr)
    {
        loop_->assertInLoopThread();
        EventLoop* ioLoop = threadPool_->getNextLoop();
        char buf[64];
        snprintf(buf, sizeof buf, "-%s#%d", ipPort_.c_str(), nextConnId_);
        ++nextConnId_;
        std::string connName = name_ + buf;

        LOG_PRINT(LogType_Info, "TcpServer::newConnection [%s] - new connection [%s] from %s",
                  name_.c_str(), connName.c_str(), peerAddr.toIpPort().c_str());
        InetAddress localAddr(SocketOps::getLocalAddr(sockfd));
        // FIXME poll with zero timeout to double confirm the new connection
        // FIXME use make_shared if necessary
        TcpConnectionPtr conn(new TcpConnection(ioLoop,
                                                connName,
                                                sockfd,
                                                localAddr,
                                                peerAddr));
        connections_[connName] = conn;
        conn->setConnectionCallback(connectionCallback_);
        conn->setMessageCallback(messageCallback_);
        conn->setWriteCompleteCallback(writeCompleteCallback_);
        conn->setCloseCallback(
            std::bind(&TcpServer::removeConnection, this, std::placeholders::_1)); // FIXME: unsafe
        ioLoop->runInLoop(std::bind(&TcpConnection::connectEstablished, conn));
    }
Exemplo n.º 19
0
ssize_t SocketIO::readn(char * buf,size_t count,InetAddress & clientAddr)
{
	size_t nleft = count;
	char * pbuf = buf;
	size_t nread;
	struct sockaddr_in clientaddr;
	size_t addrLen = sizeof(clientaddr);
	while(nleft > 0)
	{

		nread = ::recvfrom(sockfd_,pbuf,nleft,0,(struct sockaddr*)&clientaddr,&addrLen);
		if(-1 == nread)
		{
			if(errno == EINTR)
				continue;
			return -1;
		}
		else if(0 == nread)
		{
			break;
		}
		
		nleft -= nread;
		pbuf += nread;
	}
	clientAddr.setSockAddrInet(clientaddr);
	return (count - nleft);
}
Exemplo n.º 20
0
int Socket::recvFrom(char *data, int length, int flags, InetAddress& sinaddr)const
{
    socklen_t slen;
    int len = ZL_RECVFROM(sockfd_, data, length, flags, sinaddr, &slen);
    if(slen != sinaddr.addressLength())
        throw SocketException("unknown protocol type(in Socket::RecvFrom)");
    return len;
}
Exemplo n.º 21
0
int TcpSocket::Bind(InetAddress& addr)
{
    bool ret = addr.IsValid();
    if(false == ret)
    {
        FILE_LOG(logERROR)<<__FILE__<<" "<<__LINE__<<" address is invalid";
        return -1;
    }

    if(-1 == ::bind(sockfd_, (SA*)(&addr.GetAddr()), sizeof(addr.GetAddr())))
    {
        FILE_LOG(logERROR)<<__FILE__<<" "<<__LINE__<<" bind address error";
	return -1;       
    }

    return 0;
}
Exemplo n.º 22
0
	void newConnection(int sockfd, const InetAddress& peerAddr)
	{
		static char buf[] = { "I am server, accept you and close you." };
		printf("newConnection(): pid = %d, tid = %d\n", getpid(), this_thread::get_id().value());
		printf("newConnection(): accepted a new connection from %s\n", peerAddr.ipPort().c_str());
		SocketUtil::write(sockfd, buf, sizeof(buf));
        SocketUtil::closeSocket(sockfd);
	}
Exemplo n.º 23
0
long InetAddressSet::getPositionIndex(const InetAddress &addr)const{
	long low=0;
	long high=size-1;
	long mid;
	while(low<=high){
		mid=(low+high)/2;
		if(addr.getULongAddress()<getElementAt(mid).getULongAddress()){
			high=mid-1;
		}else if(addr.getULongAddress()>getElementAt(mid).getULongAddress()){
			low=mid+1;
		}else{
			return mid;
		}
	}

	return -1;

}
Exemplo n.º 24
0
TcpConnection::TcpConnection(EventLoop* loop, int sockfd, const InetAddress& localAddr, const InetAddress& peerAddr)
    : loop_(loop)
    , state_(kConnecting)
    , localAddr_(localAddr.getSockAddrInet())
    , peerAddr_(peerAddr.getSockAddrInet())
{
    socket_ = new Socket(sockfd);
    socket_->setKeepAlive(true);
    socket_->setNoDelay(true);
    socket_->setNonBlocking();

    channel_ = new Channel(loop, sockfd);
    channel_->setReadCallback(std::bind(&TcpConnection::handleRead, this, std::placeholders::_1));
    channel_->setWriteCallback(std::bind(&TcpConnection::handleWrite, this));
    channel_->setCloseCallback(std::bind(&TcpConnection::handleClose, this));
    channel_->setErrorCallback(std::bind(&TcpConnection::handleError, this));
    LOG_INFO("TcpConnection::TcpConnection(), [%0x] [%d][%0x][%0x]", this, socket_->fd(), socket_, channel_);
}
Exemplo n.º 25
0
	Path(const InetAddress &localAddress,const InetAddress &addr) :
		_lastSend(0),
		_lastReceived(0),
		_addr(addr),
		_localAddress(localAddress),
		_flags(0),
		_ipScope(addr.ipScope())
	{
	}
Exemplo n.º 26
0
void Socket::bind(InetAddress & addr)
{
	if(-1 == ::bind(sockfd_, 
		   (struct sockaddr*)addr.getSockAddrInet(), 
			sizeof(struct sockaddr)))
	{
		perror("bind error");
		exit(EXIT_FAILURE);
	}
}
Exemplo n.º 27
0
bool NetPipe::Open(size_t buf_size)
{
		assert(!m_reader.IsValid() && !m_writer.IsValid());
		
		if(m_reader.IsValid() || m_writer.IsValid()) return false;
		
		InetAddress addr;
		addr.SetAddr(::htonl(INADDR_LOOPBACK));
		addr.SetPort(0);
		
		Acceptor acceptor;
		
		CHECK_AND_RET( acceptor.Open(addr) );
		
		
		CHECK_AND_RET( acceptor.GetLocalAddr(addr) );
		



		CHECK_AND_RET( m_writer.Open() );
		
		int opt_val = 0;
		CHECK_AND_RET( m_writer.SetOpt(IPPROTO_TCP, TCP_NODELAY, &opt_val, sizeof(opt_val))	);
		
		opt_val = buf_size;
		
		CHECK_AND_RET( m_writer.SetOpt(SOL_SOCKET, SO_SNDBUF, &opt_val, sizeof(opt_val)) );

		CHECK_AND_RET(	Connector::Connect(m_writer, addr, 0)	);

		CHECK_AND_RET(	acceptor.Accept(m_reader) );

		assert(m_reader.IsValid() && m_writer.IsValid());

		m_reader.CloseWriter();
		m_writer.CloseReader();
		
		CHECK_AND_RET( m_reader.Enable(NET_NONBLOCK) && m_writer.Enable(NET_NONBLOCK) );

		return true;

}
Exemplo n.º 28
0
bool Socket::bind(const InetAddress& addr)
{
    sockaddr_ = addr.getSockAddrInet();
	int ret = ZL_BIND(sockfd_, (struct sockaddr *) &sockaddr_, sizeof(sockaddr_));
    if(ret == -1)
    {
        return false;
    }
    return true;
}
Exemplo n.º 29
0
int TcpSocket::Accept(InetAddress& addr)
{
    int res = -1;
    socklen_t addrlen = sizeof(addr);
    res = ::accept(sockfd_, (SA *)&addr.GetAddr(), &addrlen);
    if(res == -1)
    {
        FILE_LOG(logERROR)<<__FILE__<<" "<<__LINE__<<" accept error";
        return res;
    }
   
    return res;
}
Exemplo n.º 30
0
ChannelFuturePtr ClientBootstrap::connect(const InetAddress& remote,
        const InetAddress& local) {
    if (!remote) {
        LOG_INFO << "the remote address is invalidated, then return a failed future.";
        return NullChannel::instance()->newFailedFuture(
                   ChannelException("Failed to initialize a pipeline."));
    }

    ChannelPtr ch = newChannel();

    if (!ch) {
        LOG_INFO << "failed to create a new channel, then return a failed future.";
        return NullChannel::instance()->newFailedFuture(
                   ChannelException("Failed to create a new channel."));
    }

    if (!initializer()) {
        LOG_INFO << "has not set channel pipeline initializer.";
        return NullChannel::instance()->newFailedFuture(
                   ChannelException("has not set channel pipeline initializer."));
    }

    ch->setInitializer(initializer());
    ch->open();

    ch->closeFuture()->addListener(boost::bind(
        &ClientBootstrap::closeChannelBeforeDestruct,
        this,
        _1,
        ch));

    // Set the options.
    ch->config().setOptions(options());

    insertChannel(ch->id(), ch);

    // Bind.
    if (localAddress()) {
        LOG_INFO << "bind the channel to local address" << local.toString();
        ChannelFuturePtr future = ch->bind(local);
        future->awaitUninterruptibly();
    }

//     ch->closeFuture()->addListener(
//         boost::bind(&ClientBootstrap::onChannelClosed,
//                     this,
//                     _1));

    // Connect.
    return ch->connect(remote);
}