示例#1
1
  private String detectAgentUrl(
      HttpServer pServer, JolokiaServerConfig pConfig, String pContextPath) {
    serverAddress = pServer.getAddress();
    InetAddress realAddress;
    int port;
    if (serverAddress != null) {
      realAddress = serverAddress.getAddress();
      if (realAddress.isAnyLocalAddress()) {
        try {
          realAddress = NetworkUtil.getLocalAddress();
        } catch (IOException e) {
          try {
            realAddress = InetAddress.getLocalHost();
          } catch (UnknownHostException e1) {
            // Ok, ok. We take the original one
            realAddress = serverAddress.getAddress();
          }
        }
      }
      port = serverAddress.getPort();
    } else {
      realAddress = pConfig.getAddress();
      port = pConfig.getPort();
    }

    return String.format(
        "%s://%s:%d%s", pConfig.getProtocol(), realAddress.getHostAddress(), port, pContextPath);
  }
示例#2
0
  static void readConfig() {
    tracker_ip = COConfigurationManager.getStringParameter("Tracker IP", "");

    tracker_ip = UrlUtils.expandIPV6Host(tracker_ip);

    String override_ips = COConfigurationManager.getStringParameter("Override Ip", "");

    StringTokenizer tok = new StringTokenizer(override_ips, ";");

    Map new_override_map = new HashMap();

    while (tok.hasMoreTokens()) {

      String ip = tok.nextToken().trim();

      if (ip.length() > 0) {

        new_override_map.put(AENetworkClassifier.categoriseAddress(ip), ip);
      }
    }

    override_map = new_override_map;

    InetAddress bad = NetworkAdmin.getSingleton().getSingleHomedServiceBindAddress();

    if (bad == null || bad.isAnyLocalAddress()) {

      bind_ip = "";

    } else {

      bind_ip = bad.getHostAddress();
    }
  }
