Search in sources :

Example 11 with ViaHeader

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

the class SIPBalancerForwarder method removeRouteHeadersMeantForLB.

/**
 * Remove the different route headers that are meant for the Load balancer.
 * There is two cases here :
 * <ul>
 * <li>* Requests coming from external and going to the cluster : dialog creating requests can have route header so that they go through the LB and subsequent requests
 * will have route headers since the LB record routed</li>
 * <li>* Requests coming from the cluster and going to external : dialog creating requests can have route header so that they go through the LB - those requests will define in the route header
 * the originating node of the request so that that subsequent requests are routed to the originating node if still alive</li>
 * </ul>
 *
 * @param request
 */
private RouteHeaderHints removeRouteHeadersMeantForLB(Request request, boolean isIpv6) {
    if (logger.isDebugEnabled()) {
        logger.debug("Checking if there is any route headers meant for the LB to remove...");
    }
    Node node = null;
    String callVersion = null;
    int numberOfRemovedRouteHeaders = 0;
    if (balancerRunner.balancerContext.matchingHostnameForRoute != null) {
        RouteHeader routeHeader = (RouteHeader) request.getHeader(RouteHeader.NAME);
        if (routeHeader != null) {
            if (logger.isDebugEnabled()) {
                logger.debug("Matching host name for route is : " + balancerRunner.balancerContext.matchingHostnameForRoute);
                logger.debug("Matching host name and subdomain: " + balancerRunner.balancerContext.isFilterSubdomain);
            }
            if (!balancerRunner.balancerContext.isFilterSubdomain) {
                if (((SipURI) routeHeader.getAddress().getURI()).getHost().equals(balancerRunner.balancerContext.matchingHostnameForRoute))
                    request.removeFirst(RouteHeader.NAME);
            } else {
                if (((SipURI) routeHeader.getAddress().getURI()).getHost().endsWith("." + balancerRunner.balancerContext.matchingHostnameForRoute))
                    request.removeFirst(RouteHeader.NAME);
            }
        }
    }
    // Removing first routeHeader if it is for the sip balancer
    RouteHeader routeHeader = (RouteHeader) request.getHeader(RouteHeader.NAME);
    if (routeHeader != null) {
        SipURI routeUri = (SipURI) routeHeader.getAddress().getURI();
        callVersion = routeUri.getParameter(ROUTE_PARAM_NODE_VERSION);
        String transport = ((ViaHeader) request.getHeader("Via")).getTransport();
        if (routeUri.getTransportParam() != null)
            transport = routeUri.getTransportParam();
        if (!isHeaderExternal(routeUri.getHost(), routeUri.getPort(), transport, isIpv6)) {
            if (logger.isDebugEnabled()) {
                logger.debug("this route header is for the LB removing it " + routeUri);
            }
            numberOfRemovedRouteHeaders++;
            request.removeFirst(RouteHeader.NAME);
            routeHeader = (RouteHeader) request.getHeader(RouteHeader.NAME);
            // since we used double record routing we may have 2 routes corresponding to us here
            // for ACK and BYE from caller for example
            node = checkRouteHeaderForSipNode(routeUri);
            if (routeHeader != null) {
                routeUri = (SipURI) routeHeader.getAddress().getURI();
                transport = ((ViaHeader) request.getHeader("Via")).getTransport();
                if (routeUri.getTransportParam() != null)
                    transport = routeUri.getTransportParam();
                if (!isHeaderExternal(routeUri.getHost(), routeUri.getPort(), transport, isIpv6)) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("this route header is for the LB removing it " + routeUri);
                    }
                    numberOfRemovedRouteHeaders++;
                    request.removeFirst(RouteHeader.NAME);
                    if (node == null) {
                        node = checkRouteHeaderForSipNode(routeUri);
                    }
                    // SIPP sometimes appends more headers and lets remove them here. There is no legitimate reason
                    // more than two SIP LB headers to be place next to each-other, so this cleanup is SAFE!
                    boolean moreHeaders = true;
                    while (moreHeaders) {
                        RouteHeader extraHeader = (RouteHeader) request.getHeader(RouteHeader.NAME);
                        if (extraHeader != null) {
                            SipURI u = (SipURI) extraHeader.getAddress().getURI();
                            transport = ((ViaHeader) request.getHeader("Via")).getTransport();
                            if (u.getTransportParam() != null)
                                transport = u.getTransportParam();
                            if (!isHeaderExternal(u.getHost(), u.getPort(), transport, isIpv6)) {
                                numberOfRemovedRouteHeaders++;
                                request.removeFirst(RouteHeader.NAME);
                            } else {
                                moreHeaders = false;
                            }
                        } else {
                            moreHeaders = false;
                        }
                    }
                }
            }
        }
    }
    if (node == null) {
        if (request.getRequestURI().isSipURI()) {
            node = checkRouteHeaderForSipNode((SipURI) request.getRequestURI());
        }
    }
    // logger.info(request.ge + " has this hint " + node);
    ToHeader to = (ToHeader) (request.getHeader(ToHeader.NAME));
    /*
         * We determine if this is subsequent based on To tag instead of checking route header metadata.
         */
    boolean subsequent = to.getTag() != null;
    if (logger.isDebugEnabled()) {
        logger.debug("Number of removed Route headers is " + numberOfRemovedRouteHeaders);
    }
    // https://github.com/RestComm/load-balancer/issues/128
    if (numberOfRemovedRouteHeaders != 2 && subsequent && !request.getMethod().equalsIgnoreCase(Request.ACK)) {
        logger.warn("A subsequent request should have two Route headers. Number of removed Route headers is " + numberOfRemovedRouteHeaders + ". This indicates a client is removing important headers.");
    }
    return new RouteHeaderHints(node, subsequent, callVersion);
}
Also used : RouteHeader(javax.sip.header.RouteHeader) RecordRouteHeader(javax.sip.header.RecordRouteHeader) ViaHeader(javax.sip.header.ViaHeader) Node(org.mobicents.tools.heartbeat.api.Node) ToHeader(javax.sip.header.ToHeader) SipURI(javax.sip.address.SipURI) ListeningPoint(javax.sip.ListeningPoint)

Example 12 with ViaHeader

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

the class SIPBalancerForwarder method forwardRequest.

/**
 * @param requestEvent
 * @param sipProvider
 * @param originalRequest
 * @param serverTransaction
 * @param request
 * @throws ParseException
 * @throws InvalidArgumentException
 * @throws SipException
 * @throws TransactionUnavailableException
 */
