Example usage for java.net InetAddress equals

List of usage examples for java.net InetAddress equals

Introduction

In this page you can find the example usage for java.net InetAddress equals.

Prototype

public boolean equals(Object obj) 

Source Link

Document

Compares this object against the specified object.

Usage

From source file:com.vuze.plugin.azVPN_Helper.CheckerCommon.java

/**
 * @return rebind sucessful, or rebinding to already bound address
 *//*  ww  w  . j av  a  2s.c  om*/
private final boolean rebindNetworkInterface(NetworkInterface networkInterface, InetAddress onlyToAddress,
        final StringBuilder sReply) {
    vpnIP = onlyToAddress;

    config.setUnsafeBooleanParameter("Enforce Bind IP", true);
    config.setUnsafeBooleanParameter("Check Bind IP On Start", true);
    config.setUnsafeBooleanParameter("Plugin.UPnP.upnp.enable", false);
    config.setUnsafeBooleanParameter("Plugin.UPnP.natpmp.enable", false);

    /**
    if (true) {
       sReply.append("Would rebind to " + networkInterface.getDisplayName()
       + onlyToAddress + "\n");
       return false;
    }
    /**/

    String ifName = networkInterface.getName();

    String configBindIP = config.getCoreStringParameter(PluginConfig.CORE_PARAM_STRING_LOCAL_BIND_IP);

    int bindNetworkInterfaceIndex = -1;
    if (onlyToAddress != null) {
        Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
        for (int j = 0; inetAddresses.hasMoreElements(); j++) {
            InetAddress element = inetAddresses.nextElement();
            if (element.equals(onlyToAddress)) {
                bindNetworkInterfaceIndex = j;
                break;
            }
        }
    }

    if (configBindIP.equals(ifName) || (bindNetworkInterfaceIndex >= 0
            && configBindIP.equals(ifName + "[" + bindNetworkInterfaceIndex + "]"))) {

        addReply(sReply, CHAR_GOOD, "vpnhelper.already.bound.good", new String[] { ifName });
    } else {
        String newConfigBindIP = ifName;
        if (bindNetworkInterfaceIndex >= 0) {
            newConfigBindIP += "[" + bindNetworkInterfaceIndex + "]";
        }

        final AESemaphore sem = new AESemaphore("VPNHelper BindWait");

        NetworkAdmin.getSingleton().addPropertyChangeListener(new NetworkAdminPropertyChangeListener() {
            public void propertyChanged(String property) {
                if (property.equals(NetworkAdmin.PR_DEFAULT_BIND_ADDRESS)) {
                    sem.releaseForever();
                    NetworkAdmin.getSingleton().removePropertyChangeListener(this);

                    addReply(sReply, CHAR_GOOD, "vpnhelper.bind.complete.triggered");
                }
            }
        });

        // I think setting CORE_PARAM_STRING_LOCAL_BIND_IP is actually synchronous
        // We set up a PropertyChangeListener in case it ever becomes asynchronous
        config.setCoreStringParameter(PluginConfig.CORE_PARAM_STRING_LOCAL_BIND_IP, newConfigBindIP);

        addReply(sReply, CHAR_GOOD, "vpnhelper.change.binding",
                new String[] { "" + newConfigBindIP, networkInterface == null ? "null"
                        : networkInterface.getName() + " (" + networkInterface.getDisplayName() + ")" });

        sem.reserve(11000);
        return sem.isReleasedForever();
    }
    return true;
}

From source file:com.vuze.plugin.azVPN_Helper.CheckerCommon.java

