Search in sources :

Example 1 with URI

use of javax.sip.address.URI in project Openfire by igniterealtime.

the class SimpleListener method processRequest.

public void processRequest(RequestEvent requestEvent) {
    ServerTransaction serverTransaction = requestEvent.getServerTransaction();
    Dialog dialog = null;
    if (serverTransaction != null) {
        Log.debug("SimpleListener(" + myUsername + ").processRequest:  Getting dialog");
        dialog = serverTransaction.getDialog();
    }
    int responseCode = 200;
    Log.debug("SimpleListener(" + myUsername + ").processRequest:  Received a request event:  \n" + requestEvent.getRequest().toString());
    String fromAddr = "";
    Request request = requestEvent.getRequest();
    if (request.getHeader(FromHeader.NAME) != null) {
        FromHeader fromHeader = (FromHeader) request.getHeader(FromHeader.NAME);
        Address fromAddress = fromHeader.getAddress();
        //			String displayName = fromAddress.getDisplayName();
        URI fromUri = fromAddress.getURI();
        if (fromUri != null) {
            if (fromUri.isSipURI()) {
                SipURI fromSipUri = (SipURI) fromUri;
                fromAddr = fromSipUri.getUser() + "@" + fromSipUri.getHost();
            } else {
                fromAddr = fromUri.toString();
            }
        }
    }
    Log.debug("SimpleListener(" + myUsername + ").processRequest:  FromAddr = " + fromAddr);
    Log.debug("SimpleListener(" + myUsername + ").processRequest:  Request method = '" + request.getMethod() + "'");
    if (request.getMethod().equals(Request.MESSAGE)) {
        Log.debug("SimpleListener(" + myUsername + ").processRequest:  Starting MESSAGE request handling process.");
        JID senderJid = getSession().getTransport().convertIDToJID(fromAddr);
        String msgContent = new String((byte[]) request.getContent());
        Log.debug("SimpleListener(" + myUsername + ").processRequest:  Forwarding MESSAGE request as XMPP message, setting from = " + senderJid + " and content = '" + msgContent + "'");
        getSession().getTransport().sendMessage(getSession().getJID(), senderJid, msgContent);
        getSession().sendResponse(responseCode, request, serverTransaction);
    } else if (request.getMethod().equals(Request.NOTIFY)) {
        SubscriptionStateHeader subscriptionStateHeader = (SubscriptionStateHeader) request.getHeader(SubscriptionStateHeader.NAME);
        Log.debug("SimpleListener(" + myUsername + ").processRequest:  NOTIFY request handling process started.");
        if (subscriptionStateHeader.getState().equalsIgnoreCase(SubscriptionStateHeader.ACTIVE)) {
            Log.debug("SimpleListener(" + myUsername + ").processRequest:  NOTIFY Active!");
            int expires = subscriptionStateHeader.getExpires();
            Log.debug("SimpleListener(" + myUsername + ").processRequest:  NOTIFY Expiry = " + expires);
            try {
                if (expires > 0) {
                    String content = "";
                    if (request.getContent() != null)
                        content = new String((byte[]) request.getContent());
                    if (content.length() > 0) {
                        SimplePresence simplePresence = SimplePresence.parseSimplePresence(content);
                        try {
                            SimpleBuddy buddy = getSession().getBuddyManager().getBuddy(getSession().getTransport().convertIDToJID(fromAddr));
                            String verboseStatus = null;
                            if (simplePresence.getTupleStatus().isOpen()) {
                                switch(simplePresence.getRpid()) {
                                    case ON_THE_PHONE:
                                        // TODO: Translate this
                                        verboseStatus = "On Phone";
                                }
                            }
                            buddy.setPresenceAndStatus(((SimpleTransport) getSession().getTransport()).convertSIPStatusToXMPP(simplePresence), verboseStatus);
                        } catch (NotFoundException e) {
                            // Not in our contact list.  Ignore.
                            Log.debug("SIMPLE: Received presense notification for contact we don't care about: " + fromAddr);
                        }
                    }
                } else {
                    Presence p = new Presence();
                    p.setType(Presence.Type.unsubscribed);
                    p.setTo(getSession().getJID());
                    p.setFrom(getSession().getTransport().convertIDToJID(fromAddr));
                    getSession().getTransport().sendPacket(p);
                }
                Log.debug("SimpleListener(" + myUsername + ").processRequest:  Sending XMPP presence packet.");
            } catch (Exception ex) {
                Log.debug("SimpleListener(" + myUsername + ").processRequest:  Exception occured when processing NOTIFY packet...", ex);
            }
        } else if (subscriptionStateHeader.getState().equalsIgnoreCase(SubscriptionStateHeader.TERMINATED)) {
            Presence p = new Presence();
            p.setType(Presence.Type.unsubscribed);
            p.setTo(getSession().getJID());
            p.setFrom(getSession().getTransport().convertIDToJID(fromAddr));
            getSession().getTransport().sendPacket(p);
        }
        getSession().sendResponse(responseCode, request, serverTransaction);
    } else if (request.getMethod().equals(Request.SUBSCRIBE)) {
        Log.debug("SimpleListener for " + myUsername + ":  SUBSCRIBE request handling process.");
        ServerTransaction transaction = getSession().sendResponse(202, request, serverTransaction);
        Log.debug("SimpleListener for " + myUsername + ":  SUBSCRIBE should be followed by a NOTIFY");
        // Send NOTIFY packet.
        try {
            if (transaction != null)
                getSession().sendNotify(transaction.getDialog());
            else
                getSession().sendNotify(dialog);
        } catch (Exception e) {
            Log.debug("SimpleListener for " + myUsername + ":  Unable to prepare NOTIFY packet.", e);
        }
    }
}
Also used : Address(javax.sip.address.Address) JID(org.xmpp.packet.JID) FromHeader(javax.sip.header.FromHeader) SubscriptionStateHeader(javax.sip.header.SubscriptionStateHeader) Request(javax.sip.message.Request) NotFoundException(org.jivesoftware.util.NotFoundException) SipURI(javax.sip.address.SipURI) URI(javax.sip.address.URI) SipURI(javax.sip.address.SipURI) NotFoundException(org.jivesoftware.util.NotFoundException) Dialog(javax.sip.Dialog) Presence(org.xmpp.packet.Presence) ServerTransaction(javax.sip.ServerTransaction)

