Example usage for java.net InetAddress isAnyLocalAddress

List of usage examples for java.net InetAddress isAnyLocalAddress

Introduction

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

Prototype

public boolean isAnyLocalAddress() 

Source Link

Document

Utility routine to check if the InetAddress is a wildcard address.

Usage

From source file:org.mobicents.servlet.restcomm.telephony.Call.java

private void onSipServletResponse(SipServletResponse message, ActorRef self, ActorRef sender) throws Exception {
    this.lastResponse = message;

    final int code = message.getStatus();
    switch (code) {
    case SipServletResponse.SC_CALL_BEING_FORWARDED: {
        forwarding(message);//from   ww w  .j  a  va 2  s  .  com
        break;
    }
    case SipServletResponse.SC_RINGING:
    case SipServletResponse.SC_SESSION_PROGRESS: {
        if (!is(ringing)) {
            if (logger.isInfoEnabled()) {
                logger.info("Got 180 Ringing for Call: " + self().path() + " To: " + to + " sender: "
                        + sender.path() + " observers size: " + observers.size());
            }
            fsm.transition(message, ringing);
        }
        break;
    }
    case SipServletResponse.SC_BUSY_HERE:
    case SipServletResponse.SC_BUSY_EVERYWHERE:
    case SipServletResponse.SC_DECLINE: {
        sendCallInfoToObservers();

        //Important. If state is DIALING, then do nothing about the BUSY. If not DIALING state move to failingBusy
        //                // Notify the observers.
        //                external = CallStateChanged.State.BUSY;
        //                final CallStateChanged event = new CallStateChanged(external);
        //                for (final ActorRef observer : observers) {
        //                    observer.tell(event, self);
        //                }

        // XXX shouldnt it move to failingBusy IF dialing ????
        //                if (is(dialing)) {
        //                    break;
        //                } else {
        //                    fsm.transition(message, failingBusy);
        //                }
        fsm.transition(message, failingBusy);
        break;
    }
    case SipServletResponse.SC_UNAUTHORIZED:
    case SipServletResponse.SC_PROXY_AUTHENTICATION_REQUIRED: {
        // Handles Auth for https://bitbucket.org/telestax/telscale-restcomm/issue/132/implement-twilio-sip-out
        if (this.username == null || this.password == null) {
            sendCallInfoToObservers();
            fsm.transition(message, failed);
        } else {
            AuthInfo authInfo = this.factory.createAuthInfo();
            String authHeader = message.getHeader("Proxy-Authenticate");
            if (authHeader == null) {
                authHeader = message.getHeader("WWW-Authenticate");
            }
            String tempRealm = authHeader.substring(authHeader.indexOf("realm=\"") + "realm=\"".length());
            String realm = tempRealm.substring(0, tempRealm.indexOf("\""));
            authInfo.addAuthInfo(message.getStatus(), realm, this.username, this.password);
            SipServletRequest challengeRequest = message.getSession()
                    .createRequest(message.getRequest().getMethod());
            challengeRequest.addAuthHeader(message, authInfo);
            challengeRequest.setContent(this.invite.getContent(), this.invite.getContentType());
            this.invite = challengeRequest;
            // https://github.com/Mobicents/RestComm/issues/147 Make sure we send the SDP again
            this.invite.setContent(message.getRequest().getContent(), "application/sdp");
            challengeRequest.send();
        }
        break;
    }
    // https://github.com/Mobicents/RestComm/issues/148
    // Session in Progress Response should trigger MMS to start the Media Session
    // case SipServletResponse.SC_SESSION_PROGRESS:
    case SipServletResponse.SC_OK: {
        if (is(dialing) || (is(ringing) && !"inbound".equals(direction))) {
            fsm.transition(message, updatingMediaSession);
        }
        break;
    }
    default: {
        if (code >= 400 && code != 487) {
            if (code == 487 && isOutbound()) {
                String initialIpBeforeLB = null;
                String initialPortBeforeLB = null;
                try {
                    initialIpBeforeLB = message.getHeader("X-Sip-Balancer-InitialRemoteAddr");
                    initialPortBeforeLB = message.getHeader("X-Sip-Balancer-InitialRemotePort");
                } catch (Exception e) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Exception during check of LB custom headers for IP address and port");
                    }
                }
                final SipServletRequest ack = message.createAck();
                addCustomHeaders(ack);
                SipSession session = message.getSession();

                if (initialIpBeforeLB != null) {
                    if (initialPortBeforeLB == null)
                        initialPortBeforeLB = "5060";
                    if (logger.isInfoEnabled()) {
                        logger.info("We are behind load balancer, will use: " + initialIpBeforeLB + ":"
                                + initialPortBeforeLB + " for ACK message, ");
                    }
                    String realIP = initialIpBeforeLB + ":" + initialPortBeforeLB;
                    SipURI uri = factory.createSipURI(null, realIP);
                    ack.setRequestURI(uri);
                } else if (!ack.getHeaders("Route").hasNext()) {
                    final SipServletRequest originalInvite = message.getRequest();
                    final SipURI realInetUri = (SipURI) originalInvite.getRequestURI();
                    if ((SipURI) session.getAttribute("realInetUri") == null) {
                        session.setAttribute("realInetUri", realInetUri);
                    }
                    final InetAddress ackRURI = InetAddress.getByName(((SipURI) ack.getRequestURI()).getHost());
                    final int ackRURIPort = ((SipURI) ack.getRequestURI()).getPort();

                    if (realInetUri != null && (ackRURI.isSiteLocalAddress() || ackRURI.isAnyLocalAddress()
                            || ackRURI.isLoopbackAddress()) && (ackRURIPort != realInetUri.getPort())) {
                        if (logger.isInfoEnabled()) {
                            logger.info("Using the real ip address and port of the sip client "
                                    + realInetUri.toString() + " as a request uri of the ACK");
                        }
                        ack.setRequestURI(realInetUri);
                    }
                }
                ack.send();
                if (logger.isInfoEnabled()) {
                    logger.info("Just sent out ACK : " + ack.toString());
                }
            }
            this.fail = true;
            sendCallInfoToObservers();
            fsm.transition(message, stopping);
        }
    }
    }
}