public final String calcProtocolAddresses() {
    long now = pi.getUtilities().getCurrentSystemTime();
    StringBuilder sReply = new StringBuilder("Last Checked ")
            .append(pi.getUtilities().getFormatters().formatDate(now)).append("\n");
    // Stolen from NetworkAdminImpl.generateDiagnostics
    // This takes some time (1s-ish), so it's better to do it on demand
    try {/*from  w  w w.j ava2 s. c om*/
        NetworkAdmin networkAdmin = NetworkAdmin.getSingleton();
        AzureusCore azureus_core = AzureusCoreFactory.getSingleton();

        NetworkAdminNetworkInterfaceAddress bindTo = null;
        try {
            NetworkAdminNetworkInterface[] interfaces = networkAdmin.getInterfaces();
            for (NetworkAdminNetworkInterface networkAdminInterface : interfaces) {
                NetworkAdminNetworkInterfaceAddress[] addresses = networkAdminInterface.getAddresses();
                for (NetworkAdminNetworkInterfaceAddress a : addresses) {
                    InetAddress address = a.getAddress();
                    if (address.equals(vpnIP)) {
                        bindTo = a;
                        break;
                    }
                }
            }
        } catch (Throwable e) {
        }

        NetworkAdminProtocol[] protocols = networkAdmin.getOutboundProtocols(azureus_core);

        for (int i = 0; i < protocols.length; i++) {

            NetworkAdminProtocol protocol = protocols[i];

            try {

                //               InetAddress ext_addr = networkAdmin.testProtocol(protocol);
                InetAddress ext_addr = protocol
                        .test(protocol.getType() == NetworkAdminProtocol.PT_HTTP ? null : bindTo);

                String country = null;
                if (ext_addr != null) {

                    List<LocationProvider> locationProviders = pi.getUtilities().getLocationProviders();
                    for (LocationProvider locationProvider : locationProviders) {
                        country = locationProvider.getCountryNameForIP(ext_addr, Locale.getDefault());
                        if (country != null) {
                            break;
                        }
                    }
                }

                addLiteralReply(sReply,
                        protocol.getName() + " - " + ext_addr + (country == null ? "" : " - " + country));

            } catch (NetworkAdminException e) {

                addLiteralReply(sReply, protocol.getName() + " - " + Debug.getNestedExceptionMessage(e));
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
        addReply(sReply, CHAR_BAD, "vpnhelper.nat.error", new String[] { e.toString() });
    }

    lastProtocolAddresses = sReply.toString();

    CheckerListener[] triggers = PluginVPNHelper.instance.getCheckerListeners();
    for (CheckerListener l : triggers) {
        try {
            l.protocolAddressesStatusChanged(lastProtocolAddresses);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return lastProtocolAddresses;
}

From source file:com.vuze.plugin.azVPN_PIA.Checker.java

/**
 * @return rebind sucessful, or rebinding to already bound address
 *///w w w .  ja  va2s.  c  o m
private boolean rebindNetworkInterface(NetworkInterface networkInterface, InetAddress onlyToAddress,
        final StringBuilder sReply) {
    vpnIP = onlyToAddress;

    /**
    if (true) {
       sReply.append("Would rebind to " + networkInterface.getDisplayName()
       + onlyToAddress + "\n");
       return false;
    }
    /**/
    String ifName = networkInterface.getName();

    String configBindIP = config.getCoreStringParameter(PluginConfig.CORE_PARAM_STRING_LOCAL_BIND_IP);

    int bindNetworkInterfaceIndex = -1;
    if (onlyToAddress != null) {
        Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
        for (int j = 0; inetAddresses.hasMoreElements(); j++) {
            InetAddress element = inetAddresses.nextElement();
            if (element.equals(onlyToAddress)) {
                bindNetworkInterfaceIndex = j;
                break;
            }
        }
    }

    if (configBindIP.equals(ifName) || (bindNetworkInterfaceIndex >= 0
            && configBindIP.equals(ifName + "[" + bindNetworkInterfaceIndex + "]"))) {

        addReply(sReply, CHAR_GOOD, "pia.already.bound.good", new String[] { ifName });
    } else {
        String newConfigBindIP = ifName;
        if (bindNetworkInterfaceIndex >= 0) {
            newConfigBindIP += "[" + bindNetworkInterfaceIndex + "]";
        }

        final AESemaphore sem = new AESemaphore("PIA BindWait");

        NetworkAdmin.getSingleton().addPropertyChangeListener(new NetworkAdminPropertyChangeListener() {
            public void propertyChanged(String property) {
                if (property.equals(NetworkAdmin.PR_DEFAULT_BIND_ADDRESS)) {
                    sem.releaseForever();
                    NetworkAdmin.getSingleton().removePropertyChangeListener(this);

                    addReply(sReply, CHAR_GOOD, "pia.bind.complete.triggered");
                }
            }
        });

        // I think setting CORE_PARAM_STRING_LOCAL_BIND_IP is actually synchronous
        // We set up a PropertyChangeListener in case it ever becomes asynchronous
        config.setCoreStringParameter(PluginConfig.CORE_PARAM_STRING_LOCAL_BIND_IP, newConfigBindIP);
        config.setUnsafeBooleanParameter("Enforce Bind IP", true);
        config.setUnsafeBooleanParameter("Check Bind IP On Start", true);

        config.setUnsafeBooleanParameter("upnp.enable", false);
        config.setUnsafeBooleanParameter("natpmp.enable", false);

        addReply(sReply, CHAR_GOOD, "pia.change.binding", new String[] { "" + newConfigBindIP,
                networkInterface.getName() + " (" + networkInterface.getDisplayName() + ")" });

        sem.reserve(11000);
        return sem.isReleasedForever();
    }
    return true;
}

From source file:nl.mindef.c2sc.nbs.olsr.pud.uplink.server.cluster.impl.RelayClusterSenderImpl.java

private void distribute(List<RelayClusterMessage> relayClusterMessages) {
    List<RelayServer> otherRelayServers = this.relayServers.getOtherRelayServers();
    if ((otherRelayServers == null) || (otherRelayServers.size() == 0)) {
        return;/* w  ww .  ja  va  2  s .com*/
    }

    if (this.logger.isDebugEnabled()) {
        this.logger.debug("*** distribute " + relayClusterMessages.size() + " packet(s) to "
                + otherRelayServers.size() + " other relay servers");
    }

    RelayServer me = this.relayServers.getMe();

    InetAddress otherRelayServerIp = null;
    int otherRelayServerPort = -1;
    DatagramPacket p2s = null;
    for (RelayClusterMessage relayClusterMessage : relayClusterMessages) {
        p2s = relayClusterMessage.toWireFormat();
        if (p2s == null) {
            this.logger.error("Could not convert RelayClusterMessage to wire format");
            continue;
        }

        RelayServer relayServerOriginator = relayClusterMessage.getRelayServer();
        for (RelayServer otherRelayServer : otherRelayServers) {
            otherRelayServerIp = otherRelayServer.getIp();
            otherRelayServerPort = otherRelayServer.getPort().intValue();

            /* do not send to relay server from which the message came and also not to myself */
            if (!(otherRelayServerIp.equals(relayServerOriginator.getIp())
                    && (otherRelayServerPort == relayServerOriginator.getPort().intValue()))
                    && !(otherRelayServerIp.equals(me.getIp())
                            && (otherRelayServerPort == this.relayClusterUdpPort))) {
                p2s.setAddress(otherRelayServerIp);
                p2s.setPort(otherRelayServerPort);
                try {
                    if (this.logger.isDebugEnabled()) {
                        this.logger.debug("sending packet to RelayServer " + otherRelayServerIp.getHostAddress()
                                + ":" + otherRelayServerPort);
                    }
                    this.sock.send(p2s);
                } catch (IOException e) {
                    this.logger.error("Could not send to relay server " + otherRelayServerIp.getHostAddress()
                            + ":" + otherRelayServerPort, e);
                }
            } else {
                if (this.logger.isDebugEnabled()) {
                    this.logger.debug("skip sending packet to RelayServer "
                            + relayServerOriginator.getIp().getHostAddress() + ":"
                            + relayServerOriginator.getPort()
                            + " since the packet came from there, or it's me");
                }
            }
        }
    }
}

From source file:jhttpp2.Jhttpp2ClientInputStream.java

/**
 * Handler for the actual HTTP request// w w w . j a  v  a 2  s . co m
 * 
 * @exception IOException
 */
public int read(byte[] a) throws IOException {
    statuscode = Jhttpp2HTTPSession.SC_OK;
    if (ssl)
        return super.read(a);
    boolean cookies_enabled = server.enableCookiesByDefault();
    String rq = "";
    header_length = 0;
    post_data_len = 0;
    content_len = 0;
    boolean start_line = true;
    buf = getLine(); // reads the first line

    while (lread > 2) {
        if (start_line) {
            start_line = false;
            int methodID = server.getHttpMethod(buf);
            switch (methodID) {
            case -1:
                statuscode = Jhttpp2HTTPSession.SC_NOT_SUPPORTED;
                break;
            case 2:
                ssl = true;
            default:
                InetAddress host = parseRequest(buf, methodID);
                if (statuscode != Jhttpp2HTTPSession.SC_OK)
                    break; // error occured, go on with the next line

                if (!server.use_proxy && !ssl) {
                    /* creates a new request without the hostname */
                    buf = method + " " + url + " " + server.getHttpVersion() + "\r\n";
                    lread = buf.length();
                }
                if ((server.use_proxy && connection.notConnected()) || !host.equals(remote_host)) {
                    if (server.debug)
                        server.writeLog("read_f: STATE_CONNECT_TO_NEW_HOST");
                    statuscode = Jhttpp2HTTPSession.SC_CONNECTING_TO_HOST;
                    remote_host = host;
                }
                /*
                 * ------------------------- url blocking (only "GET"
                 * method) -------------------------
                 */
                if (Jhttpp2Server.block_urls && methodID == 0
                        && statuscode != Jhttpp2HTTPSession.SC_FILE_REQUEST) {
                    log.debug("Searching match... for " + this.remote_host_name + url);
                    Jhttpp2URLMatch match = server.findMatch(this.remote_host_name + url);
                    if (match != null) {
                        log.debug("Match found!");
                        cookies_enabled = match.getCookiesEnabled();
                        if (match.getActionIndex() == -1)
                            break;
                        OnURLAction action = server.getURLActions().get(match.getActionIndex());
                        if (action.onAccesssDeny()) {
                            statuscode = Jhttpp2HTTPSession.SC_URL_BLOCKED;
                            if (action.onAccessDenyWithCustomText())
                                errordescription = action.getCustomErrorText();
                        } else if (action.onAccessRedirect()) {
                            statuscode = Jhttpp2HTTPSession.SC_MOVED_PERMANENTLY;
                            errordescription = action.newLocation();
                        }
                    } // end if match!=null)
                } // end if (server.block...
            } // end switch
        } // end if(startline)
        else {
            /*-----------------------------------------------
             * Content-Length parsing
             *-----------------------------------------------*/
            if (server.startsWith(buf.toUpperCase(), "CONTENT-LENGTH")) {
                String clen = buf.substring(16);
                if (clen.indexOf("\r") != -1)
                    clen = clen.substring(0, clen.indexOf("\r"));
                else if (clen.indexOf("\n") != -1)
                    clen = clen.substring(0, clen.indexOf("\n"));
                try {
                    content_len = Integer.parseInt(clen);
                } catch (NumberFormatException e) {
                    statuscode = Jhttpp2HTTPSession.SC_CLIENT_ERROR;
                }
                log.debug("read_f: content_len: " + content_len);
                if (!ssl)
                    body = true; // Note: in HTTP/1.1 any method can have a
                // body, not only "POST"
            } else if (server.startsWith(buf, "Proxy-Connection:")) {
                if (!server.use_proxy)
                    buf = null;
                else {
                    buf = "Proxy-Connection: Keep-Alive\r\n";
                    lread = buf.length();
                }
            }
            /*
             * else if (server.startsWith(buf,"Connection:")) { if
             * (!server.use_proxy) { buf="Connection: Keep-Alive\r\n"; //use
             * always keep-alive lread=buf.length(); } else buf=null; }
             */
            /*-----------------------------------------------
             * cookie crunch section
             *-----------------------------------------------*/
            else if (server.startsWith(buf, "Cookie:")) {
                if (!cookies_enabled)
                    buf = null;
            }
            /*------------------------------------------------
             * Http-Header filtering section
             *------------------------------------------------*/
            else if (server.filter_http) {
                if (server.startsWith(buf, "Referer:")) {// removes
                    // "Referer"
                    buf = null;
                } else if (server.startsWith(buf, "User-Agent")) // changes
                // User-Agent
                {
                    buf = "User-Agent: " + server.getUserAgent() + "\r\n";
                    lread = buf.length();
                }
            }
        }
        if (buf != null) {
            rq += buf;
            if (server.debug)
                server.writeLog(buf);
            header_length += lread;
        }
        buf = getLine();
    }
    rq += buf; // adds last line (should be an empty line) to the header
    // String
    header_length += lread;

    if (header_length == 0) {
        if (server.debug)
            server.writeLog("header_length=0, setting status to SC_CONNECTION_CLOSED (buggy request)");
        statuscode = Jhttpp2HTTPSession.SC_CONNECTION_CLOSED;
    }

    for (int i = 0; i < header_length; i++)
        a[i] = (byte) rq.charAt(i);

    if (body) {// read the body, if "Content-Length" given
        post_data_len = 0;
        while (post_data_len < content_len) {
            a[header_length + post_data_len] = (byte) read(); // writes data
            // into the
            // array
            post_data_len++;
        }
        header_length += content_len; // add the body-length to the
        // header-length
        body = false;
    }

    return (statuscode == Jhttpp2HTTPSession.SC_OK) ? header_length : -1; // return
    // -1
    // with
    // an
    // error
}

From source file:org.parosproxy.paros.core.proxy.ProxyThread.java

private boolean isRecursive(HttpRequestHeader header) {
    try {/*w ww.j av a 2  s  .  c  om*/
        if (header.getHostPort() == inSocket.getLocalPort()) {
            String targetDomain = header.getHostName();
            if (API.API_DOMAIN.equals(targetDomain)) {
                return true;
            }
            InetAddress targetAddress = InetAddress.getByName(targetDomain);
            if (parentServer.getProxyParam().isProxyIpAnyLocalAddress()) {
                if (targetAddress.isLoopbackAddress() || targetAddress.isSiteLocalAddress()
                        || targetAddress.isAnyLocalAddress()) {
                    return true;
                }
            } else if (targetAddress.equals(inSocket.getLocalAddress())) {
                return true;
            }
        }
    } catch (Exception e) {
        // ZAP: Log exceptions
        log.warn(e.getMessage(), e);
    }
    return false;
}

From source file:com.master.metehan.filtereagle.ActivityLog.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    Util.setTheme(this);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.logging);//from  w  w  w  .  ja v  a 2  s . c  o  m
    running = true;

    // Action bar
    View actionView = getLayoutInflater().inflate(R.layout.actionlog, null, false);
    SwitchCompat swEnabled = (SwitchCompat) actionView.findViewById(R.id.swEnabled);

    getSupportActionBar().setDisplayShowCustomEnabled(true);
    getSupportActionBar().setCustomView(actionView);

    getSupportActionBar().setTitle(R.string.menu_log);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    // Get settings
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    resolve = prefs.getBoolean("resolve", false);
    organization = prefs.getBoolean("organization", false);
    boolean log = prefs.getBoolean("log", false);

    // Show disabled message
    TextView tvDisabled = (TextView) findViewById(R.id.tvDisabled);
    tvDisabled.setVisibility(log ? View.GONE : View.VISIBLE);

    // Set enabled switch
    swEnabled.setChecked(log);
    swEnabled.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            prefs.edit().putBoolean("log", isChecked).apply();
        }
    });

    // Listen for preference changes
    prefs.registerOnSharedPreferenceChangeListener(this);

    lvLog = (ListView) findViewById(R.id.lvLog);

    boolean udp = prefs.getBoolean("proto_udp", true);
    boolean tcp = prefs.getBoolean("proto_tcp", true);
    boolean other = prefs.getBoolean("proto_other", true);
    boolean allowed = prefs.getBoolean("traffic_allowed", true);
    boolean blocked = prefs.getBoolean("traffic_blocked", true);

    adapter = new AdapterLog(this, DatabaseHelper.getInstance(this).getLog(udp, tcp, other, allowed, blocked),
            resolve, organization);
    adapter.setFilterQueryProvider(new FilterQueryProvider() {
        public Cursor runQuery(CharSequence constraint) {
            return DatabaseHelper.getInstance(ActivityLog.this).searchLog(constraint.toString());
        }
    });

    lvLog.setAdapter(adapter);

    try {
        vpn4 = InetAddress.getByName(prefs.getString("vpn4", "10.1.10.1"));
        vpn6 = InetAddress.getByName(prefs.getString("vpn6", "fd00:1:fd00:1:fd00:1:fd00:1"));
    } catch (UnknownHostException ex) {
        Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
    }

    lvLog.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            PackageManager pm = getPackageManager();
            Cursor cursor = (Cursor) adapter.getItem(position);
            long time = cursor.getLong(cursor.getColumnIndex("time"));
            int version = cursor.getInt(cursor.getColumnIndex("version"));
            int protocol = cursor.getInt(cursor.getColumnIndex("protocol"));
            final String saddr = cursor.getString(cursor.getColumnIndex("saddr"));
            final int sport = (cursor.isNull(cursor.getColumnIndex("sport")) ? -1
                    : cursor.getInt(cursor.getColumnIndex("sport")));
            final String daddr = cursor.getString(cursor.getColumnIndex("daddr"));
            final int dport = (cursor.isNull(cursor.getColumnIndex("dport")) ? -1
                    : cursor.getInt(cursor.getColumnIndex("dport")));
            final String dname = cursor.getString(cursor.getColumnIndex("dname"));
            final int uid = (cursor.isNull(cursor.getColumnIndex("uid")) ? -1
                    : cursor.getInt(cursor.getColumnIndex("uid")));
            int allowed = (cursor.isNull(cursor.getColumnIndex("allowed")) ? -1
                    : cursor.getInt(cursor.getColumnIndex("allowed")));

            // Get external address
            InetAddress addr = null;
            try {
                addr = InetAddress.getByName(daddr);
            } catch (UnknownHostException ex) {
                Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
            }

            String ip;
            int port;
            if (addr.equals(vpn4) || addr.equals(vpn6)) {
                ip = saddr;
                port = sport;
            } else {
                ip = daddr;
                port = dport;
            }

            // Build popup menu
            PopupMenu popup = new PopupMenu(ActivityLog.this, findViewById(R.id.vwPopupAnchor));
            popup.inflate(R.menu.log);

            // Application name
            if (uid >= 0)
                popup.getMenu().findItem(R.id.menu_application)
                        .setTitle(TextUtils.join(", ", Util.getApplicationNames(uid, ActivityLog.this)));
            else
                popup.getMenu().removeItem(R.id.menu_application);

            // Destination IP
            popup.getMenu().findItem(R.id.menu_protocol)
                    .setTitle(Util.getProtocolName(protocol, version, false));

            // Whois
            final Intent lookupIP = new Intent(Intent.ACTION_VIEW,
                    Uri.parse("http://www.tcpiputils.com/whois-lookup/" + ip));
            if (pm.resolveActivity(lookupIP, 0) == null)
                popup.getMenu().removeItem(R.id.menu_whois);
            else
                popup.getMenu().findItem(R.id.menu_whois).setTitle(getString(R.string.title_log_whois, ip));

            // Lookup port
            final Intent lookupPort = new Intent(Intent.ACTION_VIEW,
                    Uri.parse("http://www.speedguide.net/port.php?port=" + port));
            if (port <= 0 || pm.resolveActivity(lookupPort, 0) == null)
                popup.getMenu().removeItem(R.id.menu_port);
            else
                popup.getMenu().findItem(R.id.menu_port).setTitle(getString(R.string.title_log_port, port));

            if (!prefs.getBoolean("filter", false)) {
                popup.getMenu().removeItem(R.id.menu_allow);
                popup.getMenu().removeItem(R.id.menu_block);
            }

            final Packet packet = new Packet();
            packet.version = version;
            packet.protocol = protocol;
            packet.daddr = daddr;
            packet.dport = dport;
            packet.time = time;
            packet.uid = uid;
            packet.allowed = (allowed > 0);

            // Time
            popup.getMenu().findItem(R.id.menu_time)
                    .setTitle(SimpleDateFormat.getDateTimeInstance().format(time));

            // Handle click
            popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(MenuItem menuItem) {
                    switch (menuItem.getItemId()) {
                    case R.id.menu_application: {
                        Intent main = new Intent(ActivityLog.this, ActivityMain.class);
                        main.putExtra(ActivityMain.EXTRA_SEARCH, Integer.toString(uid));
                        startActivity(main);
                        return true;
                    }

                    case R.id.menu_whois:
                        startActivity(lookupIP);
                        return true;

                    case R.id.menu_port:
                        startActivity(lookupPort);
                        return true;

                    case R.id.menu_allow:
                        if (IAB.isPurchased(ActivityPro.SKU_FILTER, ActivityLog.this)) {
                            DatabaseHelper.getInstance(ActivityLog.this).updateAccess(packet, dname, 0);
                            ServiceSinkhole.reload("allow host", ActivityLog.this);
                            Intent main = new Intent(ActivityLog.this, ActivityMain.class);
                            main.putExtra(ActivityMain.EXTRA_SEARCH, Integer.toString(uid));
                            startActivity(main);
                        } else
                            startActivity(new Intent(ActivityLog.this, ActivityPro.class));
                        return true;

                    case R.id.menu_block:
                        if (IAB.isPurchased(ActivityPro.SKU_FILTER, ActivityLog.this)) {
                            DatabaseHelper.getInstance(ActivityLog.this).updateAccess(packet, dname, 1);
                            ServiceSinkhole.reload("block host", ActivityLog.this);
                            Intent main = new Intent(ActivityLog.this, ActivityMain.class);
                            main.putExtra(ActivityMain.EXTRA_SEARCH, Integer.toString(uid));
                            startActivity(main);
                        } else
                            startActivity(new Intent(ActivityLog.this, ActivityPro.class));
                        return true;

                    default:
                        return false;
                    }
                }
            });

            // Show
            popup.show();
        }
    });

    live = true;
}