示例#3
0
 protected void processParameters(Collection<ConsoleParameter> parameters) {
   for (ConsoleParameter parameter : parameters) {
     if (parameter.getName().equals("-moduleName")) {
       moduleName = parameter.getValue();
     } else if (parameter.getName().equals("-noprecompile")) {
       this.noPrecompile = true;
     } else if (parameter.getName().equals("-sourceDir")) {
       sourceDir = parameter.getValue();
     } else if (parameter.getName().equals("-bindAddress")) {
       try {
         InetAddress bindAddress = InetAddress.getByName(parameter.getValue());
         if (bindAddress.isAnyLocalAddress()) {
           this.bindAddress = InetAddress.getLocalHost().getHostAddress();
         } else {
           this.bindAddress = parameter.getValue();
         }
       } catch (Exception e) {
         // Use default
       }
     } else if (parameter.getName().equals("-port")) {
       port = Integer.parseInt(parameter.getValue());
     } else if (parameter.getName().equals("-workDir")) {
       workDir = parameter.getValue();
     } else if (parameter.getName().equals("-webDir")) {
       webDir = parameter.getValue();
       launcherDir = parameter.getValue();
       recompileListener = new CodeServerRecompileListener(webDir);
     }
   }
 }
  /** Block datagrams from given source if a memory to receive all datagrams. */
  void block(MembershipKeyImpl key, InetAddress source) throws IOException {
    assert key.channel() == this;
    assert key.sourceAddress() == null;

    synchronized (stateLock) {
      if (!key.isValid()) throw new IllegalStateException("key is no longer valid");
      if (source.isAnyLocalAddress())
        throw new IllegalArgumentException("Source address is a wildcard address");
      if (source.isMulticastAddress())
        throw new IllegalArgumentException("Source address is multicast address");
      if (source.getClass() != key.group().getClass())
        throw new IllegalArgumentException("Source address is different type to group");

      int n;
      if (key instanceof MembershipKeyImpl.Type6) {
        MembershipKeyImpl.Type6 key6 = (MembershipKeyImpl.Type6) key;
        n = Net.block6(fd, key6.groupAddress(), key6.index(), Net.inet6AsByteArray(source));
      } else {
        MembershipKeyImpl.Type4 key4 = (MembershipKeyImpl.Type4) key;
        n = Net.block4(fd, key4.groupAddress(), key4.interfaceAddress(), Net.inet4AsInt(source));
      }
      if (n == IOStatus.UNAVAILABLE) {
        // ancient kernel
        throw new UnsupportedOperationException();
      }
    }
  }
  public boolean connect(SocketAddress sa) throws IOException {
    int trafficClass = 0; // ## Pick up from options
    int localPort = 0;

    synchronized (readLock) {
      synchronized (writeLock) {
        ensureOpenAndUnconnected();
        InetSocketAddress isa = Net.checkAddress(sa);
        SecurityManager sm = System.getSecurityManager();
        if (sm != null) sm.checkConnect(isa.getAddress().getHostAddress(), isa.getPort());
        synchronized (blockingLock()) {
          int n = 0;
          try {
            try {
              begin();
              synchronized (stateLock) {
                if (!isOpen()) {
                  return false;
                }
                readerThread = NativeThread.current();
              }
              for (; ; ) {
                InetAddress ia = isa.getAddress();
                if (ia.isAnyLocalAddress()) ia = InetAddress.getLocalHost();
                n = connectImpl(ia, isa.getPort(), trafficClass);
                if ((n == IOStatus.INTERRUPTED) && isOpen()) continue;
                break;
              }
            } finally {
              readerCleanup();
              end((n > 0) || (n == IOStatus.UNAVAILABLE));
              assert IOStatus.check(n);
            }
          } catch (IOException x) {
            // If an exception was thrown, close the channel after
            // invoking end() so as to avoid bogus
            // AsynchronousCloseExceptions
            close();
            throw x;
          }
          synchronized (stateLock) {
            remoteAddress = isa;
            if (n > 0) {

              // Connection succeeded; disallow further
              // invocation
              state = ST_CONNECTED;
              return true;
            }
            // If nonblocking and no exception then connection
            // pending; disallow another invocation
            if (!isBlocking()) state = ST_PENDING;
            else assert false;
          }
        }
        return false;
      }
    }
  }
 private void bindV4(InputStream in, OutputStream out, InetAddress baddr, int lport)
     throws IOException {
   if (!(baddr instanceof Inet4Address)) {
     throw new SocketException("SOCKS V4 requires IPv4 only addresses");
   }
   super.bind(baddr, lport);
   byte[] addr1 = baddr.getAddress();
   /* Test for AnyLocal */
   InetAddress naddr = baddr;
   if (naddr.isAnyLocalAddress()) {
     naddr = cmdsock.getLocalAddress();
     addr1 = naddr.getAddress();
   }
   out.write(PROTO_VERS4);
   out.write(BIND);
   out.write((super.getLocalPort() >> 8) & 0xff);
   out.write((super.getLocalPort() >> 0) & 0xff);
   out.write(addr1);
   String userName =
       (String)
           java.security.AccessController.doPrivileged(
               new sun.security.action.GetPropertyAction("user.name"));
   try {
     out.write(userName.getBytes("ISO-8859-1"));
   } catch (java.io.UnsupportedEncodingException uee) {
     assert false;
   }
   out.write(0);
   out.flush();
   byte[] data = new byte[8];
   int n = readSocksReply(in, data);
   if (n != 8) throw new SocketException("Reply from SOCKS server has bad length: " + n);
   if (data[0] != 0 && data[0] != 4)
     throw new SocketException("Reply from SOCKS server has bad version");
   SocketException ex = null;
   switch (data[1]) {
     case 90:
       // Success!
       external_address = new InetSocketAddress(baddr, lport);
       break;
     case 91:
       ex = new SocketException("SOCKS request rejected");
       break;
     case 92:
       ex = new SocketException("SOCKS server couldn't reach destination");
       break;
     case 93:
       ex = new SocketException("SOCKS authentication failed");
       break;
     default:
       ex = new SocketException("Reply from SOCKS server contains bad status");
       break;
   }
   if (ex != null) {
     in.close();
     out.close();
     throw ex;
   }
 }
  // TODO: needs to be InetAddress[]
  public InetAddress resolvePublishHostAddresses(String publishHosts[]) throws IOException {
    if (publishHosts == null) {
      if (GLOBAL_NETWORK_PUBLISHHOST_SETTING.exists(settings)
          || GLOBAL_NETWORK_HOST_SETTING.exists(settings)) {
        // if we have settings use them (we have a fallback to GLOBAL_NETWORK_HOST_SETTING inline
        publishHosts =
            GLOBAL_NETWORK_PUBLISHHOST_SETTING.get(settings).toArray(Strings.EMPTY_ARRAY);
      } else {
        // next check any registered custom resolvers
        for (CustomNameResolver customNameResolver : customNameResolvers) {
          InetAddress addresses[] = customNameResolver.resolveDefault();
          if (addresses != null) {
            return addresses[0];
          }
        }
        // we know it's not here. get the defaults
        publishHosts =
            GLOBAL_NETWORK_PUBLISHHOST_SETTING.get(settings).toArray(Strings.EMPTY_ARRAY);
      }
    }

    InetAddress addresses[] = resolveInetAddresses(publishHosts);
    // TODO: allow publishing multiple addresses
    // for now... the hack begins

    // 1. single wildcard address, probably set by network.host: expand to all interface addresses.
    if (addresses.length == 1 && addresses[0].isAnyLocalAddress()) {
      HashSet<InetAddress> all = new HashSet<>(Arrays.asList(NetworkUtils.getAllAddresses()));
      addresses = all.toArray(new InetAddress[all.size()]);
    }

    // 2. try to deal with some (mis)configuration
    for (InetAddress address : addresses) {
      // check if its multicast: flat out mistake
      if (address.isMulticastAddress()) {
        throw new IllegalArgumentException(
            "publish address: {"
                + NetworkAddress.format(address)
                + "} is invalid: multicast address");
      }
      // check if its a wildcard address: this is only ok if its the only address!
      // (if it was a single wildcard address, it was replaced by step 1 above)
      if (address.isAnyLocalAddress()) {
        throw new IllegalArgumentException(
            "publish address: {"
                + NetworkAddress.format(address)
                + "} is wildcard, but multiple addresses specified: this makes no sense");
      }
    }

    // 3. if we end out with multiple publish addresses, select by preference.
    // don't warn the user, or they will get confused by bind_host vs publish_host etc.
    if (addresses.length > 1) {
      List<InetAddress> sorted = new ArrayList<>(Arrays.asList(addresses));
      NetworkUtils.sortAddresses(sorted);
      addresses = new InetAddress[] {sorted.get(0)};
    }
    return addresses[0];
  }
