Search in sources :

Example 1 with Address

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

the class SipManager method getFromHeader.

public FromHeader getFromHeader(boolean isNew) throws CommunicationsException {
    if (fromHeader != null && !isNew) {
        return fromHeader;
    }
    try {
        SipURI fromURI = (SipURI) addressFactory.createURI(currentlyUsedURI);
        fromURI.setTransportParam(listeningPoint.getTransport());
        fromURI.setPort(listeningPoint.getPort());
        Address fromAddress = addressFactory.createAddress(fromURI);
        if (displayName != null && displayName.trim().length() > 0) {
            fromAddress.setDisplayName(displayName);
        } else {
            fromAddress.setDisplayName(// UserCredentials.getUser());
            UserCredentials.getUserDisplay());
        // JOptionPane.showMessageDialog(null,currentlyUsedURI);
        }
        fromHeader = headerFactory.createFromHeader(fromAddress, Integer.toString(hashCode()));
    } catch (ParseException ex) {
        throw new CommunicationsException("A ParseException occurred while creating From Header!", ex);
    }
    return fromHeader;
}
Also used : InetSocketAddress(java.net.InetSocketAddress) InetAddress(java.net.InetAddress) Address(javax.sip.address.Address) ParseException(java.text.ParseException) SipURI(javax.sip.address.SipURI) CommunicationsException(org.jivesoftware.openfire.sip.tester.comm.CommunicationsException)

Example 2 with Address

use of javax.sip.address.Address 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 3 with Address

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

the class SimpleSession method prepareRequest.

/**
     * @param requestType Type of request
	 * @param destUri    The SipURI for the destination.  Leave <code>null</code> if a loopback request (e.g. REGISTER) is being made.
	 * @param toTag      The tag for to header.  Can leave null.
	 * @param requestUri The Request URI to set in the message.  Leave null if the default destination SipURI should be used.
     * @param callId     ID of call
     * @param seqNum     Sequence number
     * @return Prepared request
	 */