private void forwardRequest(SipProvider sipProvider, Request request, boolean isIpv6) throws ParseException, InvalidArgumentException, SipException, TransactionUnavailableException {
    if (logger.isDebugEnabled()) {
        logger.debug("got request:\n" + request);
    }
    boolean isRequestFromServer = false;
    if (!balancerRunner.balancerContext.isTwoEntrypoints()) {
        isRequestFromServer = isViaHeaderFromServer(request);
    } else {
        isRequestFromServer = sipProvider.equals(balancerRunner.balancerContext.internalSipProvider) || sipProvider.equals(balancerRunner.balancerContext.internalIpv6SipProvider);
    }
    if (isRequestFromServer) {
        ViaHeader viaHeader = (ViaHeader) request.getHeader(ViaHeader.NAME);
        String host = viaHeader.getHost();
        if (host.matches(".*[a-zA-Z]+.*")) {
            try {
                host = InetAddress.getByName(host).getHostAddress();
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
        }
        int port = viaHeader.getPort();
        String transport = viaHeader.getTransport().toLowerCase();
        Node node = getNodeDeadOrAlive(host, port, transport);
        if (node != null) {
            if (logger.isDebugEnabled())
                logger.debug("Updating Timestamp of node: " + node + " because of request from it");
            node.updateTimerStamp();
        }
    }
    final boolean isCancel = Request.CANCEL.equals(request.getMethod());
    if (!isCancel) {
        decreaseMaxForwardsHeader(sipProvider, request);
    }
    String outerTransport = ((ViaHeader) request.getHeader(ViaHeader.NAME)).getTransport().toLowerCase();
    if (isRequestFromServer) {
        Boolean hasTransport = false;
        if (request.getRequestURI().isSipURI()) {
            if (((SipUri) request.getRequestURI()).getTransportParam() != null) {
                outerTransport = ((SipUri) request.getRequestURI()).getTransportParam();
                hasTransport = true;
            }
        }
        if (!hasTransport) {
            outerTransport = getRouteHeadersMeantForLB(request, isIpv6);
            if (outerTransport == null)
                outerTransport = ((ViaHeader) request.getHeader(ViaHeader.NAME)).getTransport().toLowerCase();
        }
    }
    RouteHeaderHints hints = removeRouteHeadersMeantForLB(request, isIpv6);
    String version = hints.version;
    if (version == null) {
        version = register.getLatestVersion();
        hints.version = version;
    }
    InvocationContext ctx = balancerRunner.getInvocationContext(version);
    final String callID = ((CallIdHeader) request.getHeader(CallIdHeader.NAME)).getCallId();
    String transport = null;
    if (balancerRunner.balancerContext.internalTransport != null) {
        if (logger.isDebugEnabled()) {
            logger.debug("Set internal transport for NODE looking: " + balancerRunner.balancerContext.internalTransport);
        }
        transport = balancerRunner.balancerContext.internalTransport.toLowerCase();
    } else if (balancerRunner.balancerContext.terminateTLSTraffic) {
        switch(((ViaHeader) request.getHeader(ViaHeader.NAME)).getTransport()) {
            case ListeningPoint.TLS:
                transport = ListeningPoint.TCP.toLowerCase();
                break;
            case ListeningPointExt.WSS:
                transport = ListeningPointExt.WS.toLowerCase();
                break;
            case ListeningPointExt.WS:
            case ListeningPointExt.TCP:
            case ListeningPointExt.UDP:
                transport = ((ViaHeader) request.getHeader(ViaHeader.NAME)).getTransport().toLowerCase();
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Terminate TLS traffic, isRequestFromServer: " + isRequestFromServer + " transport before " + ((ViaHeader) request.getHeader(ViaHeader.NAME)).getTransport() + ", transport after " + transport);
        }
    } else {
        transport = ((ViaHeader) request.getHeader(ViaHeader.NAME)).getTransport().toLowerCase();
    }
    if (hints.serverAssignedNode != null) {
        String headerKey = null;
        if (balancerRunner.balancerContext.sipHeaderAffinityKey.equalsIgnoreCase(ToHeader.NAME)) {
            URI currURI = ((HeaderAddress) request.getHeader(balancerRunner.balancerContext.sipHeaderAffinityKey)).getAddress().getURI();
            if (currURI.isSipURI())
                headerKey = ((SipURI) currURI).getUser();
            else
                headerKey = ((TelURL) currURI).getPhoneNumber();
            if (balancerRunner.balancerContext.sipHeaderAffinityKeyExclusionPattern != null && balancerRunner.balancerContext.sipHeaderAffinityKeyExclusionPattern.matcher(headerKey).matches()) {
                headerKey = ((HeaderExt) request.getHeader(balancerRunner.balancerContext.sipHeaderAffinityFallbackKey)).getValue();
            }
        } else if (balancerRunner.balancerContext.sipHeaderAffinityKey.equalsIgnoreCase(FromHeader.NAME)) {
            headerKey = ((HeaderAddress) request.getHeader(balancerRunner.balancerContext.sipHeaderAffinityKey)).getAddress().getURI().toString();
            if (balancerRunner.balancerContext.sipHeaderAffinityKeyExclusionPattern != null && balancerRunner.balancerContext.sipHeaderAffinityKeyExclusionPattern.matcher(headerKey).matches()) {
                headerKey = ((HeaderExt) request.getHeader(balancerRunner.balancerContext.sipHeaderAffinityFallbackKey)).getValue();
            }
        } else {
            headerKey = ((HeaderExt) request.getHeader(balancerRunner.balancerContext.sipHeaderAffinityKey)).getValue();
        }
        if (logger.isDebugEnabled()) {
            logger.debug("headerKey " + headerKey);
        }
        if (!request.getMethod().equalsIgnoreCase(Request.ACK))
            ctx.balancerAlgorithm.assignToNode(headerKey, hints.serverAssignedNode);
        if (logger.isDebugEnabled()) {
            logger.debug("Following node information has been found in one of the route Headers " + hints.serverAssignedNode);
        }
    // SipURI loopbackUri = getLoopbackUri(request);
    // if(loopbackUri != null) {
    // loopbackUri.setHost(hints.serverAssignedNode.getIp());
    // loopbackUri.setPort((Integer) hints.serverAssignedNode.getProperties().get(transport + "Port"));
    // }
    }
    Node nextNode = null;
    if (isRequestFromServer) {
        if (logger.isDebugEnabled()) {
            logger.debug("Request from server");
        }
        Header initialAddrHeader = request.getHeader("X-Sip-Balancer-InitialRemoteAddr");
        Header initialPortHeader = request.getHeader("X-Sip-Balancer-InitialRemotePort");
        if (initialAddrHeader != null)
            request.removeHeader(initialAddrHeader.getName());
        if (initialPortHeader != null)
            request.removeHeader(initialPortHeader.getName());
        ctx.balancerAlgorithm.processInternalRequest(request);
        if (request.getMethod().equalsIgnoreCase(Request.INVITE) && ctx.balancerAlgorithm.blockInternalRequest(request)) {
            Response response = balancerRunner.balancerContext.messageFactory.createResponse(Response.FORBIDDEN, request);
            response.setReasonPhrase("Destination not allowed");
            sipProvider.sendResponse(response);
            return;
        }
        nextNode = hints.serverAssignedNode;
        if (logger.isDebugEnabled()) {
            logger.debug("nexNode " + nextNode);
        }
    } else {
        if (logger.isDebugEnabled()) {
            logger.debug("Request not from server");
        }
        if (hints.serverAssignedNode != null) {
            SipURI loopbackUri = getLoopbackUri(request, isIpv6);
            if (loopbackUri != null) {
                loopbackUri.setHost(hints.serverAssignedNode.getIp());
                loopbackUri.setPort(Integer.parseInt(hints.serverAssignedNode.getProperties().get(transport + "Port")));
            }
        }
        // Request is NOT from app server, first check if we have hints in Route headers
        Node assignedNode = hints.serverAssignedNode;
        // If there are no hints see if there is route header pointing existing node
        if (assignedNode == null) {
            RouteHeader nextNodeHeader = (RouteHeader) request.getHeader(RouteHeader.NAME);
            if (nextNodeHeader != null) {
                URI uri = nextNodeHeader.getAddress().getURI();
                if (uri instanceof SipURI) {
                    SipURI sipUri = (SipURI) uri;
                    assignedNode = getAliveNode(sipUri.getHost(), sipUri.getPort(), transport, ctx, isIpv6);
                    if (logger.isDebugEnabled()) {
                        logger.debug("Found SIP URI " + uri + " |Next node is " + assignedNode);
                    }
                }
            }
        }
        SipURI assignedUri = null;
        // boolean nextNodeInRequestUri = false;
        SipURI originalRouteHeaderUri = null;
        if (assignedNode == null) {
            if (hints.subsequentRequest) {
                RouteHeader header = (RouteHeader) request.getHeader(RouteHeader.NAME);
                if (header != null) {
                    assignedUri = (SipURI) header.getAddress().getURI();
                    originalRouteHeaderUri = (SipURI) assignedUri.clone();
                    request.removeFirst(RouteHeader.NAME);
                } else {
                    if (request.getRequestURI() instanceof SipURI) {
                        SipURI sipUri = (SipURI) request.getRequestURI();
                        // nextNodeInRequestUri = true;
                        assignedNode = getAliveNode(sipUri.getHost(), sipUri.getPort(), transport, ctx, isIpv6);
                    }
                }
                if (logger.isDebugEnabled()) {
                    logger.debug("Subsequent request -> Found Route Header " + header + " |Next node is " + assignedNode);
                }
            } else if (request.getRequestURI() instanceof SipURI) {
                SipURI sipUri = (SipURI) request.getRequestURI();
                // nextNodeInRequestUri = true;
                assignedNode = getAliveNode(sipUri.getHost(), sipUri.getPort(), transport, ctx, isIpv6);
                if (logger.isDebugEnabled()) {
                    logger.debug("NOT Subsequent request -> using sipUri " + sipUri + " |Next node is " + assignedNode);
                }
            }
        }
        if (assignedNode == null) {
            if (logger.isDebugEnabled()) {
                logger.debug("assignedNode is null");
            }
            if (!securityCheck(request)) {
                logger.warn("Request failed at the security check:\n" + request);
            } else {
                nextNode = ctx.balancerAlgorithm.processExternalRequest(request, isIpv6);
            }
            if (nextNode instanceof NullServerNode) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Algorithm returned a NullServerNode. We will not attempt to forward this request " + request);
                }
            }
            if (nextNode != null) {
                if (logger.isDebugEnabled()) {
                    String nodesString = "";
                    // Object[] nodes = ctx.nodes.toArray();
                    Object[] nodes = ctx.sipNodeMap(isIpv6).values().toArray();
                    for (Object n : nodes) {
                        nodesString += n + " , ";
                    }
                    logger.debug("Next node is not null. Assigned uri is " + assignedUri + "Available nodes: " + nodesString);
                }
                // Adding Route Header pointing to the node the sip balancer wants to forward to
                SipURI routeSipUri;
                try {
                    if (assignedUri == null) {
                        // If a next node is NOT already assigned in the dialog from previous requests
                        routeSipUri = balancerRunner.balancerContext.addressFactory.createSipURI(null, nextNode.getIp());
                    } else {
                        // OTHERWISE, a node is already assigned and it's alive
                        routeSipUri = assignedUri;
                    }
                    routeSipUri.setHost(nextNode.getIp());
                    Integer port = Integer.parseInt(nextNode.getProperties().get(transport + "Port"));
                    if (port == null) {
                        throw new RuntimeException("Port is null in the node properties for transport=" + transport);
                    }
                    routeSipUri.setPort(port);
                    routeSipUri.setTransportParam(transport);
                    routeSipUri.setLrParam();
                    SipURI uri = (SipURI) request.getRequestURI();
                    RouteHeader header = (RouteHeader) request.getHeader(RouteHeader.NAME);
                    if (isHeaderExternal(uri.getHost(), uri.getPort(), ((ViaHeader) request.getHeader("Via")).getTransport(), isIpv6) || header != null) {
                        final RouteHeader route = balancerRunner.balancerContext.headerFactory.createRouteHeader(balancerRunner.balancerContext.addressFactory.createAddress(routeSipUri));
                        request.addFirst(route);
                        // For http://code.google.com/p/mobicents/issues/detail?id=2132
                        if (originalRouteHeaderUri != null && request.getRequestURI().isSipURI()) {
                            // we will just compare by hostport id
                            String rurihostid = uri.getHost() + uri.getPort();
                            String originalhostid = originalRouteHeaderUri.getHost() + originalRouteHeaderUri.getPort();
                            if (rurihostid.equals(originalhostid)) {
                                uri.setPort(routeSipUri.getPort());
                                uri.setHost(routeSipUri.getHost());
                            }
                        }
                    } else {
                        // should not add any routes , packet is destinated to lb
                        uri.setPort(routeSipUri.getPort());
                        uri.setHost(routeSipUri.getHost());
                    }
                } catch (Exception e) {
                    throw new RuntimeException("Error adding route header", e);
                }
            }
        } else {
            nextNode = ctx.balancerAlgorithm.processAssignedExternalRequest(request, assignedNode);
            if (logger.isDebugEnabled()) {
                logger.debug("Next node " + nextNode + " from assignedNode " + assignedNode);
            }
            // add Route header for using it for transferring instead of using uri
            if (nextNode != null && hints.subsequentRequest && !isRequestFromServer) {
                if (request.getRequestURI().isSipURI()) {
                    SipURI sipUri = (SipURI) request.getRequestURI();
                    SipURI routeSipUri = balancerRunner.balancerContext.addressFactory.createSipURI(null, nextNode.getIp());
                    Integer port = Integer.parseInt(nextNode.getProperties().get(transport + "Port"));
                    // port should not be null since it subsequent request
                    if (port != null) {
                        routeSipUri.setPort(port);
                        routeSipUri.setTransportParam(transport);
                        routeSipUri.setLrParam();
                        if (!sipUri.getHost().equals(routeSipUri.getHost()) || sipUri.getPort() != routeSipUri.getPort()) {
                            Boolean oldHeaderMatch = false;
                            Header oldHeader = request.getHeader(RouteHeader.NAME);
                            if (oldHeader != null) {
                                RouteHeader oldRouteHeader = (RouteHeader) oldHeader;
                                if (oldRouteHeader.getAddress().getURI().isSipURI()) {
                                    SipURI oldURI = (SipURI) oldRouteHeader.getAddress().getURI();
                                    if (oldURI.getHost().equals(routeSipUri.getHost()) && oldURI.getPort() == routeSipUri.getPort())
                                        oldHeaderMatch = true;
                                }
                            }
                            if (!oldHeaderMatch) {
                                final RouteHeader route = balancerRunner.balancerContext.headerFactory.createRouteHeader(balancerRunner.balancerContext.addressFactory.createAddress(routeSipUri));
                                request.addFirst(route);
                            }
                        }
                    }
                }
            }
        }
        if (nextNode == null) {
            if (logger.isDebugEnabled()) {
                logger.debug("No nodes available");
            }
            if (!Request.ACK.equalsIgnoreCase(request.getMethod())) {
                try {
                    Response response = balancerRunner.balancerContext.messageFactory.createResponse(Response.SERVER_INTERNAL_ERROR, request);
                    response.setReasonPhrase("No nodes available");
                    sipProvider.sendResponse(response);
                } catch (Exception e) {
                    logger.error("Unexpected exception while trying to send the error response for this " + request, e);
                }
            }
            return;
        } else {
        }
        if (balancerRunner.balancerContext.maxRequestNumberWithoutResponse != null && balancerRunner.balancerContext.maxResponseTime != null && !Request.ACK.equalsIgnoreCase(request.getMethod()))
            nodeHealthcheck(ctx, nextNode);
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Next node " + nextNode);
    }
    String requestMethod = request.getMethod();
    // https://telestax.atlassian.net/browse/LB-25 improve performance by sending back 100 Trying right away to tame retransmissions.
    if (balancerRunner.balancerContext.isSendTrying) {
        logger.debug("Load balancer sends 100 TRYING");
        if (requestMethod.equals(Request.INVITE) || requestMethod.equals(Request.SUBSCRIBE) || requestMethod.equals(Request.NOTIFY) || requestMethod.equals(Request.MESSAGE) || requestMethod.equals(Request.REFER) || requestMethod.equals(Request.PUBLISH) || requestMethod.equals(Request.UPDATE)) {
            try {
                Response response = balancerRunner.balancerContext.messageFactory.createResponse(Response.TRYING, request);
                RouteList routeList = ((SIPMessage) request).getRouteHeaders();
                if (routeList != null) {
                    Route route = (Route) routeList.getFirst();
                    SipUri sipUri = (SipUri) route.getAddress().getURI();
                    if (sipUri.toString().contains("node_host") || sipUri.toString().contains("node_port")) {
                        String nodeHost = sipUri.getParameter("node_host");
                        int nodePort = Integer.parseInt(sipUri.getParameter("node_port"));
                        ViaHeader viaHeader = (ViaHeader) response.getHeader(ViaHeader.NAME);
                        viaHeader.setHost(nodeHost);
                        viaHeader.setPort(nodePort);
                    }
                }
                sipProvider.sendResponse(response);
            } catch (SipException e) {
                logger.error("Unexpected exception while sending TRYING", e);
            } catch (ParseException e) {
                logger.error("Unexpected exception while sending TRYING", e);
            } catch (NumberFormatException e) {
                logger.error("Unexpected exception while sending TRYING", e);
            } catch (InvalidArgumentException e) {
                logger.error("Unexpected exception while sending TRYING", e);
            }
        }
    } else {
        logger.debug("Load balancer do not send 100 TRYING, this option is disabled");
    }
    hints.serverAssignedNode = nextNode;
    if (!hints.subsequentRequest && dialogCreationMethods.contains(request.getMethod())) {
        addLBRecordRoute(sipProvider, request, hints, version, isIpv6);
    }
    // Stateless proxies must not use internal state or ransom values when creating branch because they
    // must repeat exactly the same branches for retransmissions
    final ViaHeader via = (ViaHeader) request.getHeader(ViaHeader.NAME);
    String newBranch = via.getBranch() + callID.substring(0, Math.min(callID.length(), 5));
    // Add the via header to the top of the header list.
    ViaHeader viaHeaderExternal = null;
    ViaHeader viaHeaderInternal = null;
    String externalViaHost = null;
    String internalViaHost = null;
    String meantHost = null;
    if (!isRequestFromServer)
        meantHost = ((ViaHeader) request.getHeader(ViaHeader.NAME)).getReceived();
    else {
        Header routeHeader = request.getHeader(RouteHeader.NAME);
        if (routeHeader != null)
            meantHost = ((SipURI) ((RouteHeader) routeHeader).getAddress().getURI()).getHost();
    }
    if (!isIpv6) {
        if (balancerRunner.balancerContext.routingRulesIpv4 != null && meantHost != null) {
            boolean found = false;
            for (RoutingRule rule : balancerRunner.balancerContext.routingRulesIpv4) {
                if (rule.getIpPattern().matcher(meantHost).matches() && !rule.isPatch) {
                    found = true;
                    externalViaHost = balancerRunner.balancerContext.externalHost;
                    internalViaHost = balancerRunner.balancerContext.internalHost;
                    break;
                }
            }
            if (!found) {
                externalViaHost = balancerRunner.balancerContext.externalViaHost;
                internalViaHost = balancerRunner.balancerContext.internalViaHost;
            }
        } else {
            externalViaHost = balancerRunner.balancerContext.externalViaHost;
            internalViaHost = balancerRunner.balancerContext.internalViaHost;
        }
    } else {
        if (balancerRunner.balancerContext.routingRulesIpv6 != null && meantHost != null) {
            boolean found = false;
            for (RoutingRule rule : balancerRunner.balancerContext.routingRulesIpv6) {
                if (rule.getIpPattern().matcher(meantHost).matches() && !rule.isPatch) {
                    found = true;
                    externalViaHost = balancerRunner.balancerContext.externalIpv6Host;
                    internalViaHost = balancerRunner.balancerContext.internalIpv6Host;
                    break;
                }
            }
            if (!found) {
                externalViaHost = balancerRunner.balancerContext.externalIpv6ViaHost;
                internalViaHost = balancerRunner.balancerContext.internalIpv6ViaHost;
            }
        } else {
            externalViaHost = balancerRunner.balancerContext.externalIpv6ViaHost;
            internalViaHost = balancerRunner.balancerContext.internalIpv6ViaHost;
        }
    }
    if (!isRequestFromServer) {
        viaHeaderExternal = balancerRunner.balancerContext.headerFactory.createViaHeader(externalViaHost, balancerRunner.balancerContext.getExternalViaPortByTransport(outerTransport, isIpv6), outerTransport, newBranch + "_" + version);
        String innerTransport = transport;
        if (balancerRunner.balancerContext.internalTransport != null) {
            if (logger.isDebugEnabled()) {
                logger.debug("Set internal transport for for creating Via header : " + balancerRunner.balancerContext.internalTransport);
            }
            innerTransport = balancerRunner.balancerContext.internalTransport;
        } else if (balancerRunner.balancerContext.terminateTLSTraffic) {
            if (logger.isDebugEnabled()) {
                logger.debug("Terminate TLS traffic, isRequestFromServer: " + isRequestFromServer + " transport before " + innerTransport);
            }
            if (innerTransport.equalsIgnoreCase(ListeningPoint.TLS))
                innerTransport = ListeningPoint.TCP;
            else if (innerTransport.equalsIgnoreCase(ListeningPointExt.WSS))
                innerTransport = ListeningPointExt.WS;
            if (logger.isDebugEnabled()) {
                logger.debug("Terminate TLS traffic, transport after " + innerTransport);
            }
        }
        if (balancerRunner.balancerContext.isTwoEntrypoints())
            viaHeaderInternal = balancerRunner.balancerContext.headerFactory.createViaHeader(internalViaHost, balancerRunner.balancerContext.getInternalViaPortByTransport(innerTransport, isIpv6), innerTransport, newBranch + "zsd" + "_" + version);
        else
            viaHeaderInternal = balancerRunner.balancerContext.headerFactory.createViaHeader(externalViaHost, balancerRunner.balancerContext.getExternalViaPortByTransport(innerTransport, isIpv6), innerTransport, newBranch + "zsd" + "_" + version);
    } else {
        if (balancerRunner.balancerContext.isTwoEntrypoints())
            viaHeaderInternal = balancerRunner.balancerContext.headerFactory.createViaHeader(internalViaHost, balancerRunner.balancerContext.getInternalViaPortByTransport(transport, isIpv6), transport, newBranch + "zsd" + "_" + version);
        else
            viaHeaderInternal = balancerRunner.balancerContext.headerFactory.createViaHeader(externalViaHost, balancerRunner.balancerContext.getExternalViaPortByTransport(transport, isIpv6), transport, newBranch + "zsd" + "_" + version);
        // https://github.com/RestComm/load-balancer/issues/67
        // if (balancerRunner.balancerContext.terminateTLSTraffic) {
        // if(logger.isDebugEnabled()) {
        // logger.debug("Terminate TLS traffic, isRequestFromServer: " + isRequestFromServer +
        // " transport before " + outerTransport);
        // }
        // 
        // if (outerTransport.equalsIgnoreCase(ListeningPoint.TCP))
        // outerTransport = ListeningPoint.TLS;
        // else if (outerTransport.equalsIgnoreCase(ListeningPointExt.WS))
        // outerTransport = ListeningPointExt.WSS;
        // 
        // if(logger.isDebugEnabled()) {
        // logger.debug("Terminate TLS traffic, transport after " + outerTransport);
        // }
        // }
        viaHeaderExternal = balancerRunner.balancerContext.headerFactory.createViaHeader(externalViaHost, balancerRunner.balancerContext.getExternalViaPortByTransport(outerTransport, isIpv6), outerTransport, newBranch + "_" + version);
    }
    if (logger.isDebugEnabled()) {
        logger.debug("ViaHeaders will be added " + viaHeaderExternal + " and " + viaHeaderInternal);
        logger.debug("Sending the request:\n" + request + "\n on the other side");
    }
    if (getLoopbackUri(request, isIpv6) != null) {
        logger.warn("Drop. Cannot forward to loopback the following request: " + request);
        return;
    }
    try {
        if (!isRequestFromServer) {
            request.addHeader(viaHeaderExternal);
            if (viaHeaderInternal != null)
                request.addHeader(viaHeaderInternal);
            if (balancerRunner.balancerContext.terminateTLSTraffic) {
                // https://github.com/RestComm/load-balancer/issues/67
                // Patching the contact header for incoming requests so that requests coming out of nodes will use the non secure version
                ContactHeader contactHeader = (ContactHeader) request.getHeader(ContactHeader.NAME);
                if (contactHeader != null) {
                    final URI contactURI = contactHeader.getAddress().getURI();
                    if (logger.isDebugEnabled()) {
                        logger.debug("Patching the contact header " + contactURI + " so that requests coming out of nodes will use the non secure protocol");
                    }
                    if (contactURI instanceof SipUri) {
                        ((SipUri) contactURI).setTransportParam(outerTransport);
                        logger.debug("new transport " + contactURI + " so that requests coming out of nodes will use the non secure protocol");
                    }
                }
            } else if (balancerRunner.balancerContext.internalTransport != null) {
                // https://github.com/RestComm/load-balancer/issues/67
                // Patching the contact header for incoming requests so that requests coming out of nodes will use the non secure version
                ContactHeader contactHeader = (ContactHeader) request.getHeader(ContactHeader.NAME);
                if (contactHeader != null) {
                    final URI contactURI = contactHeader.getAddress().getURI();
                    if (logger.isDebugEnabled()) {
                        logger.debug("Patching the contact header " + contactURI + " so that requests coming out of nodes will use correct protocol");
                    }
                    if (contactURI instanceof SipUri) {
                        ((SipUri) contactURI).setTransportParam(outerTransport);
                        logger.debug("new transport " + contactURI + " so that requests coming out of nodes will use correct protocol");
                    }
                }
            }
            if (logger.isDebugEnabled()) {
                logger.debug("Sending the request:\n" + request);
            }
            if (balancerRunner.balancerContext.isTwoEntrypoints()) {
                if (!isIpv6)
                    balancerRunner.balancerContext.internalSipProvider.sendRequest(request);
                else {
                    balancerRunner.balancerContext.internalIpv6SipProvider.sendRequest(request);
                }
            } else {
                if (!isIpv6)
                    balancerRunner.balancerContext.externalSipProvider.sendRequest(request);
                else
                    balancerRunner.balancerContext.externalIpv6SipProvider.sendRequest(request);
            }
        } else {
            // Check if the next hop is actually the load balancer again
            if (viaHeaderInternal != null)
                request.addHeader(viaHeaderInternal);
            if (viaHeaderExternal != null)
                request.addHeader(viaHeaderExternal);
            // }
            if (logger.isDebugEnabled()) {
                logger.debug("Sending the request:\n" + request);
            }
            if (!isIpv6)
                balancerRunner.balancerContext.externalSipProvider.sendRequest(request);
            else
                balancerRunner.balancerContext.externalIpv6SipProvider.sendRequest(request);
        }
    } catch (Exception e) {
        if ((request.getMethod().equalsIgnoreCase(Request.OPTIONS) || e.getMessage().equals("Operation not permitted (sendto failed)")) && isRequestFromServer)
            logger.warn("Problem with sending OPTIONS to external side possibly due to closed window in broweser");
        else
            logger.error("Unexpected exception while forwarding the request \n" + request, e);
        if (balancerRunner.balancerContext.isSend5xxResponse)
            try {
                Response response = balancerRunner.balancerContext.messageFactory.createResponse(Response.SERVICE_UNAVAILABLE, request);
                response.removeFirst(ViaHeader.NAME);
                response.removeFirst(ViaHeader.NAME);
                if (balancerRunner.balancerContext.isSend5xxResponseReasonHeader != null) {
                    HeaderFactory hf = SipFactory.getInstance().createHeaderFactory();
                    ReasonHeader reasonHeader = hf.createReasonHeader(transport, balancerRunner.balancerContext.isSend5xxResponseSatusCode, balancerRunner.balancerContext.isSend5xxResponseReasonHeader);
                    response.setHeader(reasonHeader);
                }
                sipProvider.sendResponse(response);
            } catch (SipException ex) {
                logger.error("Unexpected exception while sending SERVICE_UNAVAILABLE", ex);
            } catch (ParseException ex) {
                logger.error("Unexpected exception while sending SERVICE_UNAVAILABLE", ex);
            } catch (NumberFormatException ex) {
                logger.error("Unexpected exception while sending SERVICE_UNAVAILABLE", ex);
            } catch (InvalidArgumentException ex) {
                logger.error("Unexpected exception while sending SERVICE_UNAVAILABLE", ex);
            }
    }
}
Also used : RouteHeader(javax.sip.header.RouteHeader) RecordRouteHeader(javax.sip.header.RecordRouteHeader) Node(org.mobicents.tools.heartbeat.api.Node) RouteList(gov.nist.javax.sip.header.RouteList) SipURI(javax.sip.address.SipURI) SipUri(gov.nist.javax.sip.address.SipUri) URI(javax.sip.address.URI) SipURI(javax.sip.address.SipURI) ReasonHeader(javax.sip.header.ReasonHeader) HeaderExt(gov.nist.javax.sip.header.HeaderExt) InvalidArgumentException(javax.sip.InvalidArgumentException) CallIdHeader(javax.sip.header.CallIdHeader) HeaderAddress(javax.sip.header.HeaderAddress) Route(gov.nist.javax.sip.header.Route) ContactHeader(javax.sip.header.ContactHeader) UnknownHostException(java.net.UnknownHostException) TelURL(javax.sip.address.TelURL) 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)

