void
   TCPConnection::StartAsyncConnect_(const String &ip_adress, int port)
   {
      IPAddress adress;
      adress.TryParse(ip_adress, true);

      tcp::endpoint ep;
      ep.address(adress.GetAddress());
      ep.port(port);

      //// Check that we don't try to connect to a port we're listening on. Doing
      //// that could start evil loops.
      //tcp::endpoint endpoint = *endpoint_iterator;

      if (LocalIPAddresses::Instance()->IsLocalPort(ep.address(), remote_port_))
      {
         String sMessage; 
            sMessage.Format(_T("Could not connect to %s on port %d since this would mean connecting to myself."), remote_ip_address_.c_str(), remote_port_);

         OnCouldNotConnect(sMessage);

         LOG_TCPIP(_T("TCPConnection - ") + sMessage);

         return;
      }

      // Attempt a connection to the first endpoint in the list. Each endpoint
      // will be tried until we successfully establish a connection.
      socket_.async_connect(ep,
               std::bind(&TCPConnection::AsyncConnectCompleted, shared_from_this(), std::placeholders::_1));

   }
Exemple #2
0
   IPAddress
   Utilities::GetIPAddressFromReceivedHeader(const String &sReceivedHeader)
   {
      /*
      sFirstPart now contains the following
      received =  "Received"    ":"            ; one per relay
      ["from" domain]           ; sending host
      ["by"   domain]           ; receiving host
      ["via"  atom]             ; physical path
      *("with" atom)             ; link/mail protocol
      ["id"   msg-id]           ; receiver msg id
      ["for"  addr-spec]        ; initial form
      ";"    date-time         ; time received

      http://cr.yp.to/immhf/envelope.html
      In theory, the value of a Received field is tokenizable.
      In practice, SMTP servers put all sorts of badly formatted information into Received lines. 
      Hence: We only do a quick search
      */

      int iFromPos = sReceivedHeader.Find(_T("from "));
      if (iFromPos == -1)
      {
         // Could not locate IP address.
         return IPAddress();
      }

      int iBracketPos = sReceivedHeader.Find(_T("["), iFromPos );
      if (iBracketPos == -1)
      {
         // Could not locate IP address.
         return IPAddress();
      }

      int iByPos = sReceivedHeader.Find(_T("by "));
      if (iByPos >= 0 && iByPos < iBracketPos)
      {
         // Found from but no bracket.
         return IPAddress();
      }

      int iBracketEndPos = sReceivedHeader.Find(_T("]"), iBracketPos);

      int iIPLength = iBracketEndPos - iBracketPos - 1;

      String sIPAddress = sReceivedHeader.Mid(iBracketPos + 1, iIPLength);

      if (!StringParser::IsValidIPAddress(sIPAddress))
      {
         // Could not locate IP address
         assert(0);
         return IPAddress();
      }

      IPAddress address;
      address.TryParse(sIPAddress);

      return address;

   }
   bool 
   DNSResolver::GetPTRRecords(const String &sIP, std::vector<String> &vecFoundNames)
   {
      IPAddress address;
      if (!address.TryParse(AnsiString(sIP), true))
         return false;

      if (address.GetType() == IPAddress::IPV4)
      {
         std::vector<String> vecItems = StringParser::SplitString(sIP, ".");
         reverse(vecItems.begin(), vecItems.end());
         String result = StringParser::JoinVector(vecItems, ".");
         return Resolve_(result + ".in-addr.arpa", vecFoundNames, DNS_TYPE_PTR, 0);
      }
      else
      {
         AnsiString long_ipv6 = address.ToLongString();
         long_ipv6.MakeReverse();
         long_ipv6.Remove(':');

         for (int i = long_ipv6.GetLength() - 1; i > 0; i--)
         {
            long_ipv6.insert(i, 1, '.');
         }

         return Resolve_(long_ipv6 + ".ip6.arpa", vecFoundNames, DNS_TYPE_PTR, 0);
      }


   }
Exemple #4
0
   bool
   Utilities::IsLocalHost(const String &sHostname)
   {
      USES_CONVERSION;

      SOCKADDR_IN addr;
      addr.sin_family = AF_INET;
      addr.sin_addr.s_addr = inet_addr(T2A(sHostname));

      struct hostent *host;

      if(addr.sin_addr.s_addr == INADDR_NONE)
      {
         host = NULL;
         host = gethostbyname(T2A(sHostname));
         if (!host)
            return false;

         memcpy(&addr.sin_addr, host->h_addr_list[0], host->h_length);
      }

      String sIPAddress = GetIPAddress(addr);

      IPAddress address;
      address.TryParse(sIPAddress);

      if (LocalIPAddresses::Instance()->IsLocalIPAddress(address))
         return true;
      else
         return false;

   }
