Example usage for java.net Inet4Address toString

List of usage examples for java.net Inet4Address toString

Introduction

In this page you can find the example usage for java.net Inet4Address toString.

Prototype

public String toString() 

Source Link

Document

Converts this IP address to a String .

Usage

From source file:net.fenyo.mail4hotspot.dao.IpDAOImpl.java

public Ip getIp(final Inet4Address inet4Address) {
    return getIp(inet4Address.toString().replaceFirst(".*/", ""));
}

From source file:net.fenyo.mail4hotspot.service.GeneralServicesImpl.java

@Transactional(readOnly = false)
public Ip createIp(final Inet4Address inet4Address) throws UnknownHostException {
    final Ip transientIp = new Ip();
    transientIp.setIpString(inet4Address.toString().replaceFirst(".*/", ""));
    ipDAO.persist(transientIp);//from  w  ww  .j  a v a  2  s . co m
    entityManager.flush();
    entityManager.detach(transientIp);
    return transientIp;
}

From source file:net.fenyo.mail4hotspot.service.AdvancedServicesImpl.java

public String processQueryFromClient(final String query, final Inet4Address address) {
    boolean should_remove_user_id_processing = false;

    try {//from w  w w. ja v  a2  s.c o  m
        Ip ip = null;
        try {
            ip = generalServices.getIp(address);
        } catch (final NoResultException ex) {
        }
        if (ip != null && ip.isWatch())
            log.info("TRACE: watch ip;process query;" + address.toString() + ";");

        final String[] fields = query.split("");
        final String uuid = fields[0];
        final User user = generalServices.getUserByUuid(uuid);
        final String username = user.getUsername();
        if (ip != null && ip.isWatch())
            log.info("TRACE: watch ip;process query w/ valid username;" + username + ";" + address.toString()
                    + ";");
        if (user.isWatch())
            log.info("TRACE: watch user;process query;" + username + ";" + address.toString() + ";");

        if (fields[1].equals("GetMessage")) {
            if (user.getType() != User.Type.ANONYMOUS && user.getType() != User.Type.INITIALIZE
                    && user.getMessage() != null && !user.getMessage().isEmpty()) {
                log.info("TRACE: message for user;" + username + ";" + user.getMessage() + ";");
                return "" + VpnCode.SRV2CLT_OK + "" + "message for user " + username + ": "
                        + user.getMessage();
            }

            if (ip != null && ip.getMessage() != null && !ip.getMessage().isEmpty()) {
                log.info("TRACE: message for ip;" + ip.getIpString() + ";" + ip.getMessage() + ";");
                return "" + VpnCode.SRV2CLT_OK + "" + "message for anonymous user from IP " + ip.getIpString()
                        + ": " + ip.getMessage();
            }

            return "" + VpnCode.SRV2CLT_OK + "";
        }

        if (user.getType() == User.Type.BLOCKED)
            throw new GeneralException("query from blocked user (username=" + username + ")");
        if ((user.getType() == User.Type.ANONYMOUS || user.getType() == User.Type.INITIALIZE) && ip != null
                && ip.getType() == Ip.Type.BLOCKED)
            throw new GeneralException("query from blocked ip (ip=" + ip.toString() + ")");

        // userAndAccounts contient des entits dtaches (donc si pas d'exception en accdant  userAndAccounts.user.getId() la premire fois, pas de risque en y accdant en sortant)
        final GeneralServices.UserAndAccounts userAndAccounts = generalServices.getUserAndAccountsByUuid(uuid);

        if (fields[1].equals("CheckMails")) {
            log.info("TRACE: CheckMails;" + username + ";" + address.toString() + ";");

            if (user.getType() != User.Type.NORMAL && user.getType() != User.Type.TRIAL)
                throw new GeneralException(
                        "security exception: CheckMails authorized only for NORMAL/TRIAL users (username="
                                + username + ")");

            // si cet utilisateur a par ex t supprim du serveur, il y aura une exception, prise en compte dans le catch final de cette mthode
            if (!validAccount(userAndAccounts.accounts))
                log.warn("invalid number of accounts for " + username);
            else {
                // race condition possible ici : userIdsProcessing n'est mis  jour que dans le thread donc si le GetNMails envoy par le client arrive avant la mise  jour, le client pensera qu'il n'y a pas de nouveau mme alors que la vrification n'a pas commenc 
                final Thread thread = new Thread(new ProcessMailsRunnable(username));
                thread.start();
            }

            return "" + VpnCode.SRV2CLT_START_CHECKING_MAILS + "Start checking mails";
        } else if (fields[1].equals("SendMail")) {
            log.info("TRACE: SendMail;" + username + ";" + address.toString() + ";");

            if (user.getType() != User.Type.NORMAL && user.getType() != User.Type.TRIAL)
                throw new GeneralException(
                        "security exception: SendMail authorized only for NORMAL/TRIAL users (username="
                                + username + ")");

            if (!validAccount(userAndAccounts.accounts)) {
                log.error("invalid number of accounts");
                return "" + VpnCode.SRV2CLT_NO_ACCOUNT;
            } else {
                final Account account = userAndAccounts.accounts.iterator().next();
                final OutboxMail outboxMail = new OutboxMail();
                outboxMail.setToAddr(fields[2]);
                outboxMail.setCcAddr(fields[3]);
                outboxMail.setSubject(fields[4]);
                outboxMail.setContent(fields[5]);
                generalServices.saveOutboxMail(account, outboxMail);
            }

            return "" + VpnCode.SRV2CLT_MAIL_SAVED;
        } else if (fields[1].equals("GetNMails")) {
            log.info("TRACE: GetNMails;" + username + ";" + address.toString() + ";");

            if (user.getType() != User.Type.NORMAL && user.getType() != User.Type.TRIAL)
                throw new GeneralException(
                        "security exception: GetNMails authorized only for NORMAL/TRIAL users (username="
                                + username + ")");

            // si cet utilisateur a par ex t supprim du serveur, il y aura une exception, prise en compte dans le catch final de cette mthode
            if (!validAccount(userAndAccounts.accounts)) {
                log.warn("invalid number of accounts for " + username);
                return "" + VpnCode.SRV2CLT_NO_ACCOUNT;
            }

            try {
                synchronized (userIdsProcessing) {
                    if (userIdsProcessing.contains(userAndAccounts.user.getId())) {
                        //                      log.warn("account is currently processed");
                        return "" + VpnCode.SRV2CLT_CURRENTLY_CHECKING_MAILS + "Currently checking mails";
                    } else {
                        should_remove_user_id_processing = true;
                        userIdsProcessing.add(userAndAccounts.user.getId());

                        final long nmails = generalServices
                                .getUnreadMailsCount(userAndAccounts.accounts.iterator().next());

                        final String provider_error = generalServices
                                .getLastProviderError(userAndAccounts.accounts.iterator().next());
                        return "" + VpnCode.SRV2CLT_NMAILS + "NMails" + "" + nmails + "" + provider_error;
                    }
                }
            } finally {
                synchronized (userIdsProcessing) {
                    if (should_remove_user_id_processing
                            && userIdsProcessing.contains(userAndAccounts.user.getId()))
                        userIdsProcessing.remove(userAndAccounts.user.getId());
                }
            }

        } else if (fields[1].equals("GetNewMail")) {
            log.info("TRACE: GetNewMail;" + username + ";" + address.toString() + ";");

            if (user.getType() != User.Type.NORMAL && user.getType() != User.Type.TRIAL)
                throw new GeneralException(
                        "security exception: GetNewMail authorized only for NORMAL users (username=" + username
                                + ")");

            // si cet utilisateur a par ex t supprim du serveur, il y aura une exception, prise en compte dans le catch final de cette mthode
            if (!validAccount(userAndAccounts.accounts)) {
                log.warn("invalid number of accounts for " + username);
                return "" + VpnCode.SRV2CLT_NO_UNREAD_MAIL + "OK: no unread mail";
            }

            try {
                synchronized (userIdsProcessing) {
                    if (userIdsProcessing.contains(userAndAccounts.user.getId())) {
                        //                      log.warn("account is currently processed");
                        return "" + VpnCode.SRV2CLT_CURRENTLY_CHECKING_MAILS + "Currently checking mails";
                    } else {
                        should_remove_user_id_processing = true;
                        userIdsProcessing.add(userAndAccounts.user.getId());

                        final long nmails = generalServices
                                .getUnreadMailsCount(userAndAccounts.accounts.iterator().next());

                        // pb potentiel  corriger : getLatestUnreadMail passe le mail  read dans la BDD, mais si on plante avant la rception par le client, il ne sera jamais rcupr
                        // il faudrait attendre l'acquittement de ce Message pour passer le mail  read dans la BDD
                        final InboxMail mail = generalServices
                                .getLatestUnreadMail(userAndAccounts.accounts.iterator().next());
                        if (mail == null)
                            return "" + VpnCode.SRV2CLT_NO_UNREAD_MAIL + "OK: no unread mail";
                        else {
                            final String field_from = GenericTools.escapeDelimiter(mail.getFromAddr());
                            final String field_to = GenericTools.escapeDelimiter(mail.getToAddr());
                            final String field_cc = GenericTools.escapeDelimiter(mail.getCcAddr());
                            final String field_message_id = GenericTools.escapeDelimiter(mail.getMessageId());
                            final String field_subject = GenericTools.escapeDelimiter(mail.getSubject());
                            final String field_sent_date = GenericTools
                                    .escapeDelimiter(mail.getSentDate().toString());
                            final String field_received_date = GenericTools
                                    .escapeDelimiter(mail.getReceivedDate().toString());
                            final String field_content = GenericTools.escapeDelimiter(mail.getContent());

                            return "" + VpnCode.SRV2CLT_NEW_MAIL + "New mail" + "" + field_from + ""
                                    + field_to + "" + field_cc + "" + field_message_id + ""
                                    + field_subject + "" + field_sent_date + "" + field_received_date + ""
                                    + field_content + "" + (nmails - 1);
                        }
                    }
                }
            } finally {
                synchronized (userIdsProcessing) {
                    if (should_remove_user_id_processing
                            && userIdsProcessing.contains(userAndAccounts.user.getId()))
                        userIdsProcessing.remove(userAndAccounts.user.getId());
                }
            }

        } else if (fields[1].equals("ConnectSocket")) {
            log.info("TRACE: ConnectSocket;" + username + ";" + fields[2] + ";" + fields[3] + ";"
                    + address.toString() + ";");

            final int remote_port = new Integer(fields[2]);

            // convert IPv4 name to address is necessary
            fields[3] = Inet4Address.getByName(fields[3]).toString().replaceFirst(".*/", "");
            if (fields[3].equals("127.0.0.1")) {
                fields[3] = DOCKER_IP;
                switch (user.getType()) {
                case INITIALIZE:
                case ANONYMOUS:
                    if (!DISABLE_SECURITY && remote_port != 443 && remote_port != 3130)
                        throw new GeneralException("security exception: invalid remote port " + remote_port
                                + " - (username=" + username + ")");
                    break;

                case NORMAL:
                case TRIAL:
                    if (!DISABLE_SECURITY && remote_port != 80 && remote_port != 443 && remote_port != 3128
                            && remote_port != 3129 && remote_port != 3130)
                        throw new GeneralException("security exception: invalid remote port " + remote_port
                                + " - (username=" + username + ")");
                    break;

                case BLOCKED:
                default:
                    throw new GeneralException("should not happen (username=" + username + ")");
                }
            } else {
                // vrifier que c'est unicast et pas rfc1918 et { normal ou trial }
                if (!DISABLE_SECURITY && ((user.getType() == User.Type.ANONYMOUS && remote_port != 22)
                        || (user.getType() != User.Type.ANONYMOUS && user.getType() != User.Type.NORMAL
                                && user.getType() != User.Type.TRIAL)))
                    throw new GeneralException("invalid account type for destination " + fields[3] + ":"
                            + remote_port + " - (username=" + username + ")");
                if (user.getType() == User.Type.ANONYMOUS)
                    log.info(
                            "TRACE: ConnectSocket anonymous ssh;" + fields[3] + ";" + address.toString() + ";");
                final String[] bytes = fields[3].split("\\.");
                if (bytes.length != 4)
                    throw new GeneralException(
                            "invalid address: " + fields[3] + " - (username=" + username + ")");
                for (final String _byte : bytes) {
                    if (!_byte.matches("[0-9]+"))
                        throw new GeneralException(
                                "invalid address: " + fields[3] + " - (username=" + username + ")");
                    if (_byte.length() >= 2 && _byte.matches("0.*"))
                        throw new GeneralException(
                                "invalid address: " + fields[3] + " - (username=" + username + ")");
                    if (new Integer(_byte).intValue() < 0 || new Integer(_byte).intValue() > 255)
                        throw new GeneralException("invalid non RFC-1918 unicast address: " + fields[3]
                                + " - (username=" + username + ")");
                }
                final int[] intvalues = { new Integer(bytes[0]), new Integer(bytes[1]), new Integer(bytes[2]),
                        new Integer(bytes[3]) };
                if (!DISABLE_SECURITY && (intvalues[0] >= 224 || (intvalues[0] == 192 && intvalues[1] == 168)
                        || (intvalues[0] == 172 && intvalues[1] >= 16 && intvalues[1] < 32)
                        || intvalues[0] == 10))
                    throw new GeneralException(
                            "invalid address: " + fields[3] + " - (username=" + username + ")");
            }

            final HttpProxy proxy = HttpProxyFactory.createHttpProxy(uuid, remote_port, fields[3]);
            final int port = proxy.getLocalPort();
            log.info("TRACE: ConnectSocket id;" + username + ";" + fields[2] + ";" + fields[3] + ";" + port
                    + ";" + address.toString() + ";");
            return "" + VpnCode.SRV2CLT_SOCKET_ID + "" + port;

        } else if (fields[1].equals("ClosedSocket")) {
            final int id = new Integer(fields[2]);
            log.info("TRACE: ClosedSocket;" + username + ";" + id + ";" + address.toString() + ";");
            final boolean ret = HttpProxyFactory.removeHttpProxy(id);
            if (ret == false) {
                log.warn("no such id");
                return VpnCode.SRV2CLT_ERROR + "Error: no such id";
            } else
                return VpnCode.SRV2CLT_OK + "OK";
        } else
            return "" + VpnCode.SRV2CLT_NO_SUCH_COMMAND + "Error: no such command";
    } catch (final Exception ex) {
        log.error(ex);
        // pour voir qui gnre cela, suite  une possible attaque
        log.error("address: " + address.toString() + " - query: [" + query + "]");
        ex.printStackTrace();
        return VpnCode.SRV2CLT_EXCEPTION + "Error: exception";
    }
}