From source file:org.mobicents.servlet.restcomm.telephony.CallManager.java

public void bye(final Object message) throws IOException {
    final ActorRef self = self();
    final SipServletRequest request = (SipServletRequest) message;
    final SipApplicationSession application = request.getApplicationSession();

    // if this response is coming from a client that is in a p2p session with another registered client
    // we will just proxy the response
    SipSession linkedB2BUASession = B2BUAHelper.getLinkedSession(request);
    if (linkedB2BUASession != null) {
        if (logger.isInfoEnabled()) {
            logger.info(String.format("B2BUA: Got BYE request: \n %s", request));
        }/*  w  ww.j  a va  2 s.c  o m*/

        //Prepare the BYE request to the linked session
        request.getSession().setAttribute(B2BUAHelper.B2BUA_LAST_REQUEST, request);
        SipServletRequest clonedBye = linkedB2BUASession.createRequest("BYE");
        linkedB2BUASession.setAttribute(B2BUAHelper.B2BUA_LAST_REQUEST, clonedBye);

        if (patchForNatB2BUASessions) {
            // Issue #307: https://telestax.atlassian.net/browse/RESTCOMM-307
            SipURI toInetUri = (SipURI) request.getSession().getAttribute("toInetUri");
            SipURI fromInetUri = (SipURI) request.getSession().getAttribute("fromInetUri");
            InetAddress byeRURI = null;
            try {
                byeRURI = InetAddress.getByName(((SipURI) clonedBye.getRequestURI()).getHost());
            } catch (UnknownHostException e) {
            }
            if (toInetUri != null && byeRURI == null) {
                if (logger.isInfoEnabled()) {
                    logger.info("Using the real ip address of the sip client " + toInetUri.toString()
                            + " as a request uri of the CloneBye request");
                }
                clonedBye.setRequestURI(toInetUri);
            } else if (toInetUri != null && (byeRURI.isSiteLocalAddress() || byeRURI.isAnyLocalAddress()
                    || byeRURI.isLoopbackAddress())) {
                if (logger.isInfoEnabled()) {
                    logger.info("Using the real ip address of the sip client " + toInetUri.toString()
                            + " as a request uri of the CloneBye request");
                }
                clonedBye.setRequestURI(toInetUri);
            } else if (fromInetUri != null && (byeRURI.isSiteLocalAddress() || byeRURI.isAnyLocalAddress()
                    || byeRURI.isLoopbackAddress())) {
                if (logger.isInfoEnabled()) {
                    logger.info("Using the real ip address of the sip client " + fromInetUri.toString()
                            + " as a request uri of the CloneBye request");
                }
                clonedBye.setRequestURI(fromInetUri);
            } else if (toInetUri == null && (byeRURI.isSiteLocalAddress() || byeRURI.isAnyLocalAddress()
                    || byeRURI.isLoopbackAddress())) {
                if (logger.isInfoEnabled()) {
                    logger.info(
                            "Public IP toInetUri from SipSession is null, will check LB headers from last Response");
                }
                final String initialIpBeforeLB = request.getHeader("X-Sip-Balancer-InitialRemoteAddr");
                String initialPortBeforeLB = request.getHeader("X-Sip-Balancer-InitialRemotePort");
                if (initialIpBeforeLB != null) {
                    if (initialPortBeforeLB == null)
                        initialPortBeforeLB = "5060";
                    if (logger.isInfoEnabled()) {
                        logger.info("We are behind load balancer, will use Initial Remote Address "
                                + initialIpBeforeLB + ":" + initialPortBeforeLB
                                + " for the cloned BYE request");
                    }
                    String realIP = initialIpBeforeLB + ":" + initialPortBeforeLB;
                    SipURI uri = sipFactory.createSipURI(null, realIP);
                    clonedBye.setRequestURI(uri);
                } else {
                    if (logger.isInfoEnabled()) {
                        logger.info("LB Headers are also null");
                    }
                }
            }
        }
        B2BUAHelper.updateCDR(request, CallStateChanged.State.COMPLETED);
        //Prepare 200 OK for received BYE
        SipServletResponse okay = request.createResponse(Response.OK);
        okay.send();
        //Send the Cloned BYE
        if (logger.isInfoEnabled()) {
            logger.info(String.format("B2BUA: Will send out Cloned BYE request: \n %s", clonedBye));
        }
        clonedBye.send();
    } else {
        final ActorRef call = (ActorRef) application.getAttribute(Call.class.getName());
        if (call != null)
            call.tell(request, self);
    }
}

From source file:org.mobicents.servlet.restcomm.telephony.CallManager.java