Example 13 with ViaHeader

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

the class TestSipListener method processResponse.

public void processResponse(ResponseEvent responseReceivedEvent) {
    if (abortProcessing) {
        logger.error("Processing aborted");
        return;
    }
    Response response = (Response) responseReceivedEvent.getResponse();
    System.out.println("Process response : " + response);
    eventListener.uacAfterResponse(response.getStatusCode(), appServer);
    if (response.getStatusCode() == 491)
        numberOf491s++;
    RecordRouteHeader recordRouteHeader = (RecordRouteHeader) response.getHeader(RecordRouteHeader.NAME);
    ContactHeader contactHeader = (ContactHeader) response.getHeader(ContactHeader.NAME);
    if (contactHeader != null && "0.0.0.0".equals(((SipURI) contactHeader.getAddress().getURI()).getHost())) {
        abortProcessing = true;
        throw new IllegalArgumentException("we received a contact header with 0.0.0.0 in a response !");
    }
    if (response.getStatusCode() >= 400 && response.getStatusCode() < 999) {
        this.serverErrorReceived = true;
    }
    if (response.getStatusCode() == 503) {
        this.serviceUnavailableReceived = true;
    }
    if (response.toString().toLowerCase().contains("info")) {
        lastInfoResponseTime = System.currentTimeMillis();
    }
    ClientTransaction tid = responseReceivedEvent.getClientTransaction();
    CSeqHeader cseq = (CSeqHeader) response.getHeader(CSeqHeader.NAME);
    logger.info("Response received : Status Code = " + response.getStatusCode() + " " + cseq);
    // not dropping in PRACK case on REINVITE the ClientTx can be null it seems
    if (tid == null && !prackSent) {
        if (countRetrans) {
            nbRetrans++;
        }
        logger.info("Stray response -- dropping ");
        return;
    }
    if (tid != null) {
        logger.info("transaction state is " + tid.getState());
        logger.info("Dialog = " + tid.getDialog());
        if (tid.getDialog() != null) {
            logger.info("Dialog State is " + tid.getDialog().getState());
        }
    }
    try {
        if (response.getStatusCode() > 100 && response.getStatusCode() < 200) {
            informationalResponse = response;
        }
        if (response.getStatusCode() >= 200 && response.getStatusCode() < 700) {
            logger.info("final response received : status code " + response.getStatusCode());
            finalResponseReceived = true;
            setFinalResponseStatus(response.getStatusCode());
            setFinalResponse(response);
        }
        if (response.getStatusCode() == Response.OK) {
            if (cseq.getMethod().equals(Request.INVITE) && sendAck) {
                inviteOkResponse = response;
                @SuppressWarnings("deprecation") Request ackRequest = responseReceivedEvent.getClientTransaction().createAck();
                if (useToURIasRequestUri) {
                    ackRequest.setRequestURI(requestURI);
                }
                if (timeToWaitBeforeAck > 0) {
                    Thread.sleep(timeToWaitBeforeAck);
                }
                if (!sendSubsequentRequestsThroughSipProvider && tid.getDialog() != null) {
                    tid.getDialog().sendAck(ackRequest);
                } else {
                    sipProvider.sendRequest(ackRequest);
                }
                ackSent = true;
                // If the caller is supposed to send the bye
                if (sendReinvite && !reinviteSent) {
                    List<Header> headers = new ArrayList<Header>();
                    Header reinviteHeader = protocolObjects.headerFactory.createHeader("ReInvite", "true");
                    headers.add(reinviteHeader);
                    if (prackSent) {
                        headers.add(protocolObjects.headerFactory.createHeader(RequireHeader.NAME, "100rel"));
                    }
                    sendInDialogSipRequest("INVITE", null, null, null, headers, null);
                    reinviteSent = true;
                    return;
                }
                if (sendBye) {
                    // Thread.sleep(30000);
                    sendBye();
                }
                if (sendByeAfterTerminatingNotify) {
                    tid.getDialog().terminateOnBye(false);
                }
            } else if (cseq.getMethod().equals(Request.BYE)) {
                okToByeReceived = true;
            } else if (cseq.getMethod().equals(Request.CANCEL)) {
                this.cancelOkReceived = true;
            // if (tid.getDialog().getState() == DialogState.CONFIRMED) {
            // // oops cancel went in too late. Need to hang up the
            // // dialog.
            // logger.info("Sending BYE -- cancel went in too late !!");
            // Request byeRequest = dialog.createRequest(Request.BYE);
            // ClientTransaction ct = sipProvider
            // .getNewClientTransaction(byeRequest);
            // tid.getDialog().sendRequest(ct);
            // }
            } else if (cseq.getMethod().equals(Request.PUBLISH)) {
                SIPETagHeader sipTagHeader = (SIPETagHeader) response.getHeader(SIPETag.NAME);
                sipETag = sipTagHeader.getETag();
            } else if (cseq.getMethod().equals(Request.PRACK)) {
                okToPrackReceived = true;
            }
        } else if (response.getStatusCode() == Response.MOVED_TEMPORARILY) {
            // Dialog dies as soon as you get an error response.
            if (cseq.getMethod().equals(Request.INVITE)) {
                // lookup the contact header
                ContactHeader contHdr = (ContactHeader) response.getHeader(ContactHeader.NAME);
                // we can re-use the from header
                FromHeader from = ((FromHeader) response.getHeader(FromHeader.NAME));
                // we use the to-address, but without the tag
                ToHeader to = (ToHeader) (response.getHeader(ToHeader.NAME)).clone();
                to.removeParameter("tag");
                // the call-id can be re-used
                CallIdHeader callID = ((CallIdHeader) response.getHeader(CallIdHeader.NAME));
                // we take the next cseq
                long seqNo = (((CSeqHeader) response.getHeader(CSeqHeader.NAME)).getSeqNumber());
                logger.info("seqNo = " + seqNo);
                CSeqHeader cseqNew = protocolObjects.headerFactory.createCSeqHeader(++seqNo, "INVITE");
                // Create ViaHeaders (either use tcp or udp)
                ArrayList<ViaHeader> viaHeaders = new ArrayList<ViaHeader>();
                ViaHeader viaHeader = null;
                if (!isIpv6)
                    viaHeader = protocolObjects.headerFactory.createViaHeader("127.0.0.1", sipProvider.getListeningPoint(protocolObjects.transport).getPort(), protocolObjects.transport, null);
                else
                    viaHeader = protocolObjects.headerFactory.createViaHeader("::1", sipProvider.getListeningPoint(protocolObjects.transport).getPort(), protocolObjects.transport, null);
                // add via headers
                viaHeaders.add(viaHeader);
                // create max forwards
                MaxForwardsHeader maxForwardsHeader = protocolObjects.headerFactory.createMaxForwardsHeader(10);
                // create invite Request
                SipURI newUri = (SipURI) this.requestURI.clone();
                newUri.setParameter("redirection", "true");
                requestURI = newUri;
                Request invRequest = protocolObjects.messageFactory.createRequest(newUri, "INVITE", callID, cseqNew, from, to, viaHeaders, maxForwardsHeader);
                // we set the Request URI to the address given
                SipURI contactURI = protocolObjects.addressFactory.createSipURI(null, this.listeningPoint.getIPAddress());
                contactURI.setPort(this.listeningPoint.getPort());
                contactURI.setTransportParam(protocolObjects.transport);
                Address address = protocolObjects.addressFactory.createAddress(contactURI);
                ContactHeader contact = protocolObjects.headerFactory.createContactHeader(address);
                invRequest.addHeader(contact);
                // the contacat header in the response contains where to redirect
                // the request to -- which in this case happens to be back to the
                // same location.
                ContactHeader chdr = (ContactHeader) response.getHeader(ContactHeader.NAME);
                SipURI sipUri = (SipURI) chdr.getAddress().getURI();
                // sipUri.setLrParam();
                RouteHeader routeHeader = protocolObjects.headerFactory.createRouteHeader(chdr.getAddress());
                invRequest.addHeader(routeHeader);
                invRequest.setRequestURI(sipUri);
                logger.info("Sending INVITE to " + contHdr.getAddress().getURI().toString());
                inviteClientTid = sipProvider.getNewClientTransaction(invRequest);
                logger.info("New TID = " + inviteClientTid);
                inviteClientTid.sendRequest();
                logger.info("sendReqeust succeeded " + inviteClientTid);
                Dialog dialog = inviteClientTid.getDialog();
                this.dialogCount++;
                this.dialog = dialog;
            }
        } else if (response.getStatusCode() == Response.REQUEST_TERMINATED) {
            if (cseq.getMethod().equals(Request.INVITE)) {
                this.requestTerminatedReceived = true;
            }
        } else if (response.getStatusCode() == Response.RINGING && sendUpdateOn180) {
            Request updateRequest = dialog.createRequest(Request.UPDATE);
            ClientTransaction ct = sipProvider.getNewClientTransaction(updateRequest);
            dialog.sendRequest(ct);
        } else if (response.getStatusCode() > Response.TRYING && response.getStatusCode() < Response.OK) {
            RequireHeader requireHeader = (RequireHeader) response.getHeader(RequireHeader.NAME);
            if (requireHeader != null && "100rel".equalsIgnoreCase(requireHeader.getOptionTag().trim())) {
                Request prack = dialog.createPrack(response);
                ClientTransaction ct = sipProvider.getNewClientTransaction(prack);
                dialog.sendRequest(ct);
                prackSent = true;
            }
        }
    /**
     * end of modified code
     */
    } catch (Exception ex) {
        logger.error("An unexpected exception occured while processing the response", ex);
    }
}
Also used : MaxForwardsHeader(javax.sip.header.MaxForwardsHeader) ContactHeader(javax.sip.header.ContactHeader) RouteHeader(javax.sip.header.RouteHeader) RecordRouteHeader(javax.sip.header.RecordRouteHeader) Address(javax.sip.address.Address) FromHeader(javax.sip.header.FromHeader) ClientTransaction(javax.sip.ClientTransaction) Request(javax.sip.message.Request) ArrayList(java.util.ArrayList) RecordRouteHeader(javax.sip.header.RecordRouteHeader) RequireHeader(javax.sip.header.RequireHeader) SipURI(javax.sip.address.SipURI) InvalidArgumentException(javax.sip.InvalidArgumentException) ParseException(java.text.ParseException) SipException(javax.sip.SipException) TransactionDoesNotExistException(javax.sip.TransactionDoesNotExistException) TransactionUnavailableException(javax.sip.TransactionUnavailableException) Response(javax.sip.message.Response) CSeqHeader(javax.sip.header.CSeqHeader) ReasonHeader(javax.sip.header.ReasonHeader) RequireHeader(javax.sip.header.RequireHeader) SIPETagHeader(javax.sip.header.SIPETagHeader) ContactHeader(javax.sip.header.ContactHeader) ReferToHeader(javax.sip.header.ReferToHeader) ViaHeader(javax.sip.header.ViaHeader) SIPIfMatchHeader(javax.sip.header.SIPIfMatchHeader) AuthorizationHeader(javax.sip.header.AuthorizationHeader) CallIdHeader(javax.sip.header.CallIdHeader) ContentLengthHeader(javax.sip.header.ContentLengthHeader) ExtensionHeader(javax.sip.header.ExtensionHeader) ExpiresHeader(javax.sip.header.ExpiresHeader) Header(javax.sip.header.Header) ReplacesHeader(gov.nist.javax.sip.header.extensions.ReplacesHeader) CSeqHeader(javax.sip.header.CSeqHeader) ContentTypeHeader(javax.sip.header.ContentTypeHeader) JoinHeader(gov.nist.javax.sip.header.extensions.JoinHeader) MaxForwardsHeader(javax.sip.header.MaxForwardsHeader) ToHeader(javax.sip.header.ToHeader) RouteHeader(javax.sip.header.RouteHeader) ProxyAuthorizationHeader(javax.sip.header.ProxyAuthorizationHeader) SubscriptionStateHeader(javax.sip.header.SubscriptionStateHeader) EventHeader(javax.sip.header.EventHeader) FromHeader(javax.sip.header.FromHeader) ProxyAuthenticateHeader(javax.sip.header.ProxyAuthenticateHeader) RecordRouteHeader(javax.sip.header.RecordRouteHeader) SIPETagHeader(javax.sip.header.SIPETagHeader) ViaHeader(javax.sip.header.ViaHeader) Dialog(javax.sip.Dialog) ReferToHeader(javax.sip.header.ReferToHeader) ToHeader(javax.sip.header.ToHeader) CallIdHeader(javax.sip.header.CallIdHeader)