Exemple #5
0
 bool
 TCPIPPort::SetAddress(const String &address)
 {
    IPAddress listeningAddress;
    if (!listeningAddress.TryParse(address))
       return false;
    
    SetAddress(listeningAddress);
    return true;
 }
   bool
   TestConnect::PerformTest(const String  &localAddressStr, const String &server, int port, String &result)
   {
      boost::asio::io_service io_service;

      IPAddress localAddress;
      if (!localAddressStr.IsEmpty())
      {
         if (!localAddress.TryParse(localAddressStr, false))
         {
            result.append(Formatter::Format("ERROR: Unable to parse address {0}.\r\n", localAddressStr));
            return false;
         }
         else
            result.append(Formatter::Format("Local address is {0}.\r\n", localAddress.ToString()));
      }

      result.append(Formatter::Format("Trying to connect to host {0}...\r\n", server));
      

      // Get a list of endpoints corresponding to the server name.
      tcp::resolver resolver(io_service);
      tcp::resolver::query query(AnsiString(server), AnsiString(StringParser::IntToString(port)), tcp::resolver::query::numeric_service);
      boost::system::error_code errorResolve = boost::asio::error::host_not_found;
      tcp::resolver::iterator endpoint_iterator = resolver.resolve(query, errorResolve);
      tcp::resolver::iterator end;

      if (errorResolve || endpoint_iterator == end)
      {
         // Host was not found.
         String formattedString;
         formattedString.Format(_T("ERROR: The host name %s could not be resolved.\r\n"), server);
         
         result.append(formattedString);
         return false;
      }

      // Try each endpoint until we successfully establish a connection.
      tcp::socket socket(io_service);
      boost::system::error_code error = boost::asio::error::host_not_found;
      while (error && endpoint_iterator != end)
      {
         boost::asio::ip::address adr = (*endpoint_iterator).endpoint().address();

         String ipAddressString = adr.to_string();
         String formattedString;
         formattedString.Format(_T("Trying to connect to TCP/IP address %s on port %d.\r\n"), ipAddressString, port);

         result.append(formattedString);

         socket.close();

         IPAddress emptyAddr;
         bool any = emptyAddr.IsAny();

         if (!localAddress.IsAny())
         {
            socket.open(boost::asio::ip::tcp::v4());
            boost::system::error_code tempError;
            socket.bind(boost::asio::ip::tcp::endpoint(localAddress.GetAddress(), 0), tempError);

            if (tempError)
            {
               result.append(Formatter::Format("ERROR: Unable to bind to address {0}.\r\n", localAddress.ToString()));
               socket.close();
               return false;
            }
         }

         socket.connect(*endpoint_iterator++, error);
      }

      if (error)
      {
         // We were unable to connect.
         result.append(_T("ERROR: It was not possible to connect.\r\n"));
         return false;
      }

      // Read the response status line.
      boost::asio::streambuf response;
      boost::asio::read_until(socket, response, "\r\n");

      std::string s;
      std::istream is(&response);
      std::getline(is, s, '\r');
      result.append(Formatter::Format("Received: {0}.\r\n", String(s)));

      // Close the socket again.
      socket.close();

      result.append(_T("Connected successfully.\r\n"));
      return true;

   }