From source file:eu.faircode.adblocker.ActivityLog.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    Util.setTheme(this);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.logging);/* w ww.  j  a v a 2  s . c o m*/
    running = true;

    // Action bar
    View actionView = getLayoutInflater().inflate(R.layout.actionlog, null, false);
    SwitchCompat swEnabled = (SwitchCompat) actionView.findViewById(R.id.swEnabled);

    getSupportActionBar().setDisplayShowCustomEnabled(true);
    getSupportActionBar().setCustomView(actionView);

    getSupportActionBar().setTitle(R.string.menu_log);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    // Get settings
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    resolve = prefs.getBoolean("resolve", false);
    organization = prefs.getBoolean("organization", false);
    boolean log = prefs.getBoolean("log", false);

    // Show disabled message
    TextView tvDisabled = (TextView) findViewById(R.id.tvDisabled);
    tvDisabled.setVisibility(log ? View.GONE : View.VISIBLE);

    // Set enabled switch
    swEnabled.setChecked(log);
    swEnabled.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            prefs.edit().putBoolean("log", isChecked).apply();
        }
    });

    // Listen for preference changes
    prefs.registerOnSharedPreferenceChangeListener(this);

    lvLog = (ListView) findViewById(R.id.lvLog);

    boolean udp = prefs.getBoolean("proto_udp", true);
    boolean tcp = prefs.getBoolean("proto_tcp", true);
    boolean other = prefs.getBoolean("proto_other", true);
    boolean allowed = prefs.getBoolean("traffic_allowed", true);
    boolean blocked = prefs.getBoolean("traffic_blocked", true);

    adapter = new AdapterLog(this, DatabaseHelper.getInstance(this).getLog(udp, tcp, other, allowed, blocked),
            resolve, organization);
    adapter.setFilterQueryProvider(new FilterQueryProvider() {
        public Cursor runQuery(CharSequence constraint) {
            return DatabaseHelper.getInstance(ActivityLog.this).searchLog(constraint.toString());
        }
    });

    lvLog.setAdapter(adapter);

    try {
        vpn4 = InetAddress.getByName(prefs.getString("vpn4", "10.1.10.1"));
        vpn6 = InetAddress.getByName(prefs.getString("vpn6", "fd00:1:fd00:1:fd00:1:fd00:1"));
    } catch (UnknownHostException ex) {
        Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
    }

    lvLog.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            PackageManager pm = getPackageManager();
            Cursor cursor = (Cursor) adapter.getItem(position);
            long time = cursor.getLong(cursor.getColumnIndex("time"));
            int version = cursor.getInt(cursor.getColumnIndex("version"));
            int protocol = cursor.getInt(cursor.getColumnIndex("protocol"));
            final String saddr = cursor.getString(cursor.getColumnIndex("saddr"));
            final int sport = (cursor.isNull(cursor.getColumnIndex("sport")) ? -1
                    : cursor.getInt(cursor.getColumnIndex("sport")));
            final String daddr = cursor.getString(cursor.getColumnIndex("daddr"));
            final int dport = (cursor.isNull(cursor.getColumnIndex("dport")) ? -1
                    : cursor.getInt(cursor.getColumnIndex("dport")));
            final String dname = cursor.getString(cursor.getColumnIndex("dname"));
            final int uid = (cursor.isNull(cursor.getColumnIndex("uid")) ? -1
                    : cursor.getInt(cursor.getColumnIndex("uid")));
            int allowed = (cursor.isNull(cursor.getColumnIndex("allowed")) ? -1
                    : cursor.getInt(cursor.getColumnIndex("allowed")));

            // Get external address
            InetAddress addr = null;
            try {
                addr = InetAddress.getByName(daddr);
            } catch (UnknownHostException ex) {
                Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
            }

            String ip;
            int port;
            if (addr.equals(vpn4) || addr.equals(vpn6)) {
                ip = saddr;
                port = sport;
            } else {
                ip = daddr;
                port = dport;
            }

            // Build popup menu
            PopupMenu popup = new PopupMenu(ActivityLog.this, findViewById(R.id.vwPopupAnchor));
            popup.inflate(R.menu.log);

            // Application name
            if (uid >= 0)
                popup.getMenu().findItem(R.id.menu_application)
                        .setTitle(TextUtils.join(", ", Util.getApplicationNames(uid, ActivityLog.this)));
            else
                popup.getMenu().removeItem(R.id.menu_application);

            // Destination IP
            popup.getMenu().findItem(R.id.menu_protocol)
                    .setTitle(Util.getProtocolName(protocol, version, false));

            // Whois
            final Intent lookupIP = new Intent(Intent.ACTION_VIEW,
                    Uri.parse("http://www.tcpiputils.com/whois-lookup/" + ip));
            if (pm.resolveActivity(lookupIP, 0) == null)
                popup.getMenu().removeItem(R.id.menu_whois);
            else
                popup.getMenu().findItem(R.id.menu_whois).setTitle(getString(R.string.title_log_whois, ip));

            // Lookup port
            final Intent lookupPort = new Intent(Intent.ACTION_VIEW,
                    Uri.parse("http://www.speedguide.net/port.php?port=" + port));
            if (port <= 0 || pm.resolveActivity(lookupPort, 0) == null)
                popup.getMenu().removeItem(R.id.menu_port);
            else
                popup.getMenu().findItem(R.id.menu_port).setTitle(getString(R.string.title_log_port, dport));

            if (!prefs.getBoolean("filter", false)) {
                popup.getMenu().removeItem(R.id.menu_allow);
                popup.getMenu().removeItem(R.id.menu_block);
            }

            final Packet packet = new Packet();
            packet.version = version;
            packet.protocol = protocol;
            packet.daddr = daddr;
            packet.dport = dport;
            packet.time = time;
            packet.uid = uid;
            packet.allowed = (allowed > 0);

            // Time
            popup.getMenu().findItem(R.id.menu_time)
                    .setTitle(SimpleDateFormat.getDateTimeInstance().format(time));

            // Handle click
            popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(MenuItem menuItem) {
                    switch (menuItem.getItemId()) {
                    case R.id.menu_application: {
                        Intent main = new Intent(ActivityLog.this, ActivityMain.class);
                        main.putExtra(ActivityMain.EXTRA_SEARCH, Integer.toString(uid));
                        startActivity(main);
                        return true;
                    }

                    case R.id.menu_whois:
                        startActivity(lookupIP);
                        return true;

                    case R.id.menu_port:
                        startActivity(lookupPort);
                        return true;

                    case R.id.menu_allow:
                        if (IAB.isPurchased(ActivityPro.SKU_FILTER, ActivityLog.this)) {
                            DatabaseHelper.getInstance(ActivityLog.this).updateAccess(packet, dname, 0);
                            ServiceSinkhole.reload("allow host", ActivityLog.this);
                            Intent main = new Intent(ActivityLog.this, ActivityMain.class);
                            main.putExtra(ActivityMain.EXTRA_SEARCH, Integer.toString(uid));
                            startActivity(main);
                        } else
                            startActivity(new Intent(ActivityLog.this, ActivityPro.class));
                        return true;

                    case R.id.menu_block:
                        if (IAB.isPurchased(ActivityPro.SKU_FILTER, ActivityLog.this)) {
                            DatabaseHelper.getInstance(ActivityLog.this).updateAccess(packet, dname, 1);
                            ServiceSinkhole.reload("block host", ActivityLog.this);
                            Intent main = new Intent(ActivityLog.this, ActivityMain.class);
                            main.putExtra(ActivityMain.EXTRA_SEARCH, Integer.toString(uid));
                            startActivity(main);
                        } else
                            startActivity(new Intent(ActivityLog.this, ActivityPro.class));
                        return true;

                    default:
                        return false;
                    }
                }
            });

            // Show
            popup.show();
        }
    });

    live = true;
}

