Search in sources :

Example 1 with Header

use of javax.sip.header.Header in project XobotOS by xamarin.

the class SIPHeaderList method getHeadersAsEncodedStrings.

/**
     * Return a list of encoded strings (one for each sipheader).
     *
     * @return LinkedList containing encoded strings in this header list. an
     *         empty list is returned if this header list contains no sip
     *         headers.
     */
public List<String> getHeadersAsEncodedStrings() {
    List<String> retval = new LinkedList<String>();
    ListIterator<HDR> li = hlist.listIterator();
    while (li.hasNext()) {
        Header sipheader = li.next();
        retval.add(sipheader.toString());
    }
    return retval;
}
Also used : PrivacyHeader(gov.nist.javax.sip.header.ims.PrivacyHeader) Header(javax.sip.header.Header)

Example 2 with Header

use of javax.sip.header.Header in project XobotOS by xamarin.

the class SipUri method equals.

/**
     * Compare two URIs and return true if they are equal.
     * @param that the object to compare to.
     * @return true if the object is equal to this object.
     *
     * JvB: Updated to define equality in terms of API methods, according to the rules
     * in RFC3261 section 19.1.4
     *
     * Jean Deruelle: Updated to define equality of API methods, according to the rules
     * in RFC3261 section 19.1.4 convert potential ie :
     *    %HEX HEX encoding parts of the URI before comparing them
     *    transport param added in comparison
     *    header equality enforced in comparison
     *
     */
@SuppressWarnings("unchecked")
@Override
public boolean equals(Object that) {
    // Shortcut for same object
    if (that == this)
        return true;
    if (that instanceof SipURI) {
        final SipURI a = this;
        final SipURI b = (SipURI) that;
        // A SIP and SIPS URI are never equivalent
        if (a.isSecure() ^ b.isSecure())
            return false;
        // components must match; comparison of userinfo is case-sensitive
        if (a.getUser() == null ^ b.getUser() == null)
            return false;
        if (a.getUserPassword() == null ^ b.getUserPassword() == null)
            return false;
        if (a.getUser() != null && !RFC2396UrlDecoder.decode(a.getUser()).equals(RFC2396UrlDecoder.decode(b.getUser())))
            return false;
        if (a.getUserPassword() != null && !RFC2396UrlDecoder.decode(a.getUserPassword()).equals(RFC2396UrlDecoder.decode(b.getUserPassword())))
            return false;
        if (a.getHost() == null ^ b.getHost() == null)
            return false;
        if (a.getHost() != null && !a.getHost().equalsIgnoreCase(b.getHost()))
            return false;
        if (a.getPort() != b.getPort())
            return false;
        // URI parameters
        for (Iterator i = a.getParameterNames(); i.hasNext(); ) {
            String pname = (String) i.next();
            String p1 = a.getParameter(pname);
            String p2 = b.getParameter(pname);
            // those present in both must match (case-insensitive)
            if (p1 != null && p2 != null && !RFC2396UrlDecoder.decode(p1).equalsIgnoreCase(RFC2396UrlDecoder.decode(p2)))
                return false;
        }
        // transport, user, ttl or method must match when present in either
        if (a.getTransportParam() == null ^ b.getTransportParam() == null)
            return false;
        if (a.getUserParam() == null ^ b.getUserParam() == null)
            return false;
        if (a.getTTLParam() == -1 ^ b.getTTLParam() == -1)
            return false;
        if (a.getMethodParam() == null ^ b.getMethodParam() == null)
            return false;
        if (a.getMAddrParam() == null ^ b.getMAddrParam() == null)
            return false;
        // Headers: must match according to their definition.
        if (a.getHeaderNames().hasNext() && !b.getHeaderNames().hasNext())
            return false;
        if (!a.getHeaderNames().hasNext() && b.getHeaderNames().hasNext())
            return false;
        if (a.getHeaderNames().hasNext() && b.getHeaderNames().hasNext()) {
            HeaderFactory headerFactory = null;
            try {
                headerFactory = SipFactory.getInstance().createHeaderFactory();
            } catch (PeerUnavailableException e) {
                Debug.logError("Cannot get the header factory to parse the header of the sip uris to compare", e);
                return false;
            }
            for (Iterator i = a.getHeaderNames(); i.hasNext(); ) {
                String hname = (String) i.next();
                String h1 = a.getHeader(hname);
                String h2 = b.getHeader(hname);
                if (h1 == null && h2 != null)
                    return false;
                if (h2 == null && h1 != null)
                    return false;
                // The following check should not be needed but we add it for findbugs.
                if (h1 == null && h2 == null)
                    continue;
                try {
                    Header header1 = headerFactory.createHeader(hname, RFC2396UrlDecoder.decode(h1));
                    Header header2 = headerFactory.createHeader(hname, RFC2396UrlDecoder.decode(h2));
                    // those present in both must match according to the equals method of the corresponding header
                    if (!header1.equals(header2))
                        return false;
                } catch (ParseException e) {
                    Debug.logError("Cannot parse one of the header of the sip uris to compare " + a + " " + b, e);
                    return false;
                }
            }
        }
        // Finally, we can conclude that they are indeed equal
        return true;
    }
    return false;
}
Also used : PeerUnavailableException(javax.sip.PeerUnavailableException) Header(javax.sip.header.Header) ParseException(java.text.ParseException) SipURI(javax.sip.address.SipURI) HeaderFactory(javax.sip.header.HeaderFactory)