Example 2 with URI

use of javax.sip.address.URI in project jitsi by jitsi.

the class SipMessageFactory method stripReplacesHeader.

/**
     * Returns the <tt>ReplacesHeader</tt> contained, if any, in the
     * <tt>URI</tt> of a specific <tt>Address</tt> after removing it
     * from there.
     *
     * @param address the <tt>Address</tt> which is to have its <tt>URI</tt>
     * examined and modified
     *
     * @return a <tt>Header</tt> which represents the Replaces header contained
     * in the <tt>URI</tt> of the specified <tt>address</tt>; <tt>null</tt> if
     * no such header is present
     *
     * @throws OperationFailedException if we can't parse the replaces header.
     */
private Header stripReplacesHeader(Address address) throws OperationFailedException {
    javax.sip.address.URI uri = address.getURI();
    Header replacesHeader = null;
    if (uri.isSipURI()) {
        SipURI sipURI = (SipURI) uri;
        String replacesHeaderValue = sipURI.getHeader(ReplacesHeader.NAME);
        if (replacesHeaderValue != null) {
            for (Iterator<?> headerNameIter = sipURI.getHeaderNames(); headerNameIter.hasNext(); ) {
                if (ReplacesHeader.NAME.equals(headerNameIter.next())) {
                    headerNameIter.remove();
                    break;
                }
            }
            try {
                replacesHeader = protocolProvider.getHeaderFactory().createHeader(ReplacesHeader.NAME, URLDecoder.decode(replacesHeaderValue, "UTF-8"));
            } catch (Exception ex) {
                //ParseException, EncodingNotSupportedException.
                throw new OperationFailedException("Failed to create ReplacesHeader from " + replacesHeaderValue, OperationFailedException.INTERNAL_ERROR, ex);
            }
        }
    }
    return replacesHeader;
}
Also used : javax.sip.address(javax.sip.address) gov.nist.javax.sip.address(gov.nist.javax.sip.address) URI(javax.sip.address.URI)

Example 3 with URI

use of javax.sip.address.URI in project Openfire by igniterealtime.

the class SipSecurityManager method handleChallenge.

/**
     * Uses securityAuthority to determinie a set of valid user credentials for
     * the specified Response (Challenge) and appends it to the challenged
     * request so that it could be retransmitted.
     * <p/>
     * Fredrik Wickstrom reported that dialog cseq counters are not incremented
     * when resending requests. He later uncovered additional problems and
     * proposed a way to fix them (his proposition was taken into account).
     *
     * @param challenge             the 401/407 challenge response
     * @param challengedTransaction the transaction established by the challenged request
     * @return a transaction containing a reoriginated request with the
     *         necessary authorization header.
     * @throws SipSecurityException
     */