示例#8
0
 protected void addPeer(InetAddress addr, int port) {
   if (!addr.isAnyLocalAddress()) {
     InetSocketAddress address = new InetSocketAddress(addr, port);
     if (!runqueue.contains(address)) {
       runqueue.add(address);
     }
   }
 }
  /**
   * Returns an InetAddress instance that represents the localhost, and that a socket can bind upon
   * or distribute to peers as a contact address.
   *
   * @param intendedDestination the destination that we'd like to use the localhost address with.
   * @return an InetAddress instance representing the local host, and that a socket can bind upon or
   *     distribute to peers as a contact address.
   */
  public synchronized InetAddress getLocalHost(InetAddress intendedDestination) {
    // no point in making sure that the localHostFinderSocket is initialized.
    // better let it through a NullPointerException.
    InetAddress localHost = null;
    localHostFinderSocket.connect(intendedDestination, this.RANDOM_ADDR_DISC_PORT);
    localHost = localHostFinderSocket.getLocalAddress();
    localHostFinderSocket.disconnect();
    // windows socket implementations return the any address so we need to
    // find something else here ... InetAddress.getLocalHost seems to work
    // better on windows so lets hope it'll do the trick.
    if (localHost.isAnyLocalAddress()) {
      try {
        // all that's inside the if is an ugly IPv6 hack
        // (good ol' IPv6 - always causing more problems than it solves.)
        if (intendedDestination instanceof Inet6Address) {
          // return the first globally routable ipv6 address we find
          // on the machine (and hope it's a good one)
          Enumeration interfaces = NetworkInterface.getNetworkInterfaces();

          while (interfaces.hasMoreElements()) {
            NetworkInterface iface = (NetworkInterface) interfaces.nextElement();
            Enumeration addresses = iface.getInetAddresses();
            while (addresses.hasMoreElements()) {
              InetAddress address = (InetAddress) addresses.nextElement();
              if (address instanceof Inet6Address) {
                if (!address.isAnyLocalAddress()
                    && !address.isLinkLocalAddress()
                    && !address.isSiteLocalAddress()
                    && !address.isLoopbackAddress()) {
                  return address;
                }
              }
            }
          }
        } else localHost = InetAddress.getLocalHost();
        /** @todo test on windows for ipv6 cases */
      } catch (Exception ex) {
        // sigh ... ok return 0.0.0.0
        logger.warn("Failed to get localhost ", ex);
      }
    }

    return localHost;
  }