private void info(final SipServletRequest request) throws IOException {
    final ActorRef self = self();
    final SipApplicationSession application = request.getApplicationSession();

    // if this response is coming from a client that is in a p2p session with another registered client
    // we will just proxy the response
    SipSession linkedB2BUASession = B2BUAHelper.getLinkedSession(request);
    if (linkedB2BUASession != null) {
        if (logger.isInfoEnabled()) {
            logger.info(String.format("B2BUA: Got INFO request: \n %s", request));
        }//www. j a va  2  s . co m
        request.getSession().setAttribute(B2BUAHelper.B2BUA_LAST_REQUEST, request);
        SipServletRequest clonedInfo = linkedB2BUASession.createRequest("INFO");
        linkedB2BUASession.setAttribute(B2BUAHelper.B2BUA_LAST_REQUEST, clonedInfo);

        // Issue #307: https://telestax.atlassian.net/browse/RESTCOMM-307
        SipURI toInetUri = (SipURI) request.getSession().getAttribute("toInetUri");
        SipURI fromInetUri = (SipURI) request.getSession().getAttribute("fromInetUri");
        InetAddress infoRURI = null;
        try {
            infoRURI = InetAddress.getByName(((SipURI) clonedInfo.getRequestURI()).getHost());
        } catch (UnknownHostException e) {
        }
        if (patchForNatB2BUASessions) {
            if (toInetUri != null && infoRURI == null) {

                if (logger.isInfoEnabled()) {
                    logger.info("Using the real ip address of the sip client " + toInetUri.toString()
                            + " as a request uri of the CloneBye request");
                }
                clonedInfo.setRequestURI(toInetUri);
            } else if (toInetUri != null && (infoRURI.isSiteLocalAddress() || infoRURI.isAnyLocalAddress()
                    || infoRURI.isLoopbackAddress())) {

                if (logger.isInfoEnabled()) {
                    logger.info("Using the real ip address of the sip client " + toInetUri.toString()
                            + " as a request uri of the CloneInfo request");
                }
                clonedInfo.setRequestURI(toInetUri);
            } else if (fromInetUri != null && (infoRURI.isSiteLocalAddress() || infoRURI.isAnyLocalAddress()
                    || infoRURI.isLoopbackAddress())) {
                if (logger.isInfoEnabled()) {
                    logger.info("Using the real ip address of the sip client " + fromInetUri.toString()
                            + " as a request uri of the CloneInfo request");
                }

                clonedInfo.setRequestURI(fromInetUri);
            }
        }
        clonedInfo.send();
    } else {
        final ActorRef call = (ActorRef) application.getAttribute(Call.class.getName());
        call.tell(request, self);
    }
}

From source file:org.apache.geode.distributed.internal.InternalLocator.java

/**
 * Creates a new {@code Locator} with the given port, log file, logger, and bind address.
 * //from ww  w. j  a v a2  s .com
 * @param port the tcp/ip port to listen on
 * @param logF the file that log messages should be written to
 * @param stateF the file that state should be read from / written to for recovery
 * @param logWriter a log writer that should be used (logFile parameter is ignored)
 * @param securityLogWriter the log writer to be used for security related log messages
 * @param hostnameForClients the name to give to clients for connecting to this locator
 * @param distributedSystemProperties optional properties to configure the distributed system
 *        (e.g., mcast addr/port, other locators)
 * @param cfg the config if being called from a distributed system; otherwise null.
 * @param startDistributedSystem if true locator will start its own distributed system
 */
private InternalLocator(int port, File logF, File stateF, InternalLogWriter logWriter,
        // LOG: 3 non-null sources: GemFireDistributionLocator, InternalDistributedSystem,
        // LocatorLauncher
        InternalLogWriter securityLogWriter,
        // LOG: 1 non-null source: GemFireDistributionLocator(same instance as logWriter),
        // InternalDistributedSystem
        InetAddress bindAddress, String hostnameForClients, Properties distributedSystemProperties,
        DistributionConfigImpl cfg, boolean startDistributedSystem) {

    // TODO: the following three assignments are already done in superclass
    this.logFile = logF;
    this.bindAddress = bindAddress;
    this.hostnameForClients = hostnameForClients;

    if (stateF == null) {
        this.stateFile = new File("locator" + port + "view.dat");
    } else {
        this.stateFile = stateF;
    }
    File productUseFile = new File("locator" + port + "views.log");
    this.productUseLog = new ProductUseLog(productUseFile);
    this.config = cfg;

    this.env = new Properties();

    // set bind-address explicitly only if not wildcard and let any explicit
    // value in distributedSystemProperties take precedence (#46870)
    if (bindAddress != null && !bindAddress.isAnyLocalAddress()) {
        this.env.setProperty(BIND_ADDRESS, bindAddress.getHostAddress());
    }

    if (distributedSystemProperties != null) {
        this.env.putAll(distributedSystemProperties);
    }
    this.env.setProperty(CACHE_XML_FILE, "");

    // create a DC so that all of the lookup rules, gemfire.properties, etc,
    // are considered and we have a config object we can trust
    if (this.config == null) {
        this.config = new DistributionConfigImpl(this.env);
        this.env.clear();
        this.env.putAll(this.config.getProps());
    }

    final boolean hasLogFileButConfigDoesNot = this.logFile != null
            && this.config.getLogFile().toString().equals(DistributionConfig.DEFAULT_LOG_FILE.toString());
    if (logWriter == null && hasLogFileButConfigDoesNot) {
        // LOG: this is(was) a hack for when logFile and config don't match -- if config specifies a
        // different log-file things will break!
        this.config.unsafeSetLogFile(this.logFile);
    }

    // LOG: create LogWriterAppenders (these are closed at shutdown)
    final boolean hasLogFile = this.config.getLogFile() != null
            && !this.config.getLogFile().equals(new File(""));
    final boolean hasSecurityLogFile = this.config.getSecurityLogFile() != null
            && !this.config.getSecurityLogFile().equals(new File(""));
    LogService.configureLoggers(hasLogFile, hasSecurityLogFile);
    if (hasLogFile || hasSecurityLogFile) {

        if (hasLogFile) {
            // if log-file then create logWriterAppender
            LogWriterAppenders.getOrCreateAppender(LogWriterAppenders.Identifier.MAIN, true, false, this.config,
                    !startDistributedSystem);
        }

        if (hasSecurityLogFile) {
            // if security-log-file then create securityLogWriterAppender
            LogWriterAppenders.getOrCreateAppender(LogWriterAppenders.Identifier.SECURITY, true, false,
                    this.config, false);
        }
        // do not create a LogWriterAppender for security -- let it go through to logWriterAppender
    }

    // LOG: create LogWriters for GemFireTracer (or use whatever was passed in)
    if (logWriter == null) {
        logWriter = LogWriterFactory.createLogWriterLogger(false, false, this.config, false);
        if (logger.isDebugEnabled()) {
            logger.debug("LogWriter for locator is created.");
        }
    }

    if (securityLogWriter == null) {
        securityLogWriter = LogWriterFactory.createLogWriterLogger(false, true, this.config, false);
        logWriter.setLogWriterLevel(this.config.getSecurityLogLevel());
        securityLogWriter.fine("SecurityLogWriter for locator is created.");
    }

    SocketCreatorFactory.setDistributionConfig(this.config);

    this.locatorListener = WANServiceProvider.createLocatorMembershipListener();
    if (this.locatorListener != null) {
        // We defer setting the port until the handler is init'd - that way we'll have an actual port
        // in the case where we're starting with port = 0.
        this.locatorListener.setConfig(getConfig());
    }
    this.handler = new PrimaryHandler(this, locatorListener);

    ThreadGroup group = LoggingThreadGroup.createThreadGroup("Distribution locators", logger);
    this.stats = new LocatorStats();

    this.server = new TcpServerFactory().makeTcpServer(port, this.bindAddress, null, this.config, this.handler,
            new DelayedPoolStatHelper(), group, this.toString(), this);
}