public ClientTransaction handleChallenge(Response challenge, ClientTransaction challengedTransaction) throws SipSecurityException, SipException, InvalidArgumentException, ParseException {
    try {
        String branchID = challengedTransaction.getBranchId();
        Request challengedRequest = challengedTransaction.getRequest();
        Request reoriginatedRequest = (Request) challengedRequest.clone();
        ListIterator authHeaders = null;
        if (challenge == null || reoriginatedRequest == null)
            throw new NullPointerException("A null argument was passed to handle challenge.");
        if (challenge.getStatusCode() == Response.UNAUTHORIZED)
            authHeaders = challenge.getHeaders(WWWAuthenticateHeader.NAME);
        else if (challenge.getStatusCode() == Response.PROXY_AUTHENTICATION_REQUIRED)
            authHeaders = challenge.getHeaders(ProxyAuthenticateHeader.NAME);
        if (authHeaders == null)
            throw new SecurityException("Could not find WWWAuthenticate or ProxyAuthenticate headers");
        // Remove all authorization headers from the request (we'll re-add
        // them
        // from cache)
        reoriginatedRequest.removeHeader(AuthorizationHeader.NAME);
        reoriginatedRequest.removeHeader(ProxyAuthorizationHeader.NAME);
        // rfc 3261 says that the cseq header should be augmented for the
        // new
        // request. do it here so that the new dialog (created together with
        // the new client transaction) takes it into account.
        // Bug report - Fredrik Wickstrom
        CSeqHeader cSeq = (CSeqHeader) reoriginatedRequest.getHeader((CSeqHeader.NAME));
        cSeq.setSequenceNumber(cSeq.getSequenceNumber() + 1);
        ClientTransaction retryTran = transactionCreator.getNewClientTransaction(reoriginatedRequest);
        WWWAuthenticateHeader authHeader = null;
        CredentialsCacheEntry ccEntry = null;
        while (authHeaders.hasNext()) {
            authHeader = (WWWAuthenticateHeader) authHeaders.next();
            String realm = authHeader.getRealm();
            // Check whether we have cached credentials for authHeader's
            // realm
            // make sure that if such credentials exist they get removed.
            // The
            // challenge means that there's something wrong with them.
            ccEntry = cachedCredentials.remove(realm);
            // Try to guess user name and facilitate user
            UserCredentials defaultCredentials = new UserCredentials();
            FromHeader from = (FromHeader) reoriginatedRequest.getHeader(FromHeader.NAME);
            URI uri = from.getAddress().getURI();
            if (uri.isSipURI()) {
                Log.debug("handleChallenge", SIPConfig.getAuthUserName());
                String user = SIPConfig.getAuthUserName() != null ? SIPConfig.getAuthUserName() : ((SipURI) uri).getUser();
                defaultCredentials.setAuthUserName(user == null ? SIPConfig.getUserName() : user);
            }
            boolean ccEntryHasSeenTran = false;
            if (ccEntry != null)
                ccEntryHasSeenTran = ccEntry.processResponse(branchID);
            // get a new pass
            if (// we don't have credentials for the
            ccEntry == null || // specified realm
            ((!authHeader.isStale() && ccEntryHasSeenTran))) {
                if (ccEntry == null) {
                    ccEntry = new CredentialsCacheEntry();
                    ccEntry.userCredentials = defaultCredentials;
                }
                // put the returned user name in the properties file
                // so that it appears as a default one next time user is
                // prompted for pass
                SIPConfig.setUserName(ccEntry.userCredentials.getUserName());
            } else // encode and send what we have
            if (ccEntry != null && (!ccEntryHasSeenTran || authHeader.isStale())) {
            }
            // if user canceled or sth else went wrong
            if (ccEntry.userCredentials == null)
                throw new SecurityException("Unable to authenticate with realm " + realm);
            AuthorizationHeader authorization = this.getAuthorization(reoriginatedRequest.getMethod(), reoriginatedRequest.getRequestURI().toString(), reoriginatedRequest.getContent() == null ? "" : reoriginatedRequest.getContent().toString(), authHeader, ccEntry.userCredentials);
            ccEntry.processRequest(retryTran.getBranchId());
            cachedCredentials.cacheEntry(realm, ccEntry);
            reoriginatedRequest.addHeader(authorization);
            // if there was trouble with the user - make sure we fix it
            if (uri.isSipURI()) {
                ((SipURI) uri).setUser(ccEntry.userCredentials.getUserName());
                Address add = from.getAddress();
                add.setURI(uri);
                from.setAddress(add);
                reoriginatedRequest.setHeader(from);
                if (challengedRequest.getMethod().equals(Request.REGISTER)) {
                    ToHeader to = (ToHeader) reoriginatedRequest.getHeader(ToHeader.NAME);
                    add.setURI(uri);
                    to.setAddress(add);
                    reoriginatedRequest.setHeader(to);
                }
                // very ugly but very necessary
                sipManCallback.setCurrentlyUsedURI(uri.toString());
                Log.debug("URI: " + uri.toString());
            }
        // if this is a register - fix to as well
        }
        return retryTran;
    } catch (Exception e) {
        Log.debug("ERRO REG: " + e.toString());
        return null;
    }
}
Also used : Address(javax.sip.address.Address) ClientTransaction(javax.sip.ClientTransaction) Request(javax.sip.message.Request) ListIterator(java.util.ListIterator) SipURI(javax.sip.address.SipURI) URI(javax.sip.address.URI) SipURI(javax.sip.address.SipURI) SipException(javax.sip.SipException) InvalidArgumentException(javax.sip.InvalidArgumentException) ParseException(java.text.ParseException)