示例#10
0
  /**
   * Given an InetAddress, checks to see if the address is a local address, by comparing the address
   * with all the interfaces on the node.
   *
   * @param addr address to check if it is local node's address
   * @return true if the address corresponds to the local node
   */
  public static boolean isLocalAddress(InetAddress addr) {
    // Check if the address is any local or loop back
    boolean local = addr.isAnyLocalAddress() || addr.isLoopbackAddress();

    // Check if the address is defined on any interface
    if (!local) {
      try {
        local = NetworkInterface.getByInetAddress(addr) != null;
      } catch (SocketException e) {
        local = false;
      }
    }
    return local;
  }
    /*
     * Returns the string representation of the address that this
     * listen key represents.
     */
    public String address() {
      InetAddress address = ss.getInetAddress();

      /*
       * If bound to the wildcard address then use current local
       * hostname. In the event that we don't know our own hostname
       * then assume that host supports IPv4 and return something to
       * represent the loopback address.
       */
      if (address.isAnyLocalAddress()) {
        try {
          address = InetAddress.getLocalHost();
        } catch (UnknownHostException uhe) {
          byte[] loopback = {0x7f, 0x00, 0x00, 0x01};
          try {
            address = InetAddress.getByAddress("127.0.0.1", loopback);
          } catch (UnknownHostException x) {
            throw new InternalError("unable to get local hostname");
          }
        }
      }

      /*
       * Now decide if we return a hostname or IP address. Where possible
       * return a hostname but in the case that we are bound to an
       * address that isn't registered in the name service then we
       * return an address.
       */
      String result;
      String hostname = address.getHostName();
      String hostaddr = address.getHostAddress();
      if (hostname.equals(hostaddr)) {
        if (address instanceof Inet6Address) {
          result = "[" + hostaddr + "]";
        } else {
          result = hostaddr;
        }
      } else {
        result = hostname;
      }

      /*
       * Finally return "hostname:port", "ipv4-address:port" or
       * "[ipv6-address]:port".
       */
      return result + ":" + ss.getLocalPort();
    }
示例#12
0
    public HTTPSession(
        TempFileManager tempFileManager,
        InputStream inputStream,
        OutputStream outputStream,
        InetAddress inetAddress) {
      this.tempFileManager = tempFileManager;
      this.inputStream = new PushbackInputStream(inputStream, BUFSIZE);
      this.outputStream = outputStream;
      String remoteIp =
          inetAddress.isLoopbackAddress() || inetAddress.isAnyLocalAddress()
              ? "127.0.0.1"
              : inetAddress.getHostAddress().toString();
      headers = new HashMap<String, String>();

      headers.put("remote-addr", remoteIp);
      headers.put("http-client-ip", remoteIp);
    }
示例#13
0
 /**
  * Gets the local address to which the socket is bound.
  *
  * <p>If there is a security manager, its <code>checkConnect</code> method is first called with
  * the host address and <code>-1</code> as its arguments to see if the operation is allowed.
  *
  * @see SecurityManager#checkConnect
  * @return the local address to which the socket is bound, <code>null</code> if the socket is
  *     closed, or an <code>InetAddress</code> representing {@link InetAddress#isAnyLocalAddress
  *     wildcard} address if either the socket is not bound, or the security manager <code>
  *     checkConnect</code> method does not allow the operation
  * @since 1.1
  */
 public InetAddress getLocalAddress() {
   if (isClosed()) return null;
   InetAddress in = null;
   try {
     in = (InetAddress) getImpl().getOption(SocketOptions.SO_BINDADDR);
     if (in.isAnyLocalAddress()) {
       in = InetAddress.anyLocalAddress();
     }
     SecurityManager s = System.getSecurityManager();
     if (s != null) {
       s.checkConnect(in.getHostAddress(), -1);
     }
   } catch (Exception e) {
     in = InetAddress.anyLocalAddress(); // "0.0.0.0"
   }
   return in;
 }