From source file:org.mobicents.servlet.restcomm.telephony.CallManager.java

private void ack(SipServletRequest request) throws IOException {
    SipServletResponse response = B2BUAHelper.getLinkedResponse(request);
    // if this is an ACK that belongs to a B2BUA session, then we proxy it to the other client
    if (response != null) {
        SipServletRequest ack = response.createAck();
        //            if (!ack.getHeaders("Route").hasNext() && patchForNatB2BUASessions) {
        if (patchForNatB2BUASessions) {
            InetAddress ackRURI = null;
            try {
                ackRURI = InetAddress.getByName(((SipURI) ack.getRequestURI()).getHost());
            } catch (UnknownHostException e) {
            }//from  ww  w  .  j av a2s .com
            // Issue #307: https://telestax.atlassian.net/browse/RESTCOMM-307
            SipURI toInetUri = (SipURI) request.getSession().getAttribute("toInetUri");
            if (toInetUri != null && ackRURI == null) {
                if (logger.isInfoEnabled()) {
                    logger.info("Using the real ip address of the sip client " + toInetUri.toString()
                            + " as a request uri of the ACK request");
                }
                ack.setRequestURI(toInetUri);
            } else if (toInetUri != null && (ackRURI.isSiteLocalAddress() || ackRURI.isAnyLocalAddress()
                    || ackRURI.isLoopbackAddress())) {
                if (logger.isInfoEnabled()) {
                    logger.info("Using the real ip address of the sip client " + toInetUri.toString()
                            + " as a request uri of the ACK request");
                }
                ack.setRequestURI(toInetUri);
            } else if (toInetUri == null && (ackRURI.isSiteLocalAddress() || ackRURI.isAnyLocalAddress()
                    || ackRURI.isLoopbackAddress())) {
                if (logger.isInfoEnabled()) {
                    logger.info(
                            "Public IP toInetUri from SipSession is null, will check LB headers from last Response");
                }
                final String initialIpBeforeLB = response.getHeader("X-Sip-Balancer-InitialRemoteAddr");
                String initialPortBeforeLB = response.getHeader("X-Sip-Balancer-InitialRemotePort");
                if (initialIpBeforeLB != null) {
                    if (initialPortBeforeLB == null)
                        initialPortBeforeLB = "5060";
                    if (logger.isInfoEnabled()) {
                        logger.info("We are behind load balancer, will use Initial Remote Address "
                                + initialIpBeforeLB + ":" + initialPortBeforeLB + " for the ACK request");
                    }
                    String realIP = initialIpBeforeLB + ":" + initialPortBeforeLB;
                    SipURI uri = sipFactory.createSipURI(null, realIP);
                    ack.setRequestURI(uri);
                } else {
                    if (logger.isInfoEnabled()) {
                        logger.info("LB Headers are also null");
                    }
                }
            }
        }
        ack.send();
        SipApplicationSession sipApplicationSession = request.getApplicationSession();
        // Defaulting the sip application session to 1h
        sipApplicationSession.setExpires(60);
    } else {
        if (logger.isInfoEnabled()) {
            logger.info("Linked Response couldn't be found for ACK request");
        }
        final ActorRef call = (ActorRef) request.getApplicationSession().getAttribute(Call.class.getName());
        if (call != null) {
            if (logger.isInfoEnabled()) {
                logger.info("Will send ACK to call actor: " + call.path());
            }
            call.tell(request, self());
        }
    }
    // else {
    // SipSession sipSession = request.getSession();
    // SipApplicationSession sipAppSession = request.getApplicationSession();
    // if(sipSession.getInvalidateWhenReady()){
    // logger.info("Invalidating sipSession: "+sipSession.getId());
    // sipSession.invalidate();
    // }
    // if(sipAppSession.getInvalidateWhenReady()){
    // logger.info("Invalidating sipAppSession: "+sipAppSession.getId());
    // sipAppSession.invalidate();
    // }
    // }
}

From source file:org.apache.hadoop.hdfs.DFSClient.java

private static boolean isLocalAddress(InetSocketAddress targetAddr) {
    InetAddress addr = targetAddr.getAddress();
    if (localIpAddresses.contains(addr.getHostAddress())) {
        if (LOG.isTraceEnabled()) {
            LOG.trace("Address " + targetAddr + " is local");
        }/*  www . j  a  v a 2 s. c o m*/
        return true;
    }

    // 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;
        }
    }
    if (LOG.isTraceEnabled()) {
        LOG.trace("Address " + targetAddr + " is local");
    }
    if (local == true) {
        localIpAddresses.add(addr.getHostAddress());
    }
    return local;
}

From source file:org.restcomm.connect.telephony.Call.java