Example 3 with Header

use of javax.sip.header.Header in project smscgateway by RestComm.

the class SipMessageTest method init.

public void init() {
    SipFactory sipFactory = null;
    sipStack = null;
    sipFactory = SipFactory.getInstance();
    sipFactory.setPathName("gov.nist");
    Properties properties = new Properties();
    // If you want to try TCP transport change the following to
    String transport = "udp";
    String peerHostPort = "127.0.0.1:5060";
    properties.setProperty("javax.sip.OUTBOUND_PROXY", peerHostPort + "/" + transport);
    // If you want to use UDP then uncomment this.
    properties.setProperty("javax.sip.STACK_NAME", "shootist");
    // The following properties are specific to nist-sip
    // and are not necessarily part of any other jain-sip
    // implementation.
    // You can set a max message size for tcp transport to
    // guard against denial of service attack.
    properties.setProperty("gov.nist.javax.sip.MAX_MESSAGE_SIZE", "1048576");
    properties.setProperty("gov.nist.javax.sip.DEBUG_LOG", "shootistdebuglog.txt");
    properties.setProperty("gov.nist.javax.sip.SERVER_LOG", "shootistlog.txt");
    // Drop the client connection after we are done with the transaction.
    properties.setProperty("gov.nist.javax.sip.CACHE_CLIENT_CONNECTIONS", "false");
    // Set to 0 in your production code for max speed.
    // You need 16 for logging traces. 32 for debug + traces.
    // Your code will limp at 32 but it is best for debugging.
    properties.setProperty("gov.nist.javax.sip.TRACE_LEVEL", "DEBUG");
    try {
        // Create SipStack object
        sipStack = sipFactory.createSipStack(properties);
        System.out.println("createSipStack " + sipStack);
    } catch (PeerUnavailableException e) {
        // could not find
        // gov.nist.jain.protocol.ip.sip.SipStackImpl
        // in the classpath
        e.printStackTrace();
        System.err.println(e.getMessage());
        System.exit(0);
    }
    try {
        headerFactory = sipFactory.createHeaderFactory();
        addressFactory = sipFactory.createAddressFactory();
        messageFactory = sipFactory.createMessageFactory();
        udpListeningPoint = sipStack.createListeningPoint("127.0.0.1", 5066, "udp");
        sipProvider = sipStack.createSipProvider(udpListeningPoint);
        SipMessageTest listener = this;
        sipProvider.addSipListener(listener);
        String fromName = "123456789";
        String fromSipAddress = "127.0.0.1:5066";
        String fromDisplayName = "123456789";
        String toSipAddress = "127.0.0.1:5060";
        String toUser = "6666";
        String toDisplayName = "6666";
        // create >From Header
        SipURI fromAddress = addressFactory.createSipURI(fromName, fromSipAddress);
        Address fromNameAddress = addressFactory.createAddress(fromAddress);
        fromNameAddress.setDisplayName(fromDisplayName);
        FromHeader fromHeader = headerFactory.createFromHeader(fromNameAddress, "12345");
        // create To Header
        SipURI toAddress = addressFactory.createSipURI(toUser, toSipAddress);
        Address toNameAddress = addressFactory.createAddress(toAddress);
        toNameAddress.setDisplayName(toDisplayName);
        ToHeader toHeader = headerFactory.createToHeader(toNameAddress, null);
        // create Request URI
        SipURI requestURI = addressFactory.createSipURI(toUser, peerHostPort);
        // Create ViaHeaders
        ArrayList viaHeaders = new ArrayList();
        ViaHeader viaHeader = headerFactory.createViaHeader("127.0.0.1", sipProvider.getListeningPoint(transport).getPort(), transport, null);
        // add via headers
        viaHeaders.add(viaHeader);
        // Create ContentTypeHeader
        ContentTypeHeader contentTypeHeader = headerFactory.createContentTypeHeader("text", "plain");
        // Create a new CallId header
        CallIdHeader callIdHeader = sipProvider.getNewCallId();
        // Create a new Cseq header
        CSeqHeader cSeqHeader = headerFactory.createCSeqHeader(1L, Request.MESSAGE);
        // Create a new MaxForwardsHeader
        MaxForwardsHeader maxForwards = headerFactory.createMaxForwardsHeader(70);
        // Create the request.
        Request request = messageFactory.createRequest(requestURI, Request.MESSAGE, callIdHeader, cSeqHeader, fromHeader, toHeader, viaHeaders, maxForwards);
        // Create contact headers
        String host = "127.0.0.1";
        SipURI contactUrl = addressFactory.createSipURI(fromName, host);
        contactUrl.setPort(udpListeningPoint.getPort());
        // Create the contact name address.
        SipURI contactURI = addressFactory.createSipURI(fromName, host);
        contactURI.setPort(sipProvider.getListeningPoint(transport).getPort());
        Address contactAddress = addressFactory.createAddress(contactURI);
        // Add the contact address.
        contactAddress.setDisplayName(fromName);
        contactHeader = headerFactory.createContactHeader(contactAddress);
        request.addHeader(contactHeader);
        // UDH Header
        Header udhHeader = headerFactory.createHeader("X-SMS-UDH", "06050413011301");
        request.addHeader(udhHeader);
        // Add the extension header.
        Header extensionHeader = headerFactory.createHeader("My-Header", "my header value");
        request.addHeader(extensionHeader);
        String s = this.getBody();
        byte[] contents = s.getBytes();
        request.setContent(contents, contentTypeHeader);
        // Create the client transaction.
        inviteTid = sipProvider.getNewClientTransaction(request);
        // send the request out.
        inviteTid.sendRequest();
    } catch (Exception ex) {
        System.out.println(ex.getMessage());
        ex.printStackTrace();
    }
}
Also used : MaxForwardsHeader(javax.sip.header.MaxForwardsHeader) PeerUnavailableException(javax.sip.PeerUnavailableException) Address(javax.sip.address.Address) FromHeader(javax.sip.header.FromHeader) ContentTypeHeader(javax.sip.header.ContentTypeHeader) ArrayList(java.util.ArrayList) Request(javax.sip.message.Request) Properties(java.util.Properties) SipURI(javax.sip.address.SipURI) PeerUnavailableException(javax.sip.PeerUnavailableException) CSeqHeader(javax.sip.header.CSeqHeader) CSeqHeader(javax.sip.header.CSeqHeader) ContentTypeHeader(javax.sip.header.ContentTypeHeader) MaxForwardsHeader(javax.sip.header.MaxForwardsHeader) ContactHeader(javax.sip.header.ContactHeader) ToHeader(javax.sip.header.ToHeader) FromHeader(javax.sip.header.FromHeader) ViaHeader(javax.sip.header.ViaHeader) CallIdHeader(javax.sip.header.CallIdHeader) Header(javax.sip.header.Header) ViaHeader(javax.sip.header.ViaHeader) SipFactory(javax.sip.SipFactory) ToHeader(javax.sip.header.ToHeader) CallIdHeader(javax.sip.header.CallIdHeader)