From source file:org.opennms.ng.services.capsdconfig.CapsdConfigManager.java

/**
 * {@inheritDoc}/*from w w w  .  j ava2 s. co m*/
 * <p/>
 * Checks the configuration to determine if the target is managed or
 * unmanaged.
 */
@Override
public boolean isAddressUnmanaged(InetAddress target) {
    String managementPolicy = m_config.getManagementPolicy();
    boolean managedByDefault = (managementPolicy == null || managementPolicy.equalsIgnoreCase("managed"));

    boolean found_denial = false;
    boolean found_accept = false;
    List<IpManagement> ipManagements = getIpManagements();
    Iterator<IpManagement> ipIter = ipManagements.iterator();
    while (ipIter.hasNext() && !found_denial) {
        IpManagement mgt = ipIter.next();
        for (String saddr : getSpecifics(mgt)) {
            InetAddress addr;
            addr = InetAddressUtils.addr(saddr);
            if (addr == null) {
                LOG.info("Failed to convert specific address '{}' to an InetAddress.", saddr);
                continue;
            }

            if (addr.equals(target)) {
                if (mgt.getPolicy() == null || mgt.getPolicy().equalsIgnoreCase("managed")) {
                    found_accept = true;
                } else {
                    found_denial = true;
                }

                break;
            }
        }

        // now check the ranges
        List<Range> ranges = getRanges(mgt);
        Iterator<Range> rangeIter = ranges.iterator();
        while (!found_denial && rangeIter.hasNext()) {
            Range range = rangeIter.next();

            InetAddress saddr;
            saddr = InetAddressUtils.addr(range.getBegin());
            if (saddr == null) {
                LOG.info("Failed to convert begin address '{}' to an InetAddress.", range.getBegin());
                continue;
            }

            InetAddress eaddr;
            eaddr = InetAddressUtils.addr(range.getEnd());
            if (eaddr == null) {
                LOG.info("Failed to convert end address '{}' to an InetAddress.", range.getEnd());
                continue;
            }

            int compareStartToTarget = new ByteArrayComparator().compare(saddr.getAddress(),
                    target.getAddress());
            int compareTargetToEnd = new ByteArrayComparator().compare(target.getAddress(), eaddr.getAddress());
            if (compareStartToTarget <= 0 && compareTargetToEnd <= 0) {
                if (mgt.getPolicy() == null || mgt.getPolicy().equalsIgnoreCase("managed")) {
                    found_accept = true;
                } else {
                    found_denial = true;
                }

                break;
            }
        }

        // now check urls
        List<String> includeUrls = getIncludeUrls(mgt);
        Iterator<String> includeUrlIter = includeUrls.iterator();
        boolean match = false;
        while (!found_denial && !match && includeUrlIter.hasNext()) {
            String url = includeUrlIter.next();

            /*
             * Retrieve address list from url map.
             * Iterate over addresses looking for target match.
             */
            for (String saddr : m_urlMap.get(url)) {
                InetAddress addr;
                addr = InetAddressUtils.addr(saddr);
                if (addr == null) {
                    LOG.info("Failed to convert address '{}' from include URL '{}' to an InetAddress.", saddr,
                            url);
                    continue;
                }

                if (addr.equals(target)) {
                    if (mgt.getPolicy() == null || mgt.getPolicy().equalsIgnoreCase("managed")) {
                        found_accept = true;
                    } else {
                        found_denial = true;
                    }

                    match = true;
                    break;
                }
            }
        }
    }

    boolean result = !managedByDefault;
    if (found_denial) {
        result = true;
    } else {
        if (found_accept) {
            result = false;
        }
    }

    return result;
}