private void onSipServletResponse(SipServletResponse message, ActorRef self, ActorRef sender) throws Exception {
    this.lastResponse = message;

    final int code = message.getStatus();
    switch (code) {
    case SipServletResponse.SC_CALL_BEING_FORWARDED: {
        forwarding(message);/*from   ww w  .j a  v  a 2s.  c  om*/
        break;
    }
    case SipServletResponse.SC_RINGING:
    case SipServletResponse.SC_SESSION_PROGRESS: {
        if (!is(ringing)) {
            if (logger.isInfoEnabled()) {
                logger.info("Got 180 Ringing for Call: " + self().path() + " To: " + to + " sender: "
                        + sender.path() + " observers size: " + observers.size());
            }
            fsm.transition(message, ringing);
        }
        break;
    }
    case SipServletResponse.SC_BUSY_HERE:
    case SipServletResponse.SC_BUSY_EVERYWHERE:
    case SipServletResponse.SC_DECLINE: {
        sendCallInfoToObservers();

        //Important. If state is DIALING, then do nothing about the BUSY. If not DIALING state move to failingBusy
        //                // Notify the observers.
        //                external = CallStateChanged.State.BUSY;
        //                final CallStateChanged event = new CallStateChanged(external);
        //                for (final ActorRef observer : observers) {
        //                    observer.tell(event, self);
        //                }

        // XXX shouldnt it move to failingBusy IF dialing ????
        //                if (is(dialing)) {
        //                    break;
        //                } else {
        //                    fsm.transition(message, failingBusy);
        //                }
        if (!is(failingNoAnswer))
            fsm.transition(message, failingBusy);
        break;
    }
    case SipServletResponse.SC_UNAUTHORIZED:
    case SipServletResponse.SC_PROXY_AUTHENTICATION_REQUIRED: {
        // Handles Auth for https://bitbucket.org/telestax/telscale-restcomm/issue/132/implement-twilio-sip-out
        if ((this.username != null || this.username.isEmpty())
                && (this.password != null && this.password.isEmpty())) {
            sendCallInfoToObservers();
            fsm.transition(message, failed);
        } else {
            AuthInfo authInfo = this.factory.createAuthInfo();
            String authHeader = message.getHeader("Proxy-Authenticate");
            if (authHeader == null) {
                authHeader = message.getHeader("WWW-Authenticate");
            }
            String tempRealm = authHeader.substring(authHeader.indexOf("realm=\"") + "realm=\"".length());
            String realm = tempRealm.substring(0, tempRealm.indexOf("\""));
            authInfo.addAuthInfo(message.getStatus(), realm, this.username, this.password);
            SipServletRequest challengeRequest = message.getSession()
                    .createRequest(message.getRequest().getMethod());
            challengeRequest.addAuthHeader(message, authInfo);
            challengeRequest.setContent(this.invite.getContent(), this.invite.getContentType());
            this.invite = challengeRequest;
            // https://github.com/Mobicents/RestComm/issues/147 Make sure we send the SDP again
            this.invite.setContent(message.getRequest().getContent(), "application/sdp");
            if (outboundToIms) {
                final SipURI uri = factory.createSipURI(null, imsProxyAddress);
                uri.setPort(imsProxyPort);
                uri.setLrParam(true);
                challengeRequest.pushRoute(uri);
            }
            challengeRequest.send();
        }
        break;
    }
    // https://github.com/Mobicents/RestComm/issues/148
    // Session in Progress Response should trigger MMS to start the Media Session
    // case SipServletResponse.SC_SESSION_PROGRESS:
    case SipServletResponse.SC_OK: {
        if (is(dialing) || (is(ringing) && !"inbound".equals(direction))) {
            fsm.transition(message, updatingMediaSession);
        }
        break;
    }
    default: {
        if (code >= 400 && code != 487) {
            if (code == 487 && isOutbound()) {
                String initialIpBeforeLB = null;
                String initialPortBeforeLB = null;
                try {
                    initialIpBeforeLB = message.getHeader("X-Sip-Balancer-InitialRemoteAddr");
                    initialPortBeforeLB = message.getHeader("X-Sip-Balancer-InitialRemotePort");
                } catch (Exception e) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Exception during check of LB custom headers for IP address and port");
                    }
                }
                final SipServletRequest ack = message.createAck();
                addCustomHeaders(ack);
                SipSession session = message.getSession();

                if (initialIpBeforeLB != null) {
                    if (initialPortBeforeLB == null)
                        initialPortBeforeLB = "5060";
                    if (logger.isInfoEnabled()) {
                        logger.info("We are behind load balancer, will use: " + initialIpBeforeLB + ":"
                                + initialPortBeforeLB + " for ACK message, ");
                    }
                    String realIP = initialIpBeforeLB + ":" + initialPortBeforeLB;
                    SipURI uri = factory.createSipURI(((SipURI) ack.getRequestURI()).getUser(), realIP);

                    ack.setRequestURI(uri);
                } else if (!ack.getHeaders("Route").hasNext()) {
                    final SipServletRequest originalInvite = message.getRequest();
                    final SipURI realInetUri = (SipURI) originalInvite.getRequestURI();
                    if ((SipURI) session.getAttribute("realInetUri") == null) {
                        session.setAttribute("realInetUri", realInetUri);
                    }
                    final InetAddress ackRURI = InetAddress.getByName(((SipURI) ack.getRequestURI()).getHost());
                    final int ackRURIPort = ((SipURI) ack.getRequestURI()).getPort();

                    if (realInetUri != null && (ackRURI.isSiteLocalAddress() || ackRURI.isAnyLocalAddress()
                            || ackRURI.isLoopbackAddress()) && (ackRURIPort != realInetUri.getPort())) {
                        if (logger.isInfoEnabled()) {
                            logger.info("Using the real ip address and port of the sip client "
                                    + realInetUri.toString() + " as a request uri of the ACK");
                        }

                        realInetUri.setUser(((SipURI) ack.getRequestURI()).getUser());
                        ack.setRequestURI(realInetUri);
                    }
                }
                ack.send();
                if (logger.isInfoEnabled()) {
                    logger.info("Just sent out ACK : " + ack.toString());
                }
            }
            this.fail = true;
            fsm.transition(message, stopping);
        }
    }
    }
}