private Request prepareRequest(RequestType requestType, SipURI destUri, String toTag, SipURI requestUri, String callId, long seqNum) {
    Request request = null;
    String myXMPPUsername = this.jid.getNode();
    Log.debug("SimpleSession(" + myXMPPUsername + ").prepareRequest:  Preparing request packet of type '" + requestType + "'");
    try {
        // Prepare request packet first
        request = messageFactory.createRequest(null);
        request.setMethod(requestType.toString());
    } catch (Exception e) {
        Log.debug("SimpleSession(" + myXMPPUsername + ").prepareRequest:  Exception occured when preparing request.", e);
    }
    // Prepare "From" header
    Log.debug("SimpleSession(" + myXMPPUsername + ").prepareRequest:  Preparing \"From\" header...");
    String mySipUsername = registration.getUsername();
    try {
        SipURI fromUri = addressFactory.createSipURI(mySipUsername, sipHost);
        Address fromNameAddress = addressFactory.createAddress(fromUri);
        fromNameAddress.setDisplayName(mySipUsername);
        FromHeader fromHeader = headerFactory.createFromHeader(fromNameAddress, getTag());
        // Use "set" because this header is mandatory.
        request.setHeader(fromHeader);
    } catch (Exception e) {
        Log.debug("SimpleSession(" + myXMPPUsername + ").prepareRequest:  Exception occured when preparing FromHeader.", e);
        return null;
    }
    // Prepare "To" header
    Log.debug("SimpleSession(" + myXMPPUsername + ").prepareRequest:  Preparing \"To\" header...");
    try {
        if (destUri == null)
            destUri = addressFactory.createSipURI(mySipUsername, sipHost);
        Address toNameAddress = addressFactory.createAddress(destUri);
        ToHeader toHeader = headerFactory.createToHeader(toNameAddress, toTag);
        // Use "set" because this header is mandatory.
        request.setHeader(toHeader);
    } catch (Exception e) {
        Log.debug("SimpleSession(" + myXMPPUsername + ").prepareRequest:  Exception occured when preparing ToHeader.", e);
        return null;
    }
    // Prepare "Via" header
    Log.debug("SimpleSession(" + myXMPPUsername + ").prepareRequest:  Preparing \"Via\" header...");
    try {
        ViaHeader viaHeader = headerFactory.createViaHeader(InetAddress.getLocalHost().getHostAddress(), sipPort, ListeningPoint.UDP, null);
        // Use "set" because this header is mandatory.
        request.setHeader(viaHeader);
    } catch (Exception e) {
        Log.debug("SimpleSession(" + myXMPPUsername + ").prepareRequest:  Exception occured when preparing ViaHeader.", e);
        return null;
    }
    // Prepare "CallId" header
    Log.debug("SimpleSession(" + myXMPPUsername + ").prepareRequest:  Preparing \"CallId\" header...");
    CallIdHeader callIdHeader;
    try {
        if (callId != null)
            callIdHeader = headerFactory.createCallIdHeader(callId);
        else
            callIdHeader = udpSipProvider.getNewCallId();
        // Use "set" because this header is mandatory.
        request.setHeader(callIdHeader);
    } catch (Exception e) {
        Log.debug("SimpleSession(" + myXMPPUsername + ").prepareRequest:  Exception occured when preparing CallIdHeader.", e);
        return null;
    }
    // Prepare "CSeq" header
    Log.debug("SimpleSession(" + myXMPPUsername + ").prepareRequest:  Preparing \"CSeq\" header...");
    try {
        CSeqHeader cSeqHeader = headerFactory.createCSeqHeader(seqNum, requestType.toString());
        // Use "set" because this header is mandatory.
        request.setHeader(cSeqHeader);
    } catch (Exception e) {
        Log.debug("SimpleSession(" + myXMPPUsername + ").prepareRequest:  Exception occured when preparing CSeqHeader.", e);
        return null;
    }
    // Prepare "MaxForwards" header
    Log.debug("SimpleSession(" + myXMPPUsername + ").prepareRequest:  Preparing \"MaxForwards\" header...");
    try {
        MaxForwardsHeader maxForwardsHeader = headerFactory.createMaxForwardsHeader(70);
        // Use "set" because this header is mandatory.
        request.setHeader(maxForwardsHeader);
    } catch (Exception e) {
        Log.debug("SimpleSession(" + myXMPPUsername + ").prepareRequest:  Exception occured when preparing MaxForwardsHeader.", e);
        return null;
    }
    // Setting Request URI
    Log.debug("SimpleSession(" + myXMPPUsername + ").prepareRequest:  setting request URI...");
    try {
        if (requestUri == null) {
            requestUri = (SipURI) destUri.clone();
            requestUri.setTransportParam(ListeningPoint.UDP);
        }
        request.setRequestURI(requestUri);
    } catch (Exception e) {
        Log.debug("SimpleSession(" + myXMPPUsername + ").prepareRequest:  Exception occured when setting request URI.", e);
        return null;
    }
    // Add "Contact" header
    Log.debug("SimpleSession(" + myXMPPUsername + ").prepareRequest:  Preparing \"Contact\" header...");
    try {
        SipURI contactURI = addressFactory.createSipURI(mySipUsername, InetAddress.getLocalHost().getHostAddress());
        contactURI.setPort(sipPort);
        Address contactAddress = addressFactory.createAddress(contactURI);
        contactAddress.setDisplayName(mySipUsername);
        ContactHeader contactHeader = headerFactory.createContactHeader(contactAddress);
        request.setHeader(contactHeader);
    } catch (Exception e) {
        Log.debug("SimpleSession(" + myXMPPUsername + ").prepareRequest:  Exception occured when adding ContactHeader.", e);
        return null;
    }
    return request;
}
Also used : CSeqHeader(javax.sip.header.CSeqHeader) MaxForwardsHeader(javax.sip.header.MaxForwardsHeader) ContactHeader(javax.sip.header.ContactHeader) InetAddress(java.net.InetAddress) Address(javax.sip.address.Address) ViaHeader(javax.sip.header.ViaHeader) FromHeader(javax.sip.header.FromHeader) Request(javax.sip.message.Request) ToHeader(javax.sip.header.ToHeader) CallIdHeader(javax.sip.header.CallIdHeader) SipURI(javax.sip.address.SipURI) InvalidArgumentException(javax.sip.InvalidArgumentException) ParseException(java.text.ParseException) NotFoundException(org.jivesoftware.util.NotFoundException) TooManyListenersException(java.util.TooManyListenersException) SipException(javax.sip.SipException) UserNotFoundException(org.jivesoftware.openfire.user.UserNotFoundException)