示例#14
0
  public static void main(String[] args) {
    if (args.length == 0 || args == null) {
      System.out.println("Didn't enter argument!, Please enter like this.");
      System.out.println("ex. java IPCharateristics args[0] args[1] ...");
      return;
    }
    try {
      InetAddress address = InetAddress.getByName(args[0]);

      if (address.isAnyLocalAddress()) {
        System.out.println(address + " is a wildcard address.");
      }
      if (address.isLoopbackAddress()) {
        System.out.println(address + " is a loopback address.");
      }
      if (address.isLinkLocalAddress()) {
        System.out.println(address + " is a link-local address.");
      }
      if (address.isSiteLocalAddress()) {
        System.out.println(address + " is a site-local address");
      } else {
        System.out.println(address + " is a global address");
      }

      if (address.isMulticastAddress()) {
        if (address.isMCGlobal()) {
          System.out.println(address + " is a global multicast address.");
        } else if (address.isMCOrgLocal()) {
          System.out.println(address + " is an organization wide multicast address.");
        } else if (address.isMCSiteLocal()) {
          System.out.println(address + " is a site wide multicast address.");
        } else if (address.isMCLinkLocal()) {
          System.out.println(address + " is a subnet wide multicast address.");
        } else if (address.isMCNodeLocal()) {
          System.out.println(address + " is an interface-local multicast address.");
        } else {
          System.out.println(address + " is an unknown multicast address type.");
        }
      } else {
        System.out.println(address + " is a unicast address.");
      }
    } catch (UnknownHostException ex) {
      System.out.println("Could not resolve " + args[0]);
    }
  }
  @Override
  public boolean connect(SocketAddress addr) throws IOException {
    int trafficClass = 0;

    ensureOpenAndUnconnected();
    InetSocketAddress isa = LinuxSocketImpl.checkAddress(addr);
    SecurityManager sm = System.getSecurityManager();

    if (sm != null) sm.checkConnect(isa.getAddress().getHostAddress(), isa.getPort());

    synchronized (_regLock) {
      int res = 0;

      try {
        synchronized (_stateLock) {
          if (!isOpen()) {
            return false;
          }
        }

        for (; ; ) {
          InetAddress ia = isa.getAddress();
          if (ia.isAnyLocalAddress()) ia = InetAddress.getLocalHost();
          res = LinuxSocketImpl.connect(_fd, ia, isa.getPort(), trafficClass);
          if ((res == LinuxSocketImpl.INTERRUPTED) && isOpen()) continue;
          break;
        }
      } catch (IOException e) {
        close();
        throw e;
      }

      synchronized (_stateLock) {
        _remoteAddress = isa;
        if (res > 0) {
          _state = State.Connected;
          return true;
        }
        if (!isBlocking()) _state = State.Pending;
        else assert false;
      }
    }

    return false;
  }
  private Pair<String, Integer> validateUrl(String url) throws IllegalArgumentException {
    try {
      URI uri = new URI(url);
      if (!uri.getScheme().equalsIgnoreCase("http") && !uri.getScheme().equalsIgnoreCase("https")) {
        throw new IllegalArgumentException("Unsupported scheme for url");
      }
      int port = uri.getPort();
      if (!(port == 80 || port == 443 || port == -1)) {
        throw new IllegalArgumentException("Only ports 80 and 443 are allowed");
      }

      if (port == -1 && uri.getScheme().equalsIgnoreCase("https")) {
        port = 443;
      } else if (port == -1 && uri.getScheme().equalsIgnoreCase("http")) {
        port = 80;
      }

      String host = uri.getHost();
      try {
        InetAddress hostAddr = InetAddress.getByName(host);
        if (hostAddr.isAnyLocalAddress()
            || hostAddr.isLinkLocalAddress()
            || hostAddr.isLoopbackAddress()
            || hostAddr.isMulticastAddress()) {
          throw new IllegalArgumentException("Illegal host specified in url");
        }
        if (hostAddr instanceof Inet6Address) {
          throw new IllegalArgumentException(
              "IPV6 addresses not supported (" + hostAddr.getHostAddress() + ")");
        }
        return new Pair<String, Integer>(host, port);
      } catch (UnknownHostException uhe) {
        throw new IllegalArgumentException("Unable to resolve " + host);
      }
    } catch (IllegalArgumentException iae) {
      s_logger.warn("Failed uri validation check: " + iae.getMessage());
      throw iae;
    } catch (URISyntaxException use) {
      s_logger.warn("Failed uri syntax check: " + use.getMessage());
      throw new IllegalArgumentException(use.getMessage());
    }
  }
 /**
  * Start the service. Setup a remote domain controller connection and hand it to the server
  * manager.
  *
  * @param context The start context
  * @throws StartException
  */
 public synchronized void start(final StartContext context) throws StartException {
   InetAddress dcAddress = domainControllerAddress.getValue();
   if (dcAddress.isAnyLocalAddress() || dcAddress.isSiteLocalAddress()) {
     try {
       dcAddress = InetAddress.getLocalHost();
     } catch (UnknownHostException e) {
       throw new StartException("Failed to get domain controller address", e);
     }
   }
   final NetworkInterfaceBinding managementInterface = localManagementInterface.getValue();
   domainControllerConnection =
       new RemoteDomainControllerConnection(
           serverManager.getName(),
           dcAddress,
           domainControllerPort.getValue(),
           managementInterface.getAddress(),
           localManagementPort.getValue(),
           localRepository,
           connectTimeout,
           executorService.getValue(),
           threadFactoryValue.getValue());
 }
  /**
   * Resolves {@code bindHosts} to a list of internet addresses. The list will not contain duplicate
   * addresses.
   *
   * @param bindHosts list of hosts to bind to. this may contain special pseudo-hostnames such as
   *     _local_ (see the documentation). if it is null, it will be populated based on global
   *     default settings.
   * @return unique set of internet addresses
   */
  public InetAddress[] resolveBindHostAddresses(String bindHosts[]) throws IOException {
    // first check settings
    if (bindHosts == null) {
      if (GLOBAL_NETWORK_BINDHOST_SETTING.exists(settings)
          || GLOBAL_NETWORK_HOST_SETTING.exists(settings)) {
        // if we have settings use them (we have a fallback to GLOBAL_NETWORK_HOST_SETTING inline
        bindHosts = GLOBAL_NETWORK_BINDHOST_SETTING.get(settings).toArray(Strings.EMPTY_ARRAY);
      } else {
        // next check any registered custom resolvers
        for (CustomNameResolver customNameResolver : customNameResolvers) {
          InetAddress addresses[] = customNameResolver.resolveDefault();
          if (addresses != null) {
            return addresses;
          }
        }
        // we know it's not here. get the defaults
        bindHosts = GLOBAL_NETWORK_BINDHOST_SETTING.get(settings).toArray(Strings.EMPTY_ARRAY);
      }
    }

    InetAddress addresses[] = resolveInetAddresses(bindHosts);

    // try to deal with some (mis)configuration
    for (InetAddress address : addresses) {
      // check if its multicast: flat out mistake
      if (address.isMulticastAddress()) {
        throw new IllegalArgumentException(
            "bind address: {" + NetworkAddress.format(address) + "} is invalid: multicast address");
      }
      // check if its a wildcard address: this is only ok if its the only address!
      if (address.isAnyLocalAddress() && addresses.length > 1) {
        throw new IllegalArgumentException(
            "bind address: {"
                + NetworkAddress.format(address)
                + "} is wildcard, but multiple addresses specified: this makes no sense");
      }
    }
    return addresses;
  }
  /**
   * Connects this socket to the specified remote host address/port.
   *
   * @param anAddr the remote host address to connect to
   * @param aPort the remote port to connect to
   * @param timeout a timeout where supported. 0 means no timeout
   * @throws IOException if an error occurs while connecting
   */
  private void connect(InetAddress anAddr, int aPort, int timeout) throws IOException {

    InetAddress normalAddr = anAddr.isAnyLocalAddress() ? InetAddress.getLocalHost() : anAddr;
    try {
      if (streaming) {
        if (NetUtil.usingSocks(proxy)) {
          socksConnect(anAddr, aPort, 0);
        } else {
          if (timeout == 0) {
            netImpl.connect(fd, trafficClass, normalAddr, aPort);
          } else {
            netImpl.connectStreamWithTimeoutSocket(fd, aPort, timeout, trafficClass, normalAddr);
          }
        }
      } else {
        netImpl.connectDatagram(fd, aPort, trafficClass, normalAddr);
      }
    } catch (ConnectException e) {
      throw new ConnectException(anAddr + ":" + aPort + " - " + e.getMessage());
    }
    super.address = normalAddr;
    super.port = aPort;
  }