From source file:org.restcomm.connect.telephony.CallManager.java

private void info(final SipServletRequest request) throws IOException {
    final ActorRef self = self();
    final SipApplicationSession application = request.getApplicationSession();

    // if this response is coming from a client that is in a p2p session with another registered client
    // we will just proxy the response
    SipSession linkedB2BUASession = B2BUAHelper.getLinkedSession(request);
    if (linkedB2BUASession != null) {
        if (logger.isInfoEnabled()) {
            logger.info(String.format("B2BUA: Got INFO request: \n %s", request));
        }//w  w w .  j a  v a  2  s . c o  m
        request.getSession().setAttribute(B2BUAHelper.B2BUA_LAST_REQUEST, request);
        SipServletRequest clonedInfo = linkedB2BUASession.createRequest("INFO");
        linkedB2BUASession.setAttribute(B2BUAHelper.B2BUA_LAST_REQUEST, clonedInfo);

        // Issue #307: https://telestax.atlassian.net/browse/RESTCOMM-307
        SipURI toInetUri = (SipURI) request.getSession().getAttribute(B2BUAHelper.TO_INET_URI);
        SipURI fromInetUri = (SipURI) request.getSession().getAttribute(B2BUAHelper.FROM_INET_URI);
        InetAddress infoRURI = null;
        try {
            infoRURI = InetAddress.getByName(((SipURI) clonedInfo.getRequestURI()).getHost());
        } catch (UnknownHostException e) {
        }
        if (patchForNatB2BUASessions) {
            if (toInetUri != null && infoRURI == null) {

                if (logger.isInfoEnabled()) {
                    logger.info("Using the real ip address of the sip client " + toInetUri.toString()
                            + " as a request uri of the CloneBye request");
                }
                clonedInfo.setRequestURI(toInetUri);
            } else if (toInetUri != null && (infoRURI.isSiteLocalAddress() || infoRURI.isAnyLocalAddress()
                    || infoRURI.isLoopbackAddress())) {

                if (logger.isInfoEnabled()) {
                    logger.info("Using the real ip address of the sip client " + toInetUri.toString()
                            + " as a request uri of the CloneInfo request");
                }
                clonedInfo.setRequestURI(toInetUri);
            } else if (fromInetUri != null && (infoRURI.isSiteLocalAddress() || infoRURI.isAnyLocalAddress()
                    || infoRURI.isLoopbackAddress())) {
                if (logger.isInfoEnabled()) {
                    logger.info("Using the real ip address of the sip client " + fromInetUri.toString()
                            + " as a request uri of the CloneInfo request");
                }

                clonedInfo.setRequestURI(fromInetUri);
            }
        }
        clonedInfo.send();
    } else {
        final ActorRef call = (ActorRef) application.getAttribute(Call.class.getName());
        call.tell(request, self);
    }
}

From source file:com.cloud.server.ManagementServerImpl.java