Example 4 with URI

use of javax.sip.address.URI in project Openfire by igniterealtime.

the class SipCommRouter method getNextHops.

/**
     * Return the default address to forward the request to. The list is
     * organized in the following priority.
     * <p/>
     * If the outboung proxy has been specified, then it is used to construct
     * the first element of the list.
     * <p/>
     * If the requestURI refers directly to a host, the host and port
     * information are extracted from it and made the next hop on the list.
     *
     * @param sipRequest is the sip request to route.
     */
public ListIterator<Hop> getNextHops(Request sipRequest) {
    URI requestURI = sipRequest.getRequestURI();
    if (requestURI == null) {
        throw new IllegalArgumentException("Bad message: Null requestURI");
    }
    LinkedList<Hop> hops = new LinkedList<Hop>();
    if (outboundProxy != null) {
        hops.add(outboundProxy);
    }
    ListIterator routes = sipRequest.getHeaders(RouteHeader.NAME);
    if (routes != null && routes.hasNext()) {
        while (routes.hasNext()) {
            RouteHeader route = (RouteHeader) routes.next();
            SipURI uri = (SipURI) route.getAddress().getURI();
            int port = uri.getPort();
            port = (port == -1) ? 5060 : port;
            String host = uri.getHost();
            Log.debug("getNextHops", host);
            String transport = uri.getTransportParam();
            if (transport == null) {
                transport = "udp";
            }
            Hop hop = new SipCommHop(host + ':' + port + '/' + transport);
            hops.add(hop);
        }
    } else if (requestURI instanceof SipURI && ((SipURI) requestURI).getMAddrParam() != null) {
        SipURI sipURI = ((SipURI) requestURI);
        String maddr = sipURI.getMAddrParam();
        String transport = sipURI.getTransportParam();
        if (transport == null) {
            transport = "udp";
        }
        int port = 5060;
        Hop hop = new SipCommHop(maddr, port, transport);
        hops.add(hop);
    } else if (requestURI instanceof SipURI) {
        SipURI sipURI = ((SipURI) requestURI);
        int port = sipURI.getPort();
        if (port == -1) {
            port = 5060;
        }
        String host = sipURI.getHost();
        String transport = sipURI.getTransportParam();
        if (transport == null) {
            transport = "UDP";
        }
        Hop hop = new SipCommHop(host + ":" + port + "/" + transport);
        hops.add(hop);
    } else {
        throw new IllegalArgumentException("Malformed requestURI");
    }
    return (hops.size() == 0) ? null : hops.listIterator();
}
Also used : RouteHeader(javax.sip.header.RouteHeader) Hop(javax.sip.address.Hop) ListIterator(java.util.ListIterator) SipURI(javax.sip.address.SipURI) SipURI(javax.sip.address.SipURI) URI(javax.sip.address.URI) LinkedList(java.util.LinkedList)

Example 5 with URI

use of javax.sip.address.URI in project Openfire by igniterealtime.

the class SimpleListener method processResponse.