示例#20
0
 public static String getRMWebAppHostAndPort(Configuration conf) {
   InetSocketAddress address =
       conf.getSocketAddr(
           YarnConfiguration.RM_WEBAPP_ADDRESS,
           YarnConfiguration.DEFAULT_RM_WEBAPP_ADDRESS,
           YarnConfiguration.DEFAULT_RM_WEBAPP_PORT);
   address = NetUtils.getConnectAddress(address);
   StringBuffer sb = new StringBuffer();
   InetAddress resolved = address.getAddress();
   if (resolved == null || resolved.isAnyLocalAddress() || resolved.isLoopbackAddress()) {
     String lh = address.getHostName();
     try {
       lh = InetAddress.getLocalHost().getCanonicalHostName();
     } catch (UnknownHostException e) {
       // Ignore and fallback.
     }
     sb.append(lh);
   } else {
     sb.append(address.getHostName());
   }
   sb.append(":").append(address.getPort());
   return sb.toString();
 }
示例#21
0
 private static boolean shouldInclude(
     InetAddress ia,
     boolean includeSiteLocal,
     boolean includeLoopbackAndWildcard,
     boolean includeIPv6) {
   return (!ia.isLinkLocalAddress())
       && // 169.254.x.x
       (!ia.isMulticastAddress())
       && (includeLoopbackAndWildcard || ((!ia.isAnyLocalAddress()) && (!ia.isLoopbackAddress())))
       && (includeSiteLocal
           || ((!ia.isSiteLocalAddress())
               &&
               // disallow fc00::/8 and fd00::/8 (Unique local addresses RFC 4193)
               // not recognized as local by InetAddress
               (ia.getAddress().length != 16 || (ia.getAddress()[0] & 0xfe) != 0xfc)))
       &&
       // Hamachi 5/8 allocated to RIPE (30 November 2010)
       // Removed from TransportImpl.isPubliclyRoutable()
       // Check moved to here, for now, but will eventually need to
       // remove it from here also.
       // (includeLocal ||
       // (!ia.getHostAddress().startsWith("5."))) &&
       (includeIPv6 || (ia instanceof Inet4Address));
 }
  private String validateUrl(String url) {
    try {
      URI uri = new URI(url);
      if ((uri.getScheme() == null)
          || (!uri.getScheme().equalsIgnoreCase("http")
              && !uri.getScheme().equalsIgnoreCase("https")
              && !uri.getScheme().equalsIgnoreCase("file"))) {
        throw new IllegalArgumentException("Unsupported scheme for url: " + url);
      }

      int port = uri.getPort();
      if (!(port == 80 || port == 443 || port == -1)) {
        throw new IllegalArgumentException("Only ports 80 and 443 are allowed");
      }
      String host = uri.getHost();
      try {
        InetAddress hostAddr = InetAddress.getByName(host);
        if (hostAddr.isAnyLocalAddress()
            || hostAddr.isLinkLocalAddress()
            || hostAddr.isLoopbackAddress()
            || hostAddr.isMulticastAddress()) {
          throw new IllegalArgumentException("Illegal host specified in url");
        }
        if (hostAddr instanceof Inet6Address) {
          throw new IllegalArgumentException(
              "IPV6 addresses not supported (" + hostAddr.getHostAddress() + ")");
        }
      } catch (UnknownHostException uhe) {
        throw new IllegalArgumentException("Unable to resolve " + host);
      }

      return uri.toString();
    } catch (URISyntaxException e) {
      throw new IllegalArgumentException("Invalid URL " + url);
    }
  }
  public PasswordAuthentication getAuthentication(
      String realm, String protocol, String host, int port) {
    try {
      this_mon.enter();

      String tracker = protocol + "://" + host + ":" + port + "/";

      InetAddress bind_ip = NetworkAdmin.getSingleton().getSingleHomedServiceBindAddress();

      String self_addr;

      // System.out.println( "auth req for " + realm + " - " + tracker );

      if (bind_ip == null || bind_ip.isAnyLocalAddress()) {

        self_addr = "127.0.0.1";

      } else {

        self_addr = bind_ip.getHostAddress();
      }

      // when the tracker is connected to internally we don't want to prompt
      // for the password. Here we return a special user and the password hash
      // which is picked up in the tracker auth code - search for "<internal>"!

      // also include the tracker IP as well as for scrapes these can occur on
      // a raw torrent which hasn't been modified to point to localhost

      if (host.equals(self_addr)
          || host.equals(COConfigurationManager.getStringParameter("Tracker IP", ""))) {

        try {
          byte[] pw = COConfigurationManager.getByteParameter("Tracker Password", new byte[0]);

          String str_pw = new String(Base64.encode(pw));

          return (new PasswordAuthentication("<internal>", str_pw.toCharArray()));

        } catch (Throwable e) {

          Debug.printStackTrace(e);
        }
      }

      String auth_key = realm + ":" + tracker;

      authCache cache = (authCache) auth_cache.get(auth_key);

      if (cache != null) {

        PasswordAuthentication auth = cache.getAuth();

        if (auth != null) {

          return (auth);
        }
      }

      String[] res = getAuthenticationDialog(realm, tracker);

      if (res == null) {

        return (null);

      } else {

        PasswordAuthentication auth = new PasswordAuthentication(res[0], res[1].toCharArray());

        boolean save_pw = res[2].equals("true");

        boolean old_entry_existed =
            auth_cache.put(auth_key, new authCache(auth_key, auth, save_pw)) != null;

        if (save_pw || old_entry_existed) {

          saveAuthCache();
        }

        return (auth);
      }
    } finally {

      this_mon.exit();
    }
  }