Example 14 with ViaHeader

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

the class TestSipListener method createInvite.

public Request createInvite(String callId, long cseq) throws ParseException, InvalidArgumentException {
    String fromName = "BigGuy";
    String fromSipAddress = "here.com";
    String fromDisplayName = "The Master Blaster";
    String toSipAddress = "there.com";
    String toUser = "LittleGuy";
    String toDisplayName = "The Little Blister";
    // create >From Header
    SipURI fromAddress = protocolObjects.addressFactory.createSipURI(fromName, fromSipAddress);
    Address fromNameAddress = protocolObjects.addressFactory.createAddress(fromAddress);
    fromNameAddress.setDisplayName(fromDisplayName);
    FromHeader fromHeader = protocolObjects.headerFactory.createFromHeader(fromNameAddress, "12345");
    // create To Header
    SipURI toAddress = protocolObjects.addressFactory.createSipURI(toUser, toSipAddress);
    Address toNameAddress = protocolObjects.addressFactory.createAddress(toAddress);
    toNameAddress.setDisplayName(toDisplayName);
    ToHeader toHeader = protocolObjects.headerFactory.createToHeader(toNameAddress, null);
    // create Request URI
    SipURI requestURI = protocolObjects.addressFactory.createSipURI(toUser, peerHostPort);
    // Create ViaHeaders
    ArrayList<ViaHeader> viaHeaders = new ArrayList<ViaHeader>();
    ViaHeader viaHeader = null;
    if (!isIpv6)
        viaHeader = protocolObjects.headerFactory.createViaHeader("127.0.0.1", listeningPoint.getPort(), listeningPoint.getTransport(), null);
    else
        viaHeader = protocolObjects.headerFactory.createViaHeader("::1", listeningPoint.getPort(), listeningPoint.getTransport(), null);
    // add via headers
    viaHeaders.add(viaHeader);
    // Create ContentTypeHeader
    ContentTypeHeader contentTypeHeader = protocolObjects.headerFactory.createContentTypeHeader("application", "sdp");
    // Create a new CallId header
    CallIdHeader callIdHeader;
    callIdHeader = sipProvider.getNewCallId();
    if (callId.trim().length() > 0)
        callIdHeader.setCallId(callId);
    // Create a new Cseq header
    CSeqHeader cSeqHeader = protocolObjects.headerFactory.createCSeqHeader(cseq, Request.INVITE);
    // Create a new MaxForwardsHeader
    MaxForwardsHeader maxForwards = protocolObjects.headerFactory.createMaxForwardsHeader(70);
    // Create the request.
    Request request = protocolObjects.messageFactory.createRequest(requestURI, Request.INVITE, callIdHeader, cSeqHeader, fromHeader, toHeader, viaHeaders, maxForwards);
    // Create contact headers
    String host = null;
    if (!isIpv6)
        host = "127.0.0.1";
    else
        host = "::1";
    SipURI contactUrl = protocolObjects.addressFactory.createSipURI(fromName, host);
    contactUrl.setPort(listeningPoint.getPort());
    // Create the contact name address.
    SipURI contactURI = protocolObjects.addressFactory.createSipURI(fromName, host);
    contactURI.setPort(listeningPoint.getPort());
    Address contactAddress = protocolObjects.addressFactory.createAddress(contactURI);
    // Add the contact address.
    contactAddress.setDisplayName(fromName);
    contactHeader = protocolObjects.headerFactory.createContactHeader(contactAddress);
    request.addHeader(contactHeader);
    String sdpData = "v=0\r\n" + "o=4855 13760799956958020 13760799956958020" + " IN IP4  129.6.55.78\r\n" + "s=mysession session\r\n" + "p=+46 8 52018010\r\n" + "c=IN IP4  129.6.55.78\r\n" + "t=0 0\r\n" + "m=audio 6022 RTP/AVP 0 4 18\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "a=rtpmap:4 G723/8000\r\n" + "a=rtpmap:18 G729A/8000\r\n" + "a=ptime:20\r\n";
    byte[] contents = sdpData.getBytes();
    request.setContent(contents, contentTypeHeader);
    Header callInfoHeader = protocolObjects.headerFactory.createHeader("Call-Info", "<http://www.antd.nist.gov>");
    request.addHeader(callInfoHeader);
    return request;
}
Also used : MaxForwardsHeader(javax.sip.header.MaxForwardsHeader) Address(javax.sip.address.Address) FromHeader(javax.sip.header.FromHeader) ContentTypeHeader(javax.sip.header.ContentTypeHeader) ArrayList(java.util.ArrayList) Request(javax.sip.message.Request) SipURI(javax.sip.address.SipURI) CSeqHeader(javax.sip.header.CSeqHeader) ReasonHeader(javax.sip.header.ReasonHeader) RequireHeader(javax.sip.header.RequireHeader) SIPETagHeader(javax.sip.header.SIPETagHeader) ContactHeader(javax.sip.header.ContactHeader) ReferToHeader(javax.sip.header.ReferToHeader) ViaHeader(javax.sip.header.ViaHeader) SIPIfMatchHeader(javax.sip.header.SIPIfMatchHeader) AuthorizationHeader(javax.sip.header.AuthorizationHeader) CallIdHeader(javax.sip.header.CallIdHeader) ContentLengthHeader(javax.sip.header.ContentLengthHeader) ExtensionHeader(javax.sip.header.ExtensionHeader) ExpiresHeader(javax.sip.header.ExpiresHeader) Header(javax.sip.header.Header) ReplacesHeader(gov.nist.javax.sip.header.extensions.ReplacesHeader) CSeqHeader(javax.sip.header.CSeqHeader) ContentTypeHeader(javax.sip.header.ContentTypeHeader) JoinHeader(gov.nist.javax.sip.header.extensions.JoinHeader) MaxForwardsHeader(javax.sip.header.MaxForwardsHeader) ToHeader(javax.sip.header.ToHeader) RouteHeader(javax.sip.header.RouteHeader) ProxyAuthorizationHeader(javax.sip.header.ProxyAuthorizationHeader) SubscriptionStateHeader(javax.sip.header.SubscriptionStateHeader) EventHeader(javax.sip.header.EventHeader) FromHeader(javax.sip.header.FromHeader) ProxyAuthenticateHeader(javax.sip.header.ProxyAuthenticateHeader) RecordRouteHeader(javax.sip.header.RecordRouteHeader) ViaHeader(javax.sip.header.ViaHeader) ReferToHeader(javax.sip.header.ReferToHeader) ToHeader(javax.sip.header.ToHeader) CallIdHeader(javax.sip.header.CallIdHeader)