@Override
@ActionEvent(eventType = EventTypes.EVENT_VOLUME_EXTRACT, eventDescription = "extracting volume", async = true)
public Long extractVolume(ExtractVolumeCmd cmd) throws URISyntaxException {
    Long volumeId = cmd.getId();/*from ww w  . j  av a 2s.co m*/
    String url = cmd.getUrl();
    Long zoneId = cmd.getZoneId();
    AsyncJobVO job = null; // FIXME: cmd.getJob();
    String mode = cmd.getMode();
    Account account = UserContext.current().getCaller();

    if (!_accountMgr.isRootAdmin(account.getType()) && ApiDBUtils.isExtractionDisabled()) {
        throw new PermissionDeniedException("Extraction has been disabled by admin");
    }

    VolumeVO volume = _volumeDao.findById(volumeId);
    if (volume == null) {
        InvalidParameterValueException ex = new InvalidParameterValueException(
                "Unable to find volume with specified volumeId");
        ex.addProxyObject(volume, volumeId, "volumeId");
        throw ex;
    }

    // perform permission check
    _accountMgr.checkAccess(account, null, true, volume);

    if (_dcDao.findById(zoneId) == null) {
        throw new InvalidParameterValueException("Please specify a valid zone.");
    }
    if (volume.getPoolId() == null) {
        throw new InvalidParameterValueException(
                "The volume doesnt belong to a storage pool so cant extract it");
    }
    // Extract activity only for detached volumes or for volumes whose instance is stopped
    if (volume.getInstanceId() != null
            && ApiDBUtils.findVMInstanceById(volume.getInstanceId()).getState() != State.Stopped) {
        s_logger.debug("Invalid state of the volume with ID: " + volumeId
                + ". It should be either detached or the VM should be in stopped state.");
        PermissionDeniedException ex = new PermissionDeniedException(
                "Invalid state of the volume with specified ID. It should be either detached or the VM should be in stopped state.");
        ex.addProxyObject(volume, volumeId, "volumeId");
        throw ex;
    }

    if (volume.getVolumeType() != Volume.Type.DATADISK) { // Datadisk dont have any template dependence.

        VMTemplateVO template = ApiDBUtils.findTemplateById(volume.getTemplateId());
        if (template != null) { // For ISO based volumes template = null and we allow extraction of all ISO based volumes
            boolean isExtractable = template.isExtractable()
                    && template.getTemplateType() != Storage.TemplateType.SYSTEM;
            if (!isExtractable && account != null && account.getType() != Account.ACCOUNT_TYPE_ADMIN) { // Global
                // admins are always allowed to extract
                PermissionDeniedException ex = new PermissionDeniedException(
                        "The volume with specified volumeId is not allowed to be extracted");
                ex.addProxyObject(volume, volumeId, "volumeId");
                throw ex;
            }
        }
    }

    Upload.Mode extractMode;
    if (mode == null || (!mode.equals(Upload.Mode.FTP_UPLOAD.toString())
            && !mode.equals(Upload.Mode.HTTP_DOWNLOAD.toString()))) {
        throw new InvalidParameterValueException("Please specify a valid extract Mode ");
    } else {
        extractMode = mode.equals(Upload.Mode.FTP_UPLOAD.toString()) ? Upload.Mode.FTP_UPLOAD
                : Upload.Mode.HTTP_DOWNLOAD;
    }

    // If mode is upload perform extra checks on url and also see if there is an ongoing upload on the same.
    if (extractMode == Upload.Mode.FTP_UPLOAD) {
        URI uri = new URI(url);
        if ((uri.getScheme() == null) || (!uri.getScheme().equalsIgnoreCase("ftp"))) {
            throw new IllegalArgumentException("Unsupported scheme for url: " + url);
        }

        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);
        }

        if (_uploadMonitor.isTypeUploadInProgress(volumeId, Upload.Type.VOLUME)) {
            throw new IllegalArgumentException(volume.getName()
                    + " upload is in progress. Please wait for some time to schedule another upload for the same");
        }
    }

    long accountId = volume.getAccountId();
    StoragePoolVO srcPool = _poolDao.findById(volume.getPoolId());
    HostVO sserver = _storageMgr.getSecondaryStorageHost(zoneId);
    String secondaryStorageURL = sserver.getStorageUrl();

    List<UploadVO> extractURLList = _uploadDao.listByTypeUploadStatus(volumeId, Upload.Type.VOLUME,
            UploadVO.Status.DOWNLOAD_URL_CREATED);

    if (extractMode == Upload.Mode.HTTP_DOWNLOAD && extractURLList.size() > 0) {
        return extractURLList.get(0).getId(); // If download url already exists then return
    } else {
        UploadVO uploadJob = _uploadMonitor.createNewUploadEntry(sserver.getId(), volumeId,
                UploadVO.Status.COPY_IN_PROGRESS, Upload.Type.VOLUME, url, extractMode);
        s_logger.debug("Extract Mode - " + uploadJob.getMode());
        uploadJob = _uploadDao.createForUpdate(uploadJob.getId());

        // Update the async Job
        ExtractResponse resultObj = new ExtractResponse(volumeId, volume.getName(), accountId,
                UploadVO.Status.COPY_IN_PROGRESS.toString(), uploadJob.getId());
        resultObj.setResponseName(cmd.getCommandName());
        AsyncJobExecutor asyncExecutor = BaseAsyncJobExecutor.getCurrentExecutor();
        if (asyncExecutor != null) {
            job = asyncExecutor.getJob();
            _asyncMgr.updateAsyncJobAttachment(job.getId(), Upload.Type.VOLUME.toString(), volumeId);
            _asyncMgr.updateAsyncJobStatus(job.getId(), AsyncJobResult.STATUS_IN_PROGRESS, resultObj);
        }
        String value = _configs.get(Config.CopyVolumeWait.toString());
        int copyvolumewait = NumbersUtil.parseInt(value,
                Integer.parseInt(Config.CopyVolumeWait.getDefaultValue()));
        // Copy the volume from the source storage pool to secondary storage
        CopyVolumeCommand cvCmd = new CopyVolumeCommand(volume.getId(), volume.getPath(), srcPool,
                secondaryStorageURL, true, copyvolumewait);
        CopyVolumeAnswer cvAnswer = null;
        try {
            cvAnswer = (CopyVolumeAnswer) _storageMgr.sendToPool(srcPool, cvCmd);
        } catch (StorageUnavailableException e) {
            s_logger.debug("Storage unavailable");
        }

        // Check if you got a valid answer.
        if (cvAnswer == null || !cvAnswer.getResult()) {
            String errorString = "Failed to copy the volume from the source primary storage pool to secondary storage.";

            // Update the async job.
            resultObj.setResultString(errorString);
            resultObj.setUploadStatus(UploadVO.Status.COPY_ERROR.toString());
            if (asyncExecutor != null) {
                _asyncMgr.completeAsyncJob(job.getId(), AsyncJobResult.STATUS_FAILED, 0, resultObj);
            }

            // Update the DB that volume couldn't be copied
            uploadJob.setUploadState(UploadVO.Status.COPY_ERROR);
            uploadJob.setErrorString(errorString);
            uploadJob.setLastUpdated(new Date());
            _uploadDao.update(uploadJob.getId(), uploadJob);

            throw new CloudRuntimeException(errorString);
        }

        String volumeLocalPath = "volumes/" + volume.getId() + "/" + cvAnswer.getVolumePath() + "."
                + getFormatForPool(srcPool);
        // Update the DB that volume is copied and volumePath
        uploadJob.setUploadState(UploadVO.Status.COPY_COMPLETE);
        uploadJob.setLastUpdated(new Date());
        uploadJob.setInstallPath(volumeLocalPath);
        _uploadDao.update(uploadJob.getId(), uploadJob);

        if (extractMode == Mode.FTP_UPLOAD) { // Now that the volume is copied perform the actual uploading
            _uploadMonitor.extractVolume(uploadJob, sserver, volume, url, zoneId, volumeLocalPath,
                    cmd.getStartEventId(), job.getId(), _asyncMgr);
            return uploadJob.getId();
        } else { // Volume is copied now make it visible under apache and create a URL.
            _uploadMonitor.createVolumeDownloadURL(volumeId, volumeLocalPath, Upload.Type.VOLUME, zoneId,
                    uploadJob.getId());
            return uploadJob.getId();
        }
    }
}

From source file:org.restcomm.connect.telephony.CallManager.java