From source file:net.fenyo.mail4hotspot.service.AdvancedServicesImpl.java

public BinaryMessageReply processBinaryQueryFromClient(final String query, final byte data[],
        final Inet4Address address) {
    final BinaryMessageReply reply = new BinaryMessageReply();
    reply.reply_data = new byte[] {};

    try {/*from  ww  w  .  j av  a 2 s .c o  m*/
        Ip ip = null;
        try {
            ip = generalServices.getIp(address);
        } catch (final NoResultException ex) {
        }
        if (ip == null) {
            try {
                ip = generalServices.createIp(address);
            } catch (final UnknownHostException ex) {
                log.error(ex);
            }
        }
        if (ip != null && ip.isWatch())
            log.info("TRACE: watch ip;process binary query;" + address.toString() + ";");

        final String[] fields = query.split("");
        final String uuid = fields[0];
        final User user = generalServices.getUserByUuid(uuid);
        final String username = user.getUsername();
        if (ip != null && ip.isWatch())
            log.info("TRACE: watch ip;process binary query w/ valid username;" + username + ";"
                    + address.toString() + ";");
        if (user.isWatch())
            log.info("TRACE: watch user;process binary query;" + username + ";" + address.toString() + ";");
        if (user.getType() == User.Type.BLOCKED)
            throw new GeneralException("binary query from blocked user (username=" + username + ")");
        if ((user.getType() == User.Type.ANONYMOUS || user.getType() == User.Type.INITIALIZE) && ip != null
                && ip.getType() == Ip.Type.BLOCKED)
            throw new GeneralException("binary query from blocked ip (ip=" + ip.getIpString() + ")");

        if (fields[1].equals("SocketData")) {

            if (((user.getType() != User.Type.ANONYMOUS && user.getType() != User.Type.INITIALIZE)
                    && user.isSlowDown())
                    || ((user.getType() == User.Type.ANONYMOUS || user.getType() == User.Type.INITIALIZE)
                            && ip != null && ip.getType() == Ip.Type.SLOWDOWN))
                Thread.sleep(2000);

            final int port = new Integer(fields[2]);
            final HttpProxy proxy = HttpProxyFactory.getHttpProxy(port);
            if (proxy == null) {
                log.warn("bad proxy for user: " + uuid + " - port: " + port);
                reply.reply_string = VpnCode.SRV2CLT_BAD_USER + "Error: bad proxy for this user";
                return reply;
            } else if (!proxy.getUuid().equals(uuid)) {
                log.warn("bad user: uuid=" + uuid + " - proxy uuid=" + proxy.getUuid());
                reply.reply_string = VpnCode.SRV2CLT_BAD_USER + "Error: bad user";
                return reply;
            } else if (user.getType() == User.Type.ANONYMOUS && proxy.getRemotePort() == 22
                    && (System.currentTimeMillis() - proxy.getFirstUse() > 120000)) {
                reply.reply_string = "" + VpnCode.SRV2CLT_EXCEPTION
                        + "Error: anonymous SSH session expired after 2 minutes";
                return reply;
            } else {
                try {
                    reply.reply_data = proxy.receiveData();
                    if (reply.reply_data == null) {
                        if (user.isWatch() || (ip != null && ip.isWatch()))
                            log.info("TRACE: watch binary message;username=" + user.getUsername() + ";ip="
                                    + address.toString() + ";port=" + port
                                    + ";msg=no reply data, closing connection");
                        reply.reply_data = new byte[] {};
                        HttpProxyFactory.removeHttpProxy(proxy.getLocalPort());
                        reply.reply_string = "" + VpnCode.SRV2CLT_EXCEPTION + "Error: EOF";
                        return reply;
                    } else {
                        generalServices.addUserIn(user, reply.reply_data.length);
                        if (ip != null) {
                            generalServices.addIpIn(ip, reply.reply_data.length);
                            if (user.isWatch() || ip.isWatch()) {
                                log.info("TRACE: watch binary message;username=" + user.getUsername() + ";ip="
                                        + address.toString() + ";port=" + port + ";msg=reply data length "
                                        + reply.reply_data.length);
                                String content = "";
                                for (final byte b : reply.reply_data)
                                    content += Integer.toHexString(128 + b) + " ";
                                log.info("binary content:[ " + content + "]");
                                log.info(
                                        "ascii content:["
                                                + java.nio.charset.StandardCharsets.US_ASCII
                                                        .decode(ByteBuffer.wrap(reply.reply_data)).toString()
                                                + "]");
                            }
                        }
                    }
                } catch (final IOException ex) {
                    HttpProxyFactory.removeHttpProxy(proxy.getLocalPort());
                    reply.reply_string = "" + VpnCode.SRV2CLT_EXCEPTION + "Error: exception";
                    return reply;
                }

                try {
                    if (data.length != 0) {
                        proxy.sendData(data);
                        generalServices.addUserOut(user, data.length);
                        if (ip != null) {
                            generalServices.addIpOut(ip, data.length);
                            if (user.isWatch() || ip.isWatch()) {
                                log.info("TRACE: watch binary message;username=" + user.getUsername() + ";ip="
                                        + address.toString() + ";port=" + port + ";msg=sending data length "
                                        + data.length);
                                String content = "";
                                for (final byte b : data)
                                    content += Integer.toHexString(128 + b) + " ";
                                log.info("binary content:[ " + content + "]");
                                log.info("ascii content:[" + java.nio.charset.StandardCharsets.US_ASCII
                                        .decode(ByteBuffer.wrap(data)).toString() + "]");
                            }
                        }
                    }
                } catch (final IOException ex) {
                    reply.reply_string = "" + VpnCode.SRV2CLT_OK + "OK";
                    return reply;
                }

                reply.reply_string = "" + VpnCode.SRV2CLT_OK + "OK";
                return reply;
            }
        } else {
            reply.reply_string = "" + VpnCode.SRV2CLT_NO_SUCH_COMMAND + "Error: no such command";
            return reply;
        }

    } catch (final Exception ex) {
        ex.printStackTrace();
        log.error(ex);
        reply.reply_string = VpnCode.SRV2CLT_EXCEPTION + "Error: exception";
        return reply;
    } finally {
        // log.info("TRACE: SocketData binary message;msg=EXIT FUNCTION");
    }
}