Example 15 with ViaHeader

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

the class Shootist method sendInitial.

public void sendInitial(String fromUser, String fromHost, String method, RouteHeader route, String[] headerNames, String[] headerContents) {
    try {
        if (!started)
            start();
        String fromName = fromUser;
        String fromSipAddress = fromHost;
        String fromDisplayName = "The Master Blaster";
        String toSipAddress = "there.com";
        String toUser = "LittleGuy";
        String toDisplayName = "The Little Blister";
        // 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<ViaHeader> viaHeaders = new ArrayList<ViaHeader>();
        String ipAddress = null;
        if (fromUser.equals("KostyaNosach"))
            ipAddress = "127.0.0.2";
        else
            ipAddress = listeningPoint.getIPAddress();
        ViaHeader viaHeader = headerFactory.createViaHeader(ipAddress, sipProvider.getListeningPoint(transport).getPort(), transport, null);
        // add via headers
        viaHeaders.add(viaHeader);
        // Create ContentTypeHeader
        ContentTypeHeader contentTypeHeader = headerFactory.createContentTypeHeader("application", "sdp");
        // Create a new CallId header
        CallIdHeader callIdHeader = sipProvider.getNewCallId();
        // Create a new Cseq header
        CSeqHeader cSeqHeader = headerFactory.createCSeqHeader(1L, method);
        // Create a new MaxForwardsHeader
        MaxForwardsHeader maxForwards = headerFactory.createMaxForwardsHeader(70);
        // Create the request.
        Request request = messageFactory.createRequest(requestURI, method, callIdHeader, cSeqHeader, fromHeader, toHeader, viaHeaders, maxForwards);
        // Create contact headers
        String host = localIPAddress;
        SipURI contactUrl = addressFactory.createSipURI(fromName, host);
        contactUrl.setPort(listeningPoint.getPort());
        contactUrl.setLrParam();
        // 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);
        // to the outgoing SIP request.
        // Add the extension header.
        Header extensionHeader = headerFactory.createHeader("My-Header", "my header value");
        request.addHeader(extensionHeader);
        if (headerNames != null) {
            for (int q = 0; q < headerNames.length; q++) {
                Header h = headerFactory.createHeader(headerNames[q], headerContents[q]);
                // if(setHeader) {
                request.setHeader(h);
            // } else {
            // request.addHeader(h);
            // }
            }
        }
        if (route != null)
            request.addHeader(route);
        String sdpData = "v=0\r\n" + "o=4855 13760799956958020 13760799956958020" + " IN IP4  129.6.55.78\r\n" + "s=mysession session\r\n" + "p=+46 8 52018010\r\n" + "c=IN IP4  129.6.55.78\r\n" + "t=0 0\r\n" + "m=audio 6022 RTP/AVP 0 4 18\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "a=rtpmap:4 G723/8000\r\n" + "a=rtpmap:18 G729A/8000\r\n" + "a=ptime:20\r\n";
        byte[] contents = sdpData.getBytes();
        request.setContent(contents, contentTypeHeader);
        // You can add as many extension headers as you
        // want.
        extensionHeader = headerFactory.createHeader("My-Other-Header", "my new header value ");
        request.addHeader(extensionHeader);
        Header callInfoHeader = headerFactory.createHeader("Call-Info", "<http://www.antd.nist.gov>");
        request.addHeader(callInfoHeader);
        // Create the client transaction.
        inviteTid = sipProvider.getNewClientTransaction(request);
        // send the request out.
        inviteTid.sendRequest();
        dialog = inviteTid.getDialog();
    } catch (Exception ex) {
        System.out.println(ex.getMessage());
        ex.printStackTrace();
        fail("Unxpected exception ");
    }
}
Also used : MaxForwardsHeader(javax.sip.header.MaxForwardsHeader) Address(javax.sip.address.Address) FromHeader(javax.sip.header.FromHeader) ContentTypeHeader(javax.sip.header.ContentTypeHeader) ArrayList(java.util.ArrayList) Request(javax.sip.message.Request) SipURI(javax.sip.address.SipURI) ListeningPoint(javax.sip.ListeningPoint) InvalidArgumentException(javax.sip.InvalidArgumentException) ParseException(java.text.ParseException) TransactionAlreadyExistsException(javax.sip.TransactionAlreadyExistsException) PeerUnavailableException(javax.sip.PeerUnavailableException) SipException(javax.sip.SipException) TransactionUnavailableException(javax.sip.TransactionUnavailableException) CSeqHeader(javax.sip.header.CSeqHeader) ContactHeader(javax.sip.header.ContactHeader) 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) RouteHeader(javax.sip.header.RouteHeader) FromHeader(javax.sip.header.FromHeader) ViaHeader(javax.sip.header.ViaHeader) ToHeader(javax.sip.header.ToHeader) CallIdHeader(javax.sip.header.CallIdHeader)

Aggregations

ViaHeader (javax.sip.header.ViaHeader)40 Request (javax.sip.message.Request)24 ParseException (java.text.ParseException)23 SipURI (javax.sip.address.SipURI)23 FromHeader (javax.sip.header.FromHeader)23 ToHeader (javax.sip.header.ToHeader)23 CallIdHeader (javax.sip.header.CallIdHeader)21 ContactHeader (javax.sip.header.ContactHeader)20 MaxForwardsHeader (javax.sip.header.MaxForwardsHeader)20 SipException (javax.sip.SipException)19 InvalidArgumentException (javax.sip.InvalidArgumentException)18 CSeqHeader (javax.sip.header.CSeqHeader)18 RouteHeader (javax.sip.header.RouteHeader)15 TransactionUnavailableException (javax.sip.TransactionUnavailableException)14 Address (javax.sip.address.Address)14 ContentTypeHeader (javax.sip.header.ContentTypeHeader)14 Header (javax.sip.header.Header)14 ListeningPoint (javax.sip.ListeningPoint)13 RecordRouteHeader (javax.sip.header.RecordRouteHeader)13 ClientTransaction (javax.sip.ClientTransaction)12