public void bye(final Object message) throws IOException {
    final ActorRef self = self();
    final SipServletRequest request = (SipServletRequest) message;
    final SipApplicationSession application = request.getApplicationSession();

    // if this response is coming from a client that is in a p2p session with another registered client
    // we will just proxy the response
    SipSession linkedB2BUASession = B2BUAHelper.getLinkedSession(request);
    if (linkedB2BUASession != null) {
        if (logger.isInfoEnabled()) {
            logger.info(String.format("B2BUA: Got BYE request: \n %s", request));
        }/*from  ww  w.  j  av  a2 s. c  o  m*/

        //Prepare the BYE request to the linked session
        request.getSession().setAttribute(B2BUAHelper.B2BUA_LAST_REQUEST, request);
        SipServletRequest clonedBye = linkedB2BUASession.createRequest("BYE");
        linkedB2BUASession.setAttribute(B2BUAHelper.B2BUA_LAST_REQUEST, clonedBye);

        if (patchForNatB2BUASessions) {
            // Issue #307: https://telestax.atlassian.net/browse/RESTCOMM-307
            SipURI toInetUri = (SipURI) request.getSession().getAttribute(B2BUAHelper.TO_INET_URI);
            SipURI fromInetUri = (SipURI) request.getSession().getAttribute(B2BUAHelper.FROM_INET_URI);
            InetAddress byeRURI = null;
            try {
                byeRURI = InetAddress.getByName(((SipURI) clonedBye.getRequestURI()).getHost());
            } catch (UnknownHostException e) {
            }
            boolean isBehindLB = false;
            final String initialIpBeforeLB = request.getHeader("X-Sip-Balancer-InitialRemoteAddr");
            String initialPortBeforeLB = request.getHeader("X-Sip-Balancer-InitialRemotePort");
            if (initialIpBeforeLB != null) {
                if (initialPortBeforeLB == null)
                    initialPortBeforeLB = "5060";
                if (logger.isDebugEnabled()) {
                    logger.debug(
                            "We are behind load balancer, checking if the request URI needs to be patched");
                }
                isBehindLB = true;
            }
            if (logger.isDebugEnabled()) {
                logger.debug("toInetUri: " + toInetUri + " fromInetUri: " + fromInetUri + " byeRURI: " + byeRURI
                        + " initialIpBeforeLB: " + initialIpBeforeLB + " initialPortBeforeLB: "
                        + initialPortBeforeLB);
            }
            if (toInetUri != null && byeRURI == null) {
                if (logger.isInfoEnabled()) {
                    logger.info("Using the real To inet ip address of the sip client " + toInetUri.toString()
                            + " as a request uri of the CloneBye request");
                }
                clonedBye.setRequestURI(toInetUri);
            } else if (toInetUri != null && (byeRURI.isSiteLocalAddress() || byeRURI.isAnyLocalAddress()
                    || byeRURI.isLoopbackAddress())) {
                if (logger.isInfoEnabled()) {
                    logger.info("Using the real To inet ip address of the sip client " + toInetUri.toString()
                            + " as a request uri of the CloneBye request");
                }
                clonedBye.setRequestURI(toInetUri);
            } else if (fromInetUri != null && (byeRURI.isSiteLocalAddress() || byeRURI.isAnyLocalAddress()
                    || byeRURI.isLoopbackAddress())) {
                if (isBehindLB) {
                    // https://github.com/RestComm/Restcomm-Connect/issues/1357
                    boolean patchRURI = isLBPatchRURI(clonedBye, initialIpBeforeLB, initialPortBeforeLB);
                    if (patchRURI) {
                        if (logger.isDebugEnabled()) {
                            logger.debug(
                                    "We are behind load balancer, but Using the real ip address of the sip client "
                                            + fromInetUri.toString()
                                            + " as a request uri of the CloneBye request");
                        }
                        clonedBye.setRequestURI(fromInetUri);
                    }
                } else {
                    if (logger.isInfoEnabled()) {
                        logger.info("Using the real From inet ip  address of the sip client "
                                + fromInetUri.toString() + " as a request uri of the CloneBye request");
                    }
                    clonedBye.setRequestURI(fromInetUri);
                }
            } else if (toInetUri == null && (byeRURI.isSiteLocalAddress() || byeRURI.isAnyLocalAddress()
                    || byeRURI.isLoopbackAddress())) {
                if (logger.isInfoEnabled()) {
                    logger.info(
                            "Public IP toInetUri from SipSession is null, will check LB headers from last Response");
                }
                if (isBehindLB) {
                    String realIP = initialIpBeforeLB + ":" + initialPortBeforeLB;
                    SipURI uri = sipFactory.createSipURI(null, realIP);
                    boolean patchRURI = isLBPatchRURI(clonedBye, initialIpBeforeLB, initialPortBeforeLB);
                    if (patchRURI) {
                        if (logger.isDebugEnabled()) {
                            logger.debug("We are behind load balancer, will use: " + initialIpBeforeLB + ":"
                                    + initialPortBeforeLB + " for the cloned BYE message");
                        }
                        clonedBye.setRequestURI(uri);
                    }
                    if (logger.isInfoEnabled()) {
                        logger.info("We are behind load balancer, will use Initial Remote Address "
                                + initialIpBeforeLB + ":" + initialPortBeforeLB
                                + " for the cloned BYE request");
                    }
                } else {
                    if (logger.isInfoEnabled()) {
                        logger.info("LB Headers are also null");
                    }
                }
            }
        }
        B2BUAHelper.updateCDR(request, CallStateChanged.State.COMPLETED);
        //Prepare 200 OK for received BYE
        SipServletResponse okay = request.createResponse(Response.OK);
        okay.send();
        //Send the Cloned BYE
        if (logger.isInfoEnabled()) {
            logger.info(String.format("B2BUA: Will send out Cloned BYE request: \n %s", clonedBye));
        }
        clonedBye.send();
    } else {
        final ActorRef call = (ActorRef) application.getAttribute(Call.class.getName());
        if (call != null)
            call.tell(request, self);
    }
}