Exemple #7
0
 bool 
 TCPServer::HasIPV6()
 {
    IPAddress address;
    return address.TryParse("::F", false);
 }
   void
   LocalIPAddresses::LoadIPAddresses()
   {
      m_vecLocalPorts.clear();

      std::vector<IPAddress> localAddresses;

      char name[255];

      if( gethostname ( name, sizeof(name)) == 0)
      {
         PHOSTENT hostinfo;
         if((hostinfo = gethostbyname(name)) != NULL)
         {
            int nCount = 0;
            while(hostinfo->h_addr_list[nCount])
            {
               char *ip = inet_ntoa(*(struct in_addr *)hostinfo->h_addr_list[nCount]);
               
               IPAddress address;

               if (address.TryParse(ip))
                  localAddresses.push_back(address);

               nCount++;
            }
         }
      }

      boost::shared_ptr<TCPIPPorts> pTCPIPPorts = Configuration::Instance()->GetTCPIPPorts();

      const vector<boost::shared_ptr<TCPIPPort> > vecTCPIPPorts = pTCPIPPorts->GetVector();

      vector<boost::shared_ptr<TCPIPPort> >::const_iterator iter = vecTCPIPPorts.begin();
      vector<boost::shared_ptr<TCPIPPort> >::const_iterator iterEnd = vecTCPIPPorts.end();
      for (; iter != iterEnd; iter++)
      {
         boost::shared_ptr<TCPIPPort> pTCPIPPort = (*iter);

         if (pTCPIPPort->GetAddress().IsAny())
         {
            int portNumber = pTCPIPPort->GetPortNumber();
            std::vector<IPAddress>::iterator iter = localAddresses.begin(); 
            std::vector<IPAddress>::iterator iterEnd = localAddresses.end();

            for (; iter != iterEnd; iter++)
            {
               IPAddress address = (*iter);

               m_vecLocalPorts.push_back(std::make_pair(address, portNumber));

               m_vecLocalPorts.push_back(std::make_pair(IPAddress(), portNumber));
            }
         }
         else
         {
            m_vecLocalPorts.push_back(std::make_pair(pTCPIPPort->GetAddress(), pTCPIPPort->GetPortNumber()));
         }
      }

      
   }
 bool 
 StringParser::IsValidIPAddress(const String &sAddress)
 {
    IPAddress address;
    return address.TryParse(sAddress, false);
 }
Exemple #10
0
bool
TestConnect::PerformTest(ConnectionSecurity connection_security, const String  &localAddressStr, const String &server, int port, String &result)
{
    std::shared_ptr<IOService> io_service_wrapper = Application::Instance()->GetIOService();

    IPAddress localAddress;
    if (!localAddressStr.IsEmpty())
    {
        if (!localAddress.TryParse(localAddressStr, false))
        {
            result.append(Formatter::Format("ERROR: Unable to parse address {0}.\r\n", localAddressStr));
            return false;
        }
        else
            result.append(Formatter::Format("Local address is {0}.\r\n", localAddress.ToString()));
    }

    result.append(Formatter::Format("Trying to connect to host {0}...\r\n", server));


    // Get a list of endpoints corresponding to the server name.
    tcp::resolver resolver(io_service_wrapper->GetIOService());
    tcp::resolver::query query(AnsiString(server), AnsiString(StringParser::IntToString(port)), tcp::resolver::query::numeric_service);
    boost::system::error_code errorResolve = boost::asio::error::host_not_found;
    tcp::resolver::iterator endpoint_iterator = resolver.resolve(query, errorResolve);
    tcp::resolver::iterator end;

    if (errorResolve || endpoint_iterator == end)
    {
        // Host was not found.
        String formattedString;
        formattedString.Format(_T("ERROR: The host name %s could not be resolved.\r\n"), server.c_str());

        result.append(formattedString);
        return false;
    }

    String last_error_message;

    // Try each endpoint until we successfully establish a connection.
    boost::system::error_code error = boost::asio::error::host_not_found;
    while (error && endpoint_iterator != end)
    {
        boost::asio::ip::address adr = (*endpoint_iterator).endpoint().address();

        String ipAddressString = adr.to_string();
        String formattedString;
        formattedString.Format(_T("Trying to connect to TCP/IP address %s on port %d.\r\n"), ipAddressString.c_str(), port);
        result.append(formattedString);


        std::shared_ptr<Event> disconnectEvent = std::shared_ptr<Event>(new Event());

        std::shared_ptr<TestConnectionResult> connection_result = std::make_shared<TestConnectionResult>();

        std::shared_ptr<TestConnection> connection = std::make_shared<TestConnection>(connection_security, io_service_wrapper->GetIOService(), io_service_wrapper->GetClientContext(), disconnectEvent, server, connection_result);
        if (connection->Connect(ipAddressString, port, localAddress))
        {
            connection.reset();

            disconnectEvent->Wait();

            if (connection_result->GetConnectedSuccesfully())
            {
                result.append(_T("Connected successfully.\r\n"));

                if (connection_security == CSSSL)
                {
                    if (connection_result->GetHandshakeCompletedSuccesfully())
                    {
                        result.append(_T("SSL/TLS handshake completed successfully.\r\n"));
                        return true;
                    }
                    else
                    {
                        result.append(_T("ERROR: Handshake failed.\r\n"));
                        return false;
                    }
                }
                else
                {
                    return true;
                }
            }
            else
            {
                result.append(Formatter::Format("ERROR: It was not possible to connect. Error: {0}.\r\n", connection_result->GetErrorMessage()));
            }
        }

        endpoint_iterator++;
    }

    // We were unable to connect.
    result.append(_T("ERROR: Failed to connect to all servers.\r\n"));
    return false;
}