public void processResponse(ResponseEvent responseEvent) {
    if (responseEvent.getClientTransaction() != null) {
        Log.debug("SimpleListener for " + myUsername + ":  Getting client transaction...");
        ClientTransaction clientTransaction = responseEvent.getClientTransaction();
        Dialog clientDialog = clientTransaction.getDialog();
        getSession().printDialog(clientDialog);
    }
    Log.debug("SimpleListener for " + myUsername + ":  Received a response event:  " + responseEvent.getResponse().toString());
    //		String   fromAddr = "";
    String toAddr = "";
    Response response = responseEvent.getResponse();
    //		}
    if (response.getHeader(ToHeader.NAME) != null) {
        ToHeader toHeader = (ToHeader) response.getHeader(ToHeader.NAME);
        URI toUri = toHeader.getAddress().getURI();
        if (toUri instanceof SipUri)
            toAddr = ((SipUri) toUri).getUser() + "@" + ((SipUri) toUri).getHost();
        else
            toAddr = toUri.toString();
    }
    if (response.getHeader(CSeqHeader.NAME) != null) {
        String method = ((CSeqHeader) response.getHeader(CSeqHeader.NAME)).getMethod();
        if (method.equals(Request.REGISTER)) {
            if (response.getStatusCode() / 100 == 2) {
                int expires = 0;
                if (response.getHeader(ContactHeader.NAME) != null) {
                    expires = ((ContactHeader) response.getHeader(ContactHeader.NAME)).getExpires();
                } else if (response.getHeader(ExpiresHeader.NAME) != null) {
                    expires = ((ExpiresHeader) response.getHeader(ExpiresHeader.NAME)).getExpires();
                }
                if (expires > 0) {
                    Log.debug("SimpleListener(" + myUsername + ").processResponse:  " + getSession().getRegistration().getUsername() + " log in successful!");
                    getSession().sipUserLoggedIn();
                } else {
                    if (getSession().getLoginStatus().equals(TransportLoginStatus.LOGGING_OUT)) {
                        Log.debug("SimpleListener(" + myUsername + ").processResponse:  " + getSession().getRegistration().getUsername() + " log out successful!");
                        getSession().sipUserLoggedOut();
                        getSession().removeStack();
                    }
                }
            }
        }
        if (method.equals(Request.SUBSCRIBE)) {
            if (response.getStatusCode() / 100 == 2) {
                Log.debug("SimpleListener for " + myUsername + ":  Handling SUBSCRIBE acknowledgement!!");
                int expires = 0;
                if (response.getHeader(ContactHeader.NAME) != null) {
                    expires = ((ContactHeader) response.getHeader(ContactHeader.NAME)).getExpires();
                }
                if (response.getHeader(ExpiresHeader.NAME) != null) {
                    expires = ((ExpiresHeader) response.getHeader(ExpiresHeader.NAME)).getExpires();
                }
                if (expires > 0) {
                    // Confirm subscription of roster item
                    getSession().contactSubscribed(toAddr);
                } else {
                    // Confirm unsubscription of roster item
                    getSession().contactUnsubscribed(toAddr);
                }
                Log.debug("SimpleListener for " + myUsername + ":  Handled SUBSCRIBE acknowledgement!!");
            }
        }
    }
}
Also used : Response(javax.sip.message.Response) CSeqHeader(javax.sip.header.CSeqHeader) Dialog(javax.sip.Dialog) ClientTransaction(javax.sip.ClientTransaction) ToHeader(javax.sip.header.ToHeader) ExpiresHeader(javax.sip.header.ExpiresHeader) SipUri(gov.nist.javax.sip.address.SipUri) URI(javax.sip.address.URI) SipURI(javax.sip.address.SipURI)

Aggregations

URI (javax.sip.address.URI)6 SipURI (javax.sip.address.SipURI)5 ListIterator (java.util.ListIterator)3 ClientTransaction (javax.sip.ClientTransaction)3 Request (javax.sip.message.Request)3 ParseException (java.text.ParseException)2 Dialog (javax.sip.Dialog)2 InvalidArgumentException (javax.sip.InvalidArgumentException)2 SipException (javax.sip.SipException)2 Address (javax.sip.address.Address)2 Hop (javax.sip.address.Hop)2 CSeqHeader (javax.sip.header.CSeqHeader)2 gov.nist.javax.sip.address (gov.nist.javax.sip.address)1 SipUri (gov.nist.javax.sip.address.SipUri)1 SIPRequest (gov.nist.javax.sip.message.SIPRequest)1 SIPClientTransaction (gov.nist.javax.sip.stack.SIPClientTransaction)1 LinkedList (java.util.LinkedList)1 ServerTransaction (javax.sip.ServerTransaction)1 javax.sip.address (javax.sip.address)1 AuthorizationHeader (javax.sip.header.AuthorizationHeader)1