Example 4 with Address

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

the class SimpleSession method sendResponse.

public ServerTransaction sendResponse(int status, Request request, ServerTransaction serverTransaction) {
    try {
        Log.debug("SimpleSession(" + jid.getNode() + ").sendResponse:  Starting response sending process.");
        if (serverTransaction == null)
            serverTransaction = udpSipProvider.getNewServerTransaction(request);
        Response response = messageFactory.createResponse(status, request);
        // Set "Exprires" header
        if (request.getHeader(ExpiresHeader.NAME) != null)
            response.setHeader(request.getHeader(ExpiresHeader.NAME));
        // Add "Contact" header
        Log.debug("SimpleSession(" + jid.getNode() + ").sendResponse:  Preparing \"Contact\" header...");
        try {
            SipURI contactURI = addressFactory.createSipURI(null, InetAddress.getLocalHost().getHostAddress());
            contactURI.setPort(sipPort);
            Address contactAddress = addressFactory.createAddress(contactURI);
            //				contactAddress.setDisplayName(mySipUsername);
            ContactHeader contactHeader = headerFactory.createContactHeader(contactAddress);
            response.addHeader(contactHeader);
        } catch (Exception e) {
            Log.debug("SimpleSession(" + jid.getNode() + ").sendResponse:  Exception occured when adding ContactHeader.", e);
        //				return false;	// We can continue with this though.
        }
        Log.debug("SimpleSession(" + jid.getNode() + ").sendResponse:  Sending response:  " + response.toString());
        serverTransaction.sendResponse(response);
        //			udpSipProvider.sendResponse(response);
        Log.debug("SimpleSession(" + jid.getNode() + ").sendResponse:  Response sent!");
        return serverTransaction;
    } catch (Exception ex) {
        Log.debug("SimpleSession(" + jid.getNode() + ").sendResponse:  ", ex);
    }
    return null;
}
Also used : Response(javax.sip.message.Response) ContactHeader(javax.sip.header.ContactHeader) InetAddress(java.net.InetAddress) Address(javax.sip.address.Address) SipURI(javax.sip.address.SipURI) InvalidArgumentException(javax.sip.InvalidArgumentException) ParseException(java.text.ParseException) NotFoundException(org.jivesoftware.util.NotFoundException) TooManyListenersException(java.util.TooManyListenersException) SipException(javax.sip.SipException) UserNotFoundException(org.jivesoftware.openfire.user.UserNotFoundException)

Example 5 with Address

use of javax.sip.address.Address 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)

Aggregations

Address (javax.sip.address.Address)16 SipURI (javax.sip.address.SipURI)14 ParseException (java.text.ParseException)7 InetAddress (java.net.InetAddress)5 Request (javax.sip.message.Request)5 SipException (javax.sip.SipException)4 InvalidArgumentException (javax.sip.InvalidArgumentException)3 FromHeader (javax.sip.header.FromHeader)3 CommunicationsException (org.jivesoftware.openfire.sip.tester.comm.CommunicationsException)3 NotFoundException (org.jivesoftware.util.NotFoundException)3 InetSocketAddress (java.net.InetSocketAddress)2 TooManyListenersException (java.util.TooManyListenersException)2 URI (javax.sip.address.URI)2 ContactHeader (javax.sip.header.ContactHeader)2 SubscriptionStateHeader (javax.sip.header.SubscriptionStateHeader)2 UserNotFoundException (org.jivesoftware.openfire.user.UserNotFoundException)2 SipProfile (android.net.sip.SipProfile)1 ArrayList (java.util.ArrayList)1 ListIterator (java.util.ListIterator)1 Timer (java.util.Timer)1