Exemple #1
0
void IpTest::testIpAddrOst()
{
	TITLE();

	const IpAddr ipv4 = {"8.8.8.8"};

	ost::IPV4Host v4host = ipv4;
	IpAddr ip = v4host.getAddress();
	CPPUNIT_ASSERT(ipv4 == ip);

#if HAVE_IPV6
	const IpAddr ipv6 = {"2001:4860:4860::8888"};

	ost::IPV6Host v6host = ipv6;
	ip = v6host.getAddress();
	CPPUNIT_ASSERT(ipv6 == ip);

	ost::IPV6Host v6host2 = v6host;
	ip = v6host2.getAddress();
	CPPUNIT_ASSERT(ipv6 == ip);

	ost::IPV6Host v6host3 = {};
	ip = v6host3.getAddress();
	CPPUNIT_ASSERT(ip);
	CPPUNIT_ASSERT(v6host3.getAddressCount() > 0 && v6host3.getAddressCount() < 256);

	v6host3 = v6host;
	CPPUNIT_ASSERT(IpAddr(v6host3.getAddress()) == ipv6);
	CPPUNIT_ASSERT(v6host3.getAddressCount() == 1);

	v6host3 = v6host2.getAddress();
	CPPUNIT_ASSERT(IpAddr(v6host3.getAddress()) == ipv6);
	CPPUNIT_ASSERT(v6host3.getAddressCount() == 1);
#endif
}
Exemple #2
0
void IpTest::testIpAddr()
{
	TITLE();

	IpAddr ip = {"8.8.8.8"};
	CPPUNIT_ASSERT(ip);
	CPPUNIT_ASSERT(ip.toString() == "8.8.8.8");
	CPPUNIT_ASSERT(ip.getPort() == 0);
	CPPUNIT_ASSERT(ip.isIpv4());
	CPPUNIT_ASSERT(not ip.isIpv6());
	CPPUNIT_ASSERT(not ip.isLoopback());
	CPPUNIT_ASSERT(not ip.isPrivate());
	CPPUNIT_ASSERT(not ip.isUnspecified());

	IpAddr ip_2 = ip.toString();
	CPPUNIT_ASSERT(ip_2 == ip);

	ip = IpAddr();
	CPPUNIT_ASSERT(not ip);
	CPPUNIT_ASSERT(ip.isUnspecified());
	CPPUNIT_ASSERT(not ip.isIpv4());
	CPPUNIT_ASSERT(not ip.isIpv6());
	CPPUNIT_ASSERT(ip.getPort() == 0);

	ip = IpAddr("8.8.8.8:42");
	CPPUNIT_ASSERT(ip);
	CPPUNIT_ASSERT(ip.toString() == "8.8.8.8");
	CPPUNIT_ASSERT(ip.getPort() == 42);

	pj_sockaddr_set_port(ip.pjPtr(), 5042);
	CPPUNIT_ASSERT(ip.getPort() == 5042);

#if HAVE_IPV6
	const in6_addr native_ip = {{
		0x3f, 0xfe, 0x05, 0x01,
		0x00, 0x08, 0x00, 0x00,
		0x02, 0x60, 0x97, 0xff,
		0xfe, 0x40, 0xef, 0xab
	}};
	ip = IpAddr(native_ip);
	CPPUNIT_ASSERT(ip);
	CPPUNIT_ASSERT(ip == IpAddr("3ffe:0501:0008:0000:0260:97ff:fe40:efab"));
	CPPUNIT_ASSERT(not ip.isIpv4());
	CPPUNIT_ASSERT(ip.isIpv6());

	CPPUNIT_ASSERT(IpAddr::isValid("3ffe:0501:0008:0000:0260:97ff:fe40:efab"));
	CPPUNIT_ASSERT(IpAddr::isValid("[3ffe:0501:0008:0000:0260:97ff:fe40:efab]"));
	CPPUNIT_ASSERT(IpAddr::isValid("[3ffe:0501:0008:0000:0260:97ff:fe40:efab]:4242"));
	CPPUNIT_ASSERT(IpAddr::isValid("[3ffe:501:8::260:97ff:fe40:efab]:4242"));
#endif
}
void LwipNetUdpSocket::cleanUp() //Flush input buffer
{
  //Ensure that further error won't be followed to this inst (which can be destroyed)
  if( m_pPcb )
  {
    udp_recv( (udp_pcb*) m_pPcb, NULL, (void*) NULL );
  }

  //Leaving multicast group(Ok because LwIP has a refscount for multicast group)
  #if LWIP_IGMP //Multicast support enabled
  if(m_multicastGroup.isMulticast())
  {
    ip_addr_t multicastGroupAddr = m_multicastGroup.getStruct();
    igmp_leavegroup(IP_ADDR_ANY, &multicastGroupAddr);
    m_multicastGroup = IpAddr();
  }
  #endif

  list<InPacket>::iterator it;
  for ( it = m_lInPkt.begin(); it != m_lInPkt.end(); it++ )
  {
    //Free buf
    pbuf_free((pbuf*)((*it).pBuf));
  }
  m_lInPkt.clear();
}
//Execute request & return OK if found, NOTFOUND or ERROR on error, or PROCESSING if the request has not completed yet
void LwipNetDnsRequest::poll()
{
  err_t  err;
  switch(m_state)
  {
  case LWIPNETDNS_START: //First req, let's call dns_gethostbyname
    ip_addr_t ipStruct;
    err = dns_gethostbyname(m_hostname, &ipStruct, LwipNetDnsRequest::sFoundCb, (void*) this );
    if( err == ERR_OK )
    {
      m_ip = IpAddr(&ipStruct);
      m_state = LWIPNETDNS_OK;
      DBG("DNS: Ip found in cache.\n");
    }
    else if( err == ERR_INPROGRESS)
    {
      DBG("DNS: Processing.\n");
      m_state = LWIPNETDNS_PROCESSING;
    }
    else //Likely ERR_VAL
    {
      DBG("DNS: Error on init.\n");
      m_state = LWIPNETDNS_ERROR;
    }
    break;
  case LWIPNETDNS_PROCESSING:
    break; //Nothing to do, DNS is polled on interrupt
  case LWIPNETDNS_OK:
    if(!m_cbFired)
    {
      DBG("DNS: Ip found.\n");
      m_cbFired = true;
      onReply(NETDNS_FOUND); //Raise callback
    }
    break;
  case LWIPNETDNS_NOTFOUND:
    if(!m_cbFired)
    {
      DBG("DNS: could not be resolved.\n");
      m_cbFired = true;
      onReply(NETDNS_NOTFOUND); //Raise callback
    }
    break;
  case LWIPNETDNS_ERROR:
  default:
    if(!m_cbFired)
    {
      DBG("DNS: Error.\n");
      m_cbFired = true;
      onReply(NETDNS_ERROR); //Raise callback
    }
    break;
  }
  if(m_closing && (m_state!=LWIPNETDNS_PROCESSING)) //Check wether the closure has been reqd
  {
    DBG("LwipNetDnsRequest: Closing in poll()\n");
    NetDnsRequest::close();
  }
}
Exemple #5
0
bool Url::getHostIp(IpAddr* ip)
{
  unsigned int ipArr[4] = {0};
  if ( sscanf(m_host.c_str(), "%u.%u.%u.%u", &ipArr[0], &ipArr[1], &ipArr[2], &ipArr[3]) != 4 )
  {
    return false;
  }
  *ip = IpAddr(ipArr[0], ipArr[1], ipArr[2], ipArr[3]);
  return true;
}
Exemple #6
0
IpAddr
ip_utils::getAnyHostAddr(pj_uint16_t family)
{
    if (family == pj_AF_UNSPEC()) {
#if HAVE_IPV6
        family = pj_AF_INET6();
#else
        family = pj_AF_INET();
#endif
    }
    return IpAddr(family);
}
void LwipNetDnsRequest::foundCb(const char *name, ip_addr_t *ipaddr)
{
  if( ipaddr == NULL )
  {
    DBG("LwipNetDnsRequest: Callback: Name not found\n");
    m_state = LWIPNETDNS_NOTFOUND;
    return;
  }
  DBG("LwipNetDnsRequest: Callback: Resolved\n");
  m_ip = IpAddr(ipaddr);
  m_state = LWIPNETDNS_OK;
}
Exemple #8
0
NetTcpSocketErr LwipNetTcpSocket::accept(Host* pClient, NetTcpSocket** ppNewNetTcpSocket)
{
  if( !m_pPcb ) //Pcb doesn't exist (anymore)
    return NETTCPSOCKET_MEM;
  //Dequeue a connection
  //if( m_lpInPcb.empty() )
  if( m_lpInNetTcpSocket.empty() )
    return NETTCPSOCKET_EMPTY;
  
  tcp_accepted( ((tcp_pcb*) m_pPcb) ); //Should fire proper events //WARN: m_pPcb is the GOOD param here (and not pInPcb)
  
/*  tcp_pcb* pInPcb = m_lpInPcb.front();
  m_lpInPcb.pop();*/
  
  if( (m_lpInNetTcpSocket.front()) == NULL )
  {
    m_lpInNetTcpSocket.pop();
    return NETTCPSOCKET_RST;
  }
  
  if( (m_lpInNetTcpSocket.front())->m_closed )
  {
    Net::releaseTcpSocket(m_lpInNetTcpSocket.front());
    m_lpInNetTcpSocket.pop();
    return NETTCPSOCKET_RST;
  }
  
  ip_addr_t* ip = (ip_addr_t*) &( (m_lpInNetTcpSocket.front()->m_pPcb)->remote_ip);
  
  *ppNewNetTcpSocket = m_lpInNetTcpSocket.front();
  *pClient = Host(
    IpAddr( 
      ip
    ), 
    m_lpInNetTcpSocket.front()->m_pPcb->remote_port 
  );
  m_lpInNetTcpSocket.pop();
//  *pClient = Host( IpAddr(pInPcb->remote_ip), pInPcb->remote_port );
  
  //Return a new socket
 // *ppNewNetTcpSocket = (NetTcpSocket*) new LwipNetTcpSocket(pInPcb);

  //tcp_accepted( ((tcp_pcb*) m_pPcb) ); //Should fire proper events //WARN: m_pPcb is the GOOD param here (and not pInPcb)
  
/*  if(*ppNewNetTcpSocket == NULL)
  {
    DBG("Not enough mem, socket dropped in LwipNetTcpSocket::accept.\n");
    tcp_abort(pInPcb);
  }*/
  
  return NETTCPSOCKET_OK;
}
Exemple #9
0
void
SipTransportBroker::findLocalAddressFromSTUN(pjsip_transport *transport,
                                       pj_str_t *stunServerName,
                                       int stunPort,
                                       std::string &addr, pj_uint16_t &port) const
{
    // Initialize the sip port with the default SIP port
    port = DEFAULT_SIP_PORT;

    // Initialize the sip address with the hostname
    const pj_str_t *pjMachineName = pj_gethostname();
    addr = std::string(pjMachineName->ptr, pjMachineName->slen);

    // Update address and port with active transport
    RETURN_IF_NULL(transport, "Transport is NULL in findLocalAddress, using local address %s:%d", addr.c_str(), port);

    IpAddr mapped_addr;
    pj_sock_t sipSocket = pjsip_udp_transport_get_socket(transport);
    const pjstun_setting stunOpt = {PJ_TRUE, *stunServerName, stunPort, *stunServerName, stunPort};
    const pj_status_t stunStatus = pjstun_get_mapped_addr2(&cp_.factory, &stunOpt, 1, &sipSocket, &static_cast<pj_sockaddr_in&>(mapped_addr));

    switch (stunStatus) {
        case PJLIB_UTIL_ESTUNNOTRESPOND:
           ERROR("No response from STUN server %.*s", stunServerName->slen, stunServerName->ptr);
           return;
        case PJLIB_UTIL_ESTUNSYMMETRIC:
           ERROR("Different mapped addresses are returned by servers.");
           return;
        case PJ_SUCCESS:
            port = mapped_addr.getPort();
            addr = mapped_addr.toString();
        default:
           break;
    }

    WARN("Using address %s provided by STUN server %.*s",
         IpAddr(mapped_addr).toString(true).c_str(), stunServerName->slen, stunServerName->ptr);
}
int SyncedSDFileSystem::disk_initialize() {
  int ret;
  TCPSocketErr err;

  ret = SDFileSystem::disk_initialize();

  dirty_ = vector<bool>(MAX_SYNCED_BLOCKS, false);
  block_md4_ = vector<struct block_hash>(MAX_SYNCED_BLOCKS);
  for (int i = 0; i < MAX_SYNCED_BLOCKS; ++i) {
    block_md4_[i].block_num = i;
    if (SDFileSystem::disk_read((char *)buffer_, i)) {
      // TODO: handle error
    }
    mdfour((unsigned char *) block_md4_[i].md4, buffer_, BLOCK_SIZE);
  }

  if (is_master_) {
    tcp_socket_->setOnEvent(this, &SyncedSDFileSystem::on_master_event);
    tcp_socket_->bind(Host(address_, SYNC_FS_PORT));
    tcp_socket_->listen();
    debug("MASTER: listening for connections");
  } else {
    tcp_socket_->setOnEvent(this, &SyncedSDFileSystem::on_node_event);
    err = tcp_socket_->connect(Host(IpAddr(192, 168, 1, MASTER_ADDR), SYNC_FS_PORT));
    if (err) {
      // TODO: retry master registration periodically
      tcp_socket_->close();
      delete tcp_socket_;
      printf("SLAVE: failed to connect to master, entering standalone mode\n\r");
      // TODO: handle offline mode by checking if tcp_socket_ == NULL
    } else {
      debug("SLAVE: connected to master");
    }
  }
  return ret;
}
Exemple #11
0
void HTTPServer::bind(int port /*= 80*/)
{
  Host h(IpAddr(127,0,0,1), port, "localhost");
  m_pTCPSocket->bind(h);     
  m_pTCPSocket->listen(); //Listen
}
int /*if < 0 : NetUdpSocketErr*/ LwipNetUdpSocket::recvfrom(char* buf, int len, Host* pHost)
{
  if( !m_pPcb ) //Pcb doesn't exist (anymore)
    return NETUDPSOCKET_MEM;
  int inLen = 0;
  int cpyLen = 0;

  static int rmgLen = 0;
  //Contains the remaining len in this pbuf

  if( m_lInPkt.empty() )
    return 0;

  pbuf* pBuf = (pbuf*) m_lInPkt.front().pBuf;

  if(pHost)
    *pHost = Host( IpAddr(&m_lInPkt.front().addr), m_lInPkt.front().port );

  if( !pBuf )
  {
    rmgLen = 0;
    return 0;
  }

  if ( !rmgLen ) //We did not know m_pReadPbuf->len last time we called this fn
  {
    rmgLen = pBuf->len;
  }

  while ( inLen < len )
  {
    cpyLen = MIN( (len - inLen), rmgLen ); //Remaining len to copy, remaining len in THIS pbuf
    memcpy((void*)buf, (void*)((char*)(pBuf->payload) + (pBuf->len - rmgLen)), cpyLen);
    inLen += cpyLen;
    buf += cpyLen;

    rmgLen = rmgLen - cpyLen; //Update rmgLen

    if( rmgLen > 0 )
    {
      //We did not read this pbuf completely, so let's save it's pos & return
      break;
    }

    if(pBuf->next)
    {
      pbuf* pNextPBuf = pBuf->next;
      pBuf->next = NULL; //So that it is not freed as well
      //We get the reference to pNextPBuf from m_pReadPbuf
      pbuf_free((pbuf*)pBuf);
      pBuf = pNextPBuf;
      rmgLen = pBuf->len;
    }
    else
    {
      pbuf_free((pbuf*)pBuf);
      pBuf = NULL;
      rmgLen = 0;
      m_lInPkt.pop_front();
      break; //No more data to read
    }
  }

  return inLen;
}
Exemple #13
0
  void Beacon::handleListenSocket(Socket &socket)
  {
    SockAddr sourceAddr;
    IpAddr destIpAddr, sourceIpAddr;
    uint8_t ttl;
    BfdPacket packet;
    bool found;
    Session *session = NULL;

    if (!m_packet.DoRecvMsg(socket))
    {
      gLog.ErrnoError(m_packet.GetLastError(), "Error receiving on BFD listen socket");
      return;
    }

    sourceAddr = m_packet.GetSrcAddress();
    if (!LogVerify(sourceAddr.IsValid()))
      return;
    sourceIpAddr = IpAddr(sourceAddr);

    destIpAddr = m_packet.GetDestAddress();
    if (!destIpAddr.IsValid())
    {
      gLog.LogError("Could not get destination address for packet from %s.", sourceAddr.ToString());
      return;
    }

    ttl = m_packet.GetTTLorHops(&found);
    if (!found)
    {
      gLog.LogError("Could not get ttl for packet from %s.", sourceAddr.ToString());
      return;
    }

    LogOptional(Log::Packet, "Received bfd packet %zu bytes from %s to %s", m_packet.GetDataSize(), sourceAddr.ToString(), destIpAddr.ToString());

    //
    // Check ip specific stuff. See draft-ietf-bfd-v4v6-1hop-11.txt
    //

    // Port
    if (m_strictPorts)
    {
      if (sourceAddr.Port() < bfd::MinSourcePort) // max port is max value, so no need to check
      {
        LogOptional(Log::Discard, "Discard packet: bad source port %s to %s", sourceAddr.ToString(), destIpAddr.ToString());
        return;
      }
    }

    // TTL assumes that all control packets are from neighbors.
    if (ttl != 255)
    {
      gLog.Optional(Log::Discard, "Discard packet: bad ttl/hops %hhu", ttl);
      return;
    }

    if (!Session::InitialProcessControlPacket(m_packet.GetData(), m_packet.GetDataSize(), packet))
    {
      gLog.Optional(Log::Discard, "Discard packet");
      return;
    }

    // We have a (partially) valid packet ... now find the correct session.
    if (packet.header.yourDisc != 0)
    {
      DiscMapIt found = m_discMap.find(packet.header.yourDisc);
      if (found == m_discMap.end())
      {
        if (gLog.LogTypeEnabled(Log::DiscardDetail))
          Session::LogPacketContents(packet, false, true, sourceAddr, destIpAddr);

        gLog.Optional(Log::Discard, "Discard packet: no session found for yourDisc <%u>.", packet.header.yourDisc);
        return;
      }
      session = found->second;
      if (session->GetRemoteAddress() != sourceIpAddr)
      {
        if (gLog.LogTypeEnabled(Log::DiscardDetail))
          Session::LogPacketContents(packet, false, true, sourceAddr, destIpAddr);

        LogOptional(Log::Discard, "Discard packet: mismatched yourDisc <%u> and ip <from %s to %s>.", packet.header.yourDisc, sourceAddr.ToString(), destIpAddr.ToString());
        return;
      }
    }
    else
    {
      // No discriminator
      session = findInSourceMap(sourceIpAddr, destIpAddr);
      if (NULL == session)
      {
        // No session yet .. create one !?
        if (!m_allowAnyPassiveIP && m_allowedPassiveIP.find(sourceIpAddr) == m_allowedPassiveIP.end())
        {
          if (gLog.LogTypeEnabled(Log::DiscardDetail))
            Session::LogPacketContents(packet, false, true, sourceAddr, destIpAddr);

          LogOptional(Log::Discard, "Ignoring unauthorized bfd packets from %s",  sourceAddr.ToString());
          return;
        }

        session = addSession(sourceIpAddr, destIpAddr);
        if (!session)
          return;
        if (!session->StartPassiveSession(sourceAddr, destIpAddr))
        {
          gLog.LogError("Failed to add new session for local %s to remote  %s id=%d.", destIpAddr.ToString(), sourceAddr.ToString(), session->GetId());
          KillSession(session);
        }
        LogOptional(Log::Session, "Added new session for local %s to remote  %s id=%d.", destIpAddr.ToString(), sourceAddr.ToString(), session->GetId());
      }
    }

    //
    //  We have a session that can handle the rest.
    //
    session->ProcessControlPacket(packet, sourceAddr.Port());
  }