Example 4 with Header

use of javax.sip.header.Header in project smscgateway by RestComm.

the class RxSipServerSbb method sendMessage.

// *********
// Main service methods
/**
 * Sending of a SIP message after initial message or when all sent messages was sent
 *
 * @param smsSet
 * @throws SmscProcessingException
 */
private void sendMessage(SmsSet smsSet) throws SmscProcessingException {
    smscStatAggregator.updateMsgOutTryAll();
    smscStatAggregator.updateMsgOutTrySip();
    Sms sms = this.obtainNextMessage(ProcessingType.SIP);
    if (sms == null) {
        this.markDeliveringIsEnded(true);
        return;
    }
    try {
        // TODO: let make here a special check if SIP is in a good state
        // if not - skip sending and set temporary error
        String fromAddressStr = sms.getSourceAddr();
        String toAddressStr = smsSet.getDestAddr();
        Sip sip = sipManagement.getSipByName(SipManagement.SIP_NAME);
        ListeningPoint listeningPoint = sipRA.getListeningPoints()[0];
        SipURI fromAddressUri = addressFactory.createSipURI(fromAddressStr, listeningPoint.getIPAddress() + ":" + listeningPoint.getPort());
        javax.sip.address.Address fromAddress = addressFactory.createAddress(fromAddressUri);
        FromHeader fromHeader = headerFactory.createFromHeader(fromAddress, null);
        SipURI toAddressUri = addressFactory.createSipURI(toAddressStr, sip.getSipAddress());
        javax.sip.address.Address toAddress = addressFactory.createAddress(toAddressUri);
        ToHeader toHeader = headerFactory.createToHeader(toAddress, null);
        List<ViaHeader> viaHeaders = new ArrayList<ViaHeader>(1);
        ViaHeader viaHeader = headerFactory.createViaHeader(listeningPoint.getIPAddress(), listeningPoint.getPort(), listeningPoint.getTransport(), null);
        viaHeaders.add(viaHeader);
        ContentTypeHeader contentTypeHeader = headerFactory.createContentTypeHeader("text", "plain");
        CSeqHeader cSeqHeader = headerFactory.createCSeqHeader(2L, Request.MESSAGE);
        MaxForwardsHeader maxForwardsHeader = headerFactory.createMaxForwardsHeader(70);
        CallIdHeader callId = this.sipRA.getNewCallId();
        String msgStr = sms.getShortMessageText();
        byte[] msgUdh = sms.getShortMessageBin();
        byte[] msg;
        msg = recodeShortMessage(sms.getDataCoding(), msgStr, msgUdh);
        // create request
        Request request = messageFactory.createRequest(toAddressUri, Request.MESSAGE, callId, cSeqHeader, fromHeader, toHeader, viaHeaders, maxForwardsHeader, contentTypeHeader, msg);
        // Custom X Headers
        // SMSC-ID
        String originEsmeName = sms.getOrigEsmeName();
        if (originEsmeName != null) {
            Header smsIdHeader = headerFactory.createHeader(SipXHeaders.XSmscId, originEsmeName);
            request.addHeader(smsIdHeader);
        }
        // data-coding
        DataCodingScheme dataCodingScheme = new DataCodingSchemeImpl(sms.getDataCoding());
        Header smsIdHeader = headerFactory.createHeader(SipXHeaders.XSmsCoding, Integer.toString(dataCodingScheme.getCharacterSet().getCode()));
        request.addHeader(smsIdHeader);
        // TODO X header message class
        // X header delivery time, use SUBMIT_DATE
        Date submitDate = sms.getSubmitDate();
        if (submitDate != null) {
            String submitDateStr = MessageUtil.formatDate(submitDate);
            Header submitDateHeader = headerFactory.createHeader(SipXHeaders.XDeliveryTime, submitDateStr);
            request.addHeader(submitDateHeader);
        }
        // Validity Period
        Date validityPeriod = sms.getValidityPeriod();
        if (validityPeriod != null) {
            String validityPeriodStr = MessageUtil.formatDate(validityPeriod);
            Header validityHeader = headerFactory.createHeader(SipXHeaders.XSmsValidty, validityPeriodStr);
            request.addHeader(validityHeader);
        }
        // X header UDH
        if (msgUdh != null) {
            String udhString = hexStringToByteArray(msgUdh);
            Header udhHeader = headerFactory.createHeader(SipXHeaders.XSmsUdh, udhString);
            request.addHeader(udhHeader);
        }
        // create client transaction and send request
        ClientTransaction clientTransaction = sipRA.getNewClientTransaction(request);
        ActivityContextInterface sipClientTxaci = this.sipACIFactory.getActivityContextInterface(clientTransaction);
        sipClientTxaci.attach(this.sbbContext.getSbbLocalObject());
        clientTransaction.sendRequest();
    } catch (Exception e) {
        throw new SmscProcessingException("RxSipServerSbb.sendMessage(): Exception while trying to send SIP Message =" + e.getMessage() + "\nMessage: " + sms, 0, 0, SmscProcessingException.HTTP_ERROR_CODE_NOT_SET, null, e);
    }
}
Also used : MaxForwardsHeader(javax.sip.header.MaxForwardsHeader) DataCodingScheme(org.mobicents.protocols.ss7.map.api.smstpdu.DataCodingScheme) SmscProcessingException(org.mobicents.smsc.library.SmscProcessingException) ArrayList(java.util.ArrayList) SipURI(javax.sip.address.SipURI) DataCodingSchemeImpl(org.mobicents.protocols.ss7.map.smstpdu.DataCodingSchemeImpl) ToHeader(javax.sip.header.ToHeader) CallIdHeader(javax.sip.header.CallIdHeader) ActivityContextInterface(javax.slee.ActivityContextInterface) FromHeader(javax.sip.header.FromHeader) ContentTypeHeader(javax.sip.header.ContentTypeHeader) ClientTransaction(javax.sip.ClientTransaction) Request(javax.sip.message.Request) Date(java.util.Date) SmscProcessingException(org.mobicents.smsc.library.SmscProcessingException) CharacterCodingException(java.nio.charset.CharacterCodingException) CSeqHeader(javax.sip.header.CSeqHeader) ViaHeader(javax.sip.header.ViaHeader) CallIdHeader(javax.sip.header.CallIdHeader) Header(javax.sip.header.Header) CSeqHeader(javax.sip.header.CSeqHeader) ContentTypeHeader(javax.sip.header.ContentTypeHeader) MaxForwardsHeader(javax.sip.header.MaxForwardsHeader) ToHeader(javax.sip.header.ToHeader) FromHeader(javax.sip.header.FromHeader) ViaHeader(javax.sip.header.ViaHeader) Sms(org.mobicents.smsc.library.Sms) ListeningPoint(javax.sip.ListeningPoint) Sip(org.mobicents.smsc.domain.Sip)