From source file:android_network.hetnet.vpn_service.ActivityLog.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    Util.setTheme(this);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.logging);/*  w  w  w  .  jav a2s .com*/
    running = true;

    // Action bar
    View actionView = getLayoutInflater().inflate(R.layout.actionlog, null, false);
    SwitchCompat swEnabled = (SwitchCompat) actionView.findViewById(R.id.swEnabled);

    getSupportActionBar().setDisplayShowCustomEnabled(true);
    getSupportActionBar().setCustomView(actionView);

    getSupportActionBar().setTitle(R.string.menu_log);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    // Get settings
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    resolve = prefs.getBoolean("resolve", false);
    organization = prefs.getBoolean("organization", false);
    boolean log = prefs.getBoolean("log", false);

    // Show disabled message
    TextView tvDisabled = (TextView) findViewById(R.id.tvDisabled);
    tvDisabled.setVisibility(log ? View.GONE : View.VISIBLE);

    // Set enabled switch
    swEnabled.setChecked(log);
    swEnabled.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            prefs.edit().putBoolean("log", isChecked).apply();
        }
    });

    // Listen for preference changes
    prefs.registerOnSharedPreferenceChangeListener(this);

    lvLog = (ListView) findViewById(R.id.lvLog);

    boolean udp = prefs.getBoolean("proto_udp", true);
    boolean tcp = prefs.getBoolean("proto_tcp", true);
    boolean other = prefs.getBoolean("proto_other", true);
    boolean allowed = prefs.getBoolean("traffic_allowed", true);
    boolean blocked = prefs.getBoolean("traffic_blocked", true);

    // -- the adapter holds rows of data entries -> AdapterLog class
    adapter = new AdapterLog(this, DatabaseHelper.getInstance(this).getLog(udp, tcp, other, allowed, blocked),
            resolve, organization);
    adapter.setFilterQueryProvider(new FilterQueryProvider() {
        public Cursor runQuery(CharSequence constraint) {
            return DatabaseHelper.getInstance(ActivityLog.this).searchLog(constraint.toString());
        }
    });

    lvLog.setAdapter(adapter);

    try {
        vpn4 = InetAddress.getByName(prefs.getString("vpn4", "10.1.10.1"));
        vpn6 = InetAddress.getByName(prefs.getString("vpn6", "fd00:1:fd00:1:fd00:1:fd00:1"));
    } catch (UnknownHostException ex) {
        Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
    }

    // -- when clicking the log items
    lvLog.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            PackageManager pm = getPackageManager();
            Cursor cursor = (Cursor) adapter.getItem(position);
            long time = cursor.getLong(cursor.getColumnIndex("time"));
            int version = cursor.getInt(cursor.getColumnIndex("version"));
            int protocol = cursor.getInt(cursor.getColumnIndex("protocol"));
            final String saddr = cursor.getString(cursor.getColumnIndex("saddr"));
            final int sport = (cursor.isNull(cursor.getColumnIndex("sport")) ? -1
                    : cursor.getInt(cursor.getColumnIndex("sport")));
            final String daddr = cursor.getString(cursor.getColumnIndex("daddr"));
            final int dport = (cursor.isNull(cursor.getColumnIndex("dport")) ? -1
                    : cursor.getInt(cursor.getColumnIndex("dport")));
            final String dname = cursor.getString(cursor.getColumnIndex("dname"));
            final int uid = (cursor.isNull(cursor.getColumnIndex("uid")) ? -1
                    : cursor.getInt(cursor.getColumnIndex("uid")));
            int allowed = (cursor.isNull(cursor.getColumnIndex("allowed")) ? -1
                    : cursor.getInt(cursor.getColumnIndex("allowed")));

            // Get external address
            InetAddress addr = null;
            try {
                addr = InetAddress.getByName(daddr);
            } catch (UnknownHostException ex) {
                Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
            }

            String ip;
            int port;
            if (addr.equals(vpn4) || addr.equals(vpn6)) {
                ip = saddr;
                port = sport;
            } else {
                ip = daddr;
                port = dport;
            }

            // Build popup menu
            PopupMenu popup = new PopupMenu(ActivityLog.this, findViewById(R.id.vwPopupAnchor));
            popup.inflate(R.menu.log);

            // Application name
            if (uid >= 0)
                popup.getMenu().findItem(R.id.menu_application)
                        .setTitle(TextUtils.join(", ", Util.getApplicationNames(uid, ActivityLog.this)));
            else
                popup.getMenu().removeItem(R.id.menu_application);

            // Destination IP
            popup.getMenu().findItem(R.id.menu_protocol)
                    .setTitle(Util.getProtocolName(protocol, version, false));

            // Whois
            final Intent lookupIP = new Intent(Intent.ACTION_VIEW,
                    Uri.parse("http://www.tcpiputils.com/whois-lookup/" + ip));
            if (pm.resolveActivity(lookupIP, 0) == null)
                popup.getMenu().removeItem(R.id.menu_whois);
            else
                popup.getMenu().findItem(R.id.menu_whois).setTitle(getString(R.string.title_log_whois, ip));

            // Lookup port
            final Intent lookupPort = new Intent(Intent.ACTION_VIEW,
                    Uri.parse("http://www.speedguide.net/port.php?port=" + port));
            if (port <= 0 || pm.resolveActivity(lookupPort, 0) == null)
                popup.getMenu().removeItem(R.id.menu_port);
            else
                popup.getMenu().findItem(R.id.menu_port).setTitle(getString(R.string.title_log_port, port));

            if (!prefs.getBoolean("filter", false)) {
                popup.getMenu().removeItem(R.id.menu_allow);
                popup.getMenu().removeItem(R.id.menu_block);
            }

            final Packet packet = new Packet();
            packet.version = version;
            packet.protocol = protocol;
            packet.daddr = daddr;
            packet.dport = dport;
            packet.time = time;
            packet.uid = uid;
            packet.allowed = (allowed > 0);

            // Time
            popup.getMenu().findItem(R.id.menu_time)
                    .setTitle(SimpleDateFormat.getDateTimeInstance().format(time));

            // Handle click
            popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(MenuItem menuItem) {
                    switch (menuItem.getItemId()) {
                    case R.id.menu_application: {
                        Intent main = new Intent(ActivityLog.this, MainActivity.class);
                        main.putExtra(MainActivity.EXTRA_SEARCH, Integer.toString(uid));
                        startActivity(main);
                        return true;
                    }

                    case R.id.menu_whois:
                        startActivity(lookupIP);
                        return true;

                    case R.id.menu_port:
                        startActivity(lookupPort);
                        return true;

                    case R.id.menu_allow:
                        if (true) {
                            DatabaseHelper.getInstance(ActivityLog.this).updateAccess(packet, dname, 0);
                            ServiceSinkhole.reload("allow host", ActivityLog.this);
                            Intent main = new Intent(ActivityLog.this, MainActivity.class);
                            main.putExtra(MainActivity.EXTRA_SEARCH, Integer.toString(uid));
                            startActivity(main);
                        }

                        return true;

                    case R.id.menu_block:
                        if (true) {
                            DatabaseHelper.getInstance(ActivityLog.this).updateAccess(packet, dname, 1);
                            ServiceSinkhole.reload("block host", ActivityLog.this);
                            Intent main = new Intent(ActivityLog.this, MainActivity.class);
                            main.putExtra(MainActivity.EXTRA_SEARCH, Integer.toString(uid));
                            startActivity(main);
                        }
                        return true;

                    default:
                        return false;
                    }
                }
            });

            // Show
            popup.show();
        }
    });

    live = true;
}