示例#24
0
 private static boolean acceptableAddress(InetAddress address) {
   return address != null
       && !address.isLoopbackAddress()
       && !address.isAnyLocalAddress()
       && !address.isLinkLocalAddress();
 }
 /**
  * Binds the socket to the specified address of the specified local port.
  *
  * @param address the address
  * @param port the port
  */
 protected synchronized void bind(InetAddress address, int lport) throws IOException {
   super.bind(address, lport);
   if (address.isAnyLocalAddress()) {
     anyLocalBoundAddr = address;
   }
 }
示例#26
0
 private static boolean isGoodV6Address(InetAddress address) {
   return address instanceof Inet6Address
       && !address.isAnyLocalAddress()
       && !address.isLoopbackAddress()
       && !address.isMulticastAddress();
 }
示例#27
0
  public static void main(String args[]) throws Exception {

    boolean silent = true;
    if (args.length > 0) {
      if (args[0].equals("-d")) {
        silent = false;
      }
    }

    /*
     * Test needs an IPv4 and IPv6 address to run.
     */
    Enumeration nifs = NetworkInterface.getNetworkInterfaces();
    while (nifs.hasMoreElements()) {
      NetworkInterface ni = (NetworkInterface) nifs.nextElement();

      Enumeration addrs = ni.getInetAddresses();
      while (addrs.hasMoreElements()) {
        InetAddress ia = (InetAddress) addrs.nextElement();

        if (ia.isLoopbackAddress() || ia.isAnyLocalAddress()) {
          continue;
        }

        if ((ia instanceof Inet4Address) && (ia4_this == null)) {
          ia4_this = ia;
        }

        if ((ia instanceof Inet6Address) && (ia6_this == null)) {
          ia6_this = ia;
        }
      }
    }

    /*
     * Perform tests on all combinations of IPv4 and IPv6
     * addresses.
     */
    InetAddress addrs[] = {ia4_this, ia6_this};

    Object tests[][] = getTestCombinations();

    for (int i = 0; i < tests.length; i++) {
      Object test[] = tests[i];

      for (int j = 0; j < addrs.length; j++) {
        for (int k = 0; k < addrs.length; k++) {

          if (addrs[j] == null || addrs[k] == null) {
            continue;
          }

          doTest(test, addrs[j], addrs[k], silent);
        }
      }
    }

    System.out.println("");
    System.out.println(count + " test(s) executed. " + failures + " failure(s).");

    if (failures > 0) {
      throw new Exception(failures + " tests(s) failed - see log");
    }
  }
  /** Joins channel's socket to the given group/interface and optional source address. */
  private MembershipKey innerJoin(InetAddress group, NetworkInterface interf, InetAddress source)
      throws IOException {
    if (!group.isMulticastAddress())
      throw new IllegalArgumentException("Group not a multicast address");

    // check multicast address is compatible with this socket
    if (group instanceof Inet4Address) {
      if (family == StandardProtocolFamily.INET6 && !Net.canIPv6SocketJoinIPv4Group())
        throw new IllegalArgumentException("IPv6 socket cannot join IPv4 multicast group");
    } else if (group instanceof Inet6Address) {
      if (family != StandardProtocolFamily.INET6)
        throw new IllegalArgumentException("Only IPv6 sockets can join IPv6 multicast group");
    } else {
      throw new IllegalArgumentException("Address type not supported");
    }

    // check source address
    if (source != null) {
      if (source.isAnyLocalAddress())
        throw new IllegalArgumentException("Source address is a wildcard address");
      if (source.isMulticastAddress())
        throw new IllegalArgumentException("Source address is multicast address");
      if (source.getClass() != group.getClass())
        throw new IllegalArgumentException("Source address is different type to group");
    }

    SecurityManager sm = System.getSecurityManager();
    if (sm != null) sm.checkMulticast(group);

    synchronized (stateLock) {
      if (!isOpen()) throw new ClosedChannelException();

      // check the registry to see if we are already a member of the group
      if (registry == null) {
        registry = new MembershipRegistry();
      } else {
        // return existing membership key
        MembershipKey key = registry.checkMembership(group, interf, source);
        if (key != null) return key;
      }

      MembershipKeyImpl key;
      if ((family == StandardProtocolFamily.INET6)
          && ((group instanceof Inet6Address) || Net.canJoin6WithIPv4Group())) {
        int index = interf.getIndex();
        if (index == -1) throw new IOException("Network interface cannot be identified");

        // need multicast and source address as byte arrays
        byte[] groupAddress = Net.inet6AsByteArray(group);
        byte[] sourceAddress = (source == null) ? null : Net.inet6AsByteArray(source);

        // join the group
        int n = Net.join6(fd, groupAddress, index, sourceAddress);
        if (n == IOStatus.UNAVAILABLE) throw new UnsupportedOperationException();

        key =
            new MembershipKeyImpl.Type6(
                this, group, interf, source, groupAddress, index, sourceAddress);

      } else {
        // need IPv4 address to identify interface
        Inet4Address target = Net.anyInet4Address(interf);
        if (target == null) throw new IOException("Network interface not configured for IPv4");

        int groupAddress = Net.inet4AsInt(group);
        int targetAddress = Net.inet4AsInt(target);
        int sourceAddress = (source == null) ? 0 : Net.inet4AsInt(source);

        // join the group
        int n = Net.join4(fd, groupAddress, targetAddress, sourceAddress);
        if (n == IOStatus.UNAVAILABLE) throw new UnsupportedOperationException();

        key =
            new MembershipKeyImpl.Type4(
                this, group, interf, source, groupAddress, targetAddress, sourceAddress);
      }

      registry.add(key);
      return key;
    }
  }