Example 5 with Header

use of javax.sip.header.Header in project load-balancer by RestComm.

the class SIPBalancerForwarder method processResponse.

/**
 * @param originalRequest
 * @param serverTransaction
 * @throws ParseException
 * @throws SipException
 * @throws InvalidArgumentException
 * @throws TransactionUnavailableException
 */
/*
     * (non-Javadoc)
     * @see javax.sip.SipListener#processResponse(javax.sip.ResponseEvent)
     */
public void processResponse(ResponseEvent responseEvent) {
    BalancerAppContent content = (BalancerAppContent) responseEvent.getSource();
    boolean isIpv6 = content.isIpv6();
    SipProvider sipProvider = content.getProvider();
    Response originalResponse = responseEvent.getResponse();
    if (logger.isDebugEnabled()) {
        logger.debug("got response :\n" + originalResponse);
    }
    updateStats(originalResponse);
    final Response response = (Response) originalResponse;
    Node senderNode = getSenderNode(response);
    if (senderNode != null) {
        if (logger.isDebugEnabled()) {
            logger.debug("Updating Timestamp of sendernode: " + senderNode);
        }
        senderNode.updateTimerStamp();
    }
    // Topmost via headers is me. As it is response to external request
    ViaHeader viaHeader = (ViaHeader) response.getHeader(ViaHeader.NAME);
    String branch = viaHeader.getBranch();
    int versionDelimiter = branch.lastIndexOf('_');
    String version = branch.substring(versionDelimiter + 1);
    InvocationContext ctx = balancerRunner.getInvocationContext(version);
    if (viaHeader != null && !isHeaderExternal(viaHeader.getHost(), viaHeader.getPort(), viaHeader.getTransport(), isIpv6)) {
        response.removeFirst(ViaHeader.NAME);
    }
    viaHeader = (ViaHeader) response.getHeader(ViaHeader.NAME);
    String transport = viaHeader.getTransport();
    if (viaHeader != null && !isHeaderExternal(viaHeader.getHost(), viaHeader.getPort(), viaHeader.getTransport(), isIpv6)) {
        response.removeFirst(ViaHeader.NAME);
    }
    boolean fromServer = false;
    if (balancerRunner.balancerContext.isTwoEntrypoints()) {
        if (!isIpv6)
            fromServer = sipProvider.equals(balancerRunner.balancerContext.internalSipProvider);
        else
            fromServer = sipProvider.equals(balancerRunner.balancerContext.internalIpv6SipProvider);
        if (logger.isDebugEnabled()) {
            if (!isIpv6)
                logger.debug("fromServer : " + fromServer + ", sipProvider " + sipProvider + ", internalSipProvider " + balancerRunner.balancerContext.internalSipProvider);
            else
                logger.debug("fromServer : " + fromServer + ", sipProvider " + sipProvider + ", internalIpv6SipProvider " + balancerRunner.balancerContext.internalIpv6SipProvider);
        }
    } else {
        fromServer = senderNode == null;
        if (logger.isDebugEnabled()) {
            logger.debug("fromServer : " + fromServer + ", senderNode " + senderNode);
        }
    }
    // only for external responses
    if (balancerRunner.balancerContext.isUseWithNexmo && !fromServer) {
        viaHeader = (ViaHeader) response.getHeader(ViaHeader.NAME);
        if (viaHeader != null) {
            if (logger.isDebugEnabled())
                logger.debug("We are going to remove rport and received parametres from :" + viaHeader + " from external response");
            response.removeFirst(ViaHeader.NAME);
            viaHeader.removeParameter("rport");
            viaHeader.removeParameter("received");
            try {
                response.addFirst(viaHeader);
            } catch (NullPointerException | SipException e) {
                e.printStackTrace();
            }
            if (logger.isDebugEnabled())
                logger.debug("After removing :" + response);
        }
    }
    if (fromServer) {
        if (senderNode != null && senderNode.getIp() != null) {
            if (balancerRunner.balancerContext.maxRequestNumberWithoutResponse != null && balancerRunner.balancerContext.maxResponseTime != null) {
                KeySip keySip = new KeySip(senderNode, isIpv6);
                // adding null check for https://github.com/RestComm/load-balancer/issues/83
                Node currNode = ctx.sipNodeMap(isIpv6).get(keySip);
                if (currNode != null) {
                    if (logger.isDebugEnabled())
                        logger.debug("We are going to reset counters of health check" + currNode.getRequestNumberWithoutResponse() + " : " + currNode.getLastTimeResponse());
                    currNode.setLastTimeResponse(System.currentTimeMillis());
                    currNode.setRequestNumberWithoutResponse(0);
                    if (logger.isDebugEnabled())
                        logger.debug("Counter of request without responses is : " + currNode.getRequestNumberWithoutResponse() + " : " + currNode.getLastTimeResponse());
                } else {
                    logger.warn("Node is null, we will not reset counters");
                }
            }
            mediaFailureDetection(response, ctx, senderNode);
        }
        /*
			if("true".equals(balancerRunner.balancerContext.properties.getProperty("removeNodesOn500Response")) && response.getStatusCode() == 500) {
				// If the server is broken remove it from the list and try another one with the next retransmission
				if(!(sourceNode instanceof ExtraServerNode)) {
					if(balancerRunner.balancerContext.nodes.size()>1) {
						balancerRunner.balancerContext.nodes.remove(sourceNode);
						balancerRunner.balancerContext.balancerAlgorithm.nodeRemoved(sourceNode);
					}
				}
			} 
        	*/
        String publicIp = null;
        if (!isIpv6)
            publicIp = balancerRunner.balancerContext.publicIP;
        else
            publicIp = balancerRunner.balancerContext.publicIPv6;
        if (publicIp != null && publicIp.trim().length() > 0) {
            if (logger.isDebugEnabled()) {
                logger.debug("Will add Record-Route header to response with public IP Address: " + publicIp);
            }
            patchSipMessageForNAT(response, isIpv6);
        }
        // https://github.com/RestComm/load-balancer/issues/45 Adding sender node for the algorithm to be available
        ((ResponseExt) response).setApplicationData(senderNode);
        ctx.balancerAlgorithm.processInternalResponse(response, isIpv6);
        try {
            if (logger.isDebugEnabled()) {
                logger.debug("from server sending response externally " + response);
            }
            if (!isIpv6)
                balancerRunner.balancerContext.externalSipProvider.sendResponse(response);
            else
                balancerRunner.balancerContext.externalIpv6SipProvider.sendResponse(response);
        } catch (Exception ex) {
            logger.error("Unexpected exception while forwarding the response \n" + response, ex);
        }
    } else {
        try {
            SIPMessage message = (SIPMessage) response;
            String initialRemoteAddr = message.getPeerPacketSourceAddress().getHostAddress();
            String initialRemotePort = String.valueOf(message.getPeerPacketSourcePort());
            Header remoteAddrHeader = null;
            Header remotePortHeader = null;
            try {
                HeaderFactory hf = SipFactory.getInstance().createHeaderFactory();
                remoteAddrHeader = hf.createHeader("X-Sip-Balancer-InitialRemoteAddr", initialRemoteAddr);
                remotePortHeader = hf.createHeader("X-Sip-Balancer-InitialRemotePort", initialRemotePort);
            } catch (PeerUnavailableException e) {
                logger.error("Unexpected exception while creating custom headers for REGISTER message ", e);
            } catch (ParseException e) {
                logger.error("Unexpected exception while creating custom headers for REGISTER message ", e);
            }
            if (remoteAddrHeader != null)
                response.addHeader(remoteAddrHeader);
            if (remotePortHeader != null)
                response.addHeader(remotePortHeader);
            if (balancerRunner.balancerContext.isTwoEntrypoints()) {
                ctx.balancerAlgorithm.processExternalResponse(response, isIpv6);
                if (logger.isDebugEnabled()) {
                    logger.debug("two entry points: from external sending response " + response);
                }
                if (!isIpv6)
                    balancerRunner.balancerContext.internalSipProvider.sendResponse(response);
                else
                    balancerRunner.balancerContext.internalIpv6SipProvider.sendResponse(response);
            } else {
                if (!comesFromInternalNode(response, ctx, initialRemoteAddr, message.getPeerPacketSourcePort(), transport, isIpv6))
                    ctx.balancerAlgorithm.processExternalResponse(response, isIpv6);
                else
                    ctx.balancerAlgorithm.processInternalResponse(response, isIpv6);
                if (logger.isDebugEnabled()) {
                    logger.debug("one entry point: from external sending response " + response);
                }
                if (!isIpv6)
                    balancerRunner.balancerContext.externalSipProvider.sendResponse(response);
                else
                    balancerRunner.balancerContext.externalIpv6SipProvider.sendResponse(response);
            }
        } catch (Exception ex) {
            logger.error("Unexpected exception while forwarding the response \n" + response, ex);
        }
    }
}
Also used : PeerUnavailableException(javax.sip.PeerUnavailableException) Node(org.mobicents.tools.heartbeat.api.Node) ResponseExt(gov.nist.javax.sip.message.ResponseExt) HeaderFactory(javax.sip.header.HeaderFactory) ListeningPoint(javax.sip.ListeningPoint) InvalidArgumentException(javax.sip.InvalidArgumentException) ParseException(java.text.ParseException) TransportNotSupportedException(javax.sip.TransportNotSupportedException) TransportAlreadySupportedException(javax.sip.TransportAlreadySupportedException) ObjectInUseException(javax.sip.ObjectInUseException) PeerUnavailableException(javax.sip.PeerUnavailableException) TooManyListenersException(java.util.TooManyListenersException) SipException(javax.sip.SipException) UnknownHostException(java.net.UnknownHostException) TransactionUnavailableException(javax.sip.TransactionUnavailableException) Response(javax.sip.message.Response) SIPResponse(gov.nist.javax.sip.message.SIPResponse) ReasonHeader(javax.sip.header.ReasonHeader) ContactHeader(javax.sip.header.ContactHeader) ViaHeader(javax.sip.header.ViaHeader) CallIdHeader(javax.sip.header.CallIdHeader) Header(javax.sip.header.Header) MaxForwardsHeader(javax.sip.header.MaxForwardsHeader) ToHeader(javax.sip.header.ToHeader) RouteHeader(javax.sip.header.RouteHeader) FromHeader(javax.sip.header.FromHeader) RecordRouteHeader(javax.sip.header.RecordRouteHeader) ViaHeader(javax.sip.header.ViaHeader) SIPMessage(gov.nist.javax.sip.message.SIPMessage) ParseException(java.text.ParseException) SipException(javax.sip.SipException) SipProvider(javax.sip.SipProvider)

Aggregations

Header (javax.sip.header.Header)24 FromHeader (javax.sip.header.FromHeader)19 ToHeader (javax.sip.header.ToHeader)19 ViaHeader (javax.sip.header.ViaHeader)19 CallIdHeader (javax.sip.header.CallIdHeader)18 ContactHeader (javax.sip.header.ContactHeader)17 MaxForwardsHeader (javax.sip.header.MaxForwardsHeader)17 Request (javax.sip.message.Request)16 ParseException (java.text.ParseException)15 SipURI (javax.sip.address.SipURI)15 RouteHeader (javax.sip.header.RouteHeader)15 RecordRouteHeader (javax.sip.header.RecordRouteHeader)14 CSeqHeader (javax.sip.header.CSeqHeader)13 ContentTypeHeader (javax.sip.header.ContentTypeHeader)13 ReasonHeader (javax.sip.header.ReasonHeader)13 SipException (javax.sip.SipException)11 ArrayList (java.util.ArrayList)10 InvalidArgumentException (javax.sip.InvalidArgumentException)10 TransactionUnavailableException (javax.sip.TransactionUnavailableException)9 Response (javax.sip.message.Response)9