use of javax.sip.address.SipURI 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;
}
}
use of javax.sip.address.SipURI in project Openfire by igniterealtime.
the class RegisterProcessing method processOK.
void processOK(ClientTransaction clientTransatcion, Response response) {
isRegistered = true;
FromHeader fromHeader = ((FromHeader) response.getHeader(FromHeader.NAME));
Address address = fromHeader.getAddress();
int expires = 0;
if (!isUnregistering) {
ContactHeader contactHeader = (ContactHeader) response.getHeader(ContactHeader.NAME);
// TODO check if the registrar created the contact address
if (contactHeader != null) {
expires = contactHeader.getExpires();
} else {
ExpiresHeader expiresHeader = response.getExpires();
if (expiresHeader != null) {
expires = expiresHeader.getExpires();
}
}
}
// fix by Luca Bincoletto <Luca.Bincoletto@tilab.com>
if (expires == 0) {
isUnregistering = false;
sipManCallback.fireUnregistered(address.toString());
} else {
if (reRegisterTimer != null)
reRegisterTimer.cancel();
if (keepAliveTimer != null)
keepAliveTimer.cancel();
reRegisterTimer = new Timer();
keepAliveTimer = new Timer();
// if (expires > 0 && expires < 60) {
// [issue 2] Schedule re registrations
// bug reported by LynlvL@netscape.com
// use the value returned by the server to reschedule
// registration
SipURI uri = (SipURI) address.getURI();
scheduleReRegistration(uri.getHost(), uri.getPort(), uri.getTransportParam(), expires);
// }
/*
* else{ SipURI uri = (SipURI) address.getURI();
* scheduleReRegistration(uri.getHost(), uri.getServerPort(),
* uri.getTransportParam(), expires); }
*/
sipManCallback.fireRegistered(address.toString());
}
}
use of javax.sip.address.SipURI in project Openfire by igniterealtime.
the class RegisterProcessing method register.
synchronized void register(String registrarAddress, int registrarPort, String registrarTransport, int expires) throws CommunicationsException {
try {
isUnregistering = false;
// From
FromHeader fromHeader = sipManCallback.getFromHeader(true);
Address fromAddress = fromHeader.getAddress();
sipManCallback.fireRegistering(fromAddress.toString());
// Request URI
SipURI requestURI = null;
try {
requestURI = sipManCallback.addressFactory.createSipURI(null, registrarAddress);
} catch (ParseException ex) {
throw new CommunicationsException("Bad registrar address:" + registrarAddress, ex);
} catch (NullPointerException ex) {
// Do not throw an exc, we should rather silently notify the
// user
// throw new CommunicationsException("A registrar address was
// not specified!", ex);
sipManCallback.fireUnregistered(fromAddress.getURI().toString() + " (registrar not specified)");
return;
}
requestURI.setPort(registrarPort);
try {
requestURI.setTransportParam(registrarTransport);
} catch (ParseException ex) {
throw new CommunicationsException(registrarTransport + " is not a valid transport!", ex);
}
// Call ID Header
CallIdHeader callIdHeader = sipManCallback.sipProvider.getNewCallId();
// CSeq Header
CSeqHeader cSeqHeader = null;
try {
cSeqHeader = sipManCallback.headerFactory.createCSeqHeader(1, Request.REGISTER);
} catch (ParseException ex) {
// Should never happen
Log.error("register", ex);
} catch (InvalidArgumentException ex) {
// Should never happen
Log.error("register", ex);
}
// To Header
ToHeader toHeader = null;
try {
toHeader = sipManCallback.headerFactory.createToHeader(fromAddress, null);
} catch (ParseException ex) {
// throw was missing - reported by Eero Vaarnas
throw new CommunicationsException("Could not create a To header " + "for address:" + fromHeader.getAddress(), ex);
}
// User Agent Header
UserAgentHeader uaHeader = null;
ArrayList<String> userAgentList = new ArrayList<String>();
userAgentList.add(SIPConfig.getStackName());
try {
uaHeader = sipManCallback.headerFactory.createUserAgentHeader(userAgentList);
} catch (ParseException ex) {
// throw was missing - reported by Eero Vaarnas
throw new CommunicationsException("Could not create a To header " + "for address:" + fromHeader.getAddress(), ex);
}
// Via Headers
ArrayList viaHeaders = sipManCallback.getLocalViaHeaders();
// MaxForwardsHeader
MaxForwardsHeader maxForwardsHeader = sipManCallback.getMaxForwardsHeader();
// Request
Request request = null;
try {
request = sipManCallback.messageFactory.createRequest(requestURI, Request.REGISTER, callIdHeader, cSeqHeader, fromHeader, toHeader, viaHeaders, maxForwardsHeader);
request.setHeader(uaHeader);
} catch (ParseException ex) {
// throw was missing - reported by Eero Vaarnas
throw new CommunicationsException("Could not create the register request!", ex);
}
// Expires Header
ExpiresHeader expHeader = null;
for (int retry = 0; retry < 2; retry++) {
try {
expHeader = sipManCallback.headerFactory.createExpiresHeader(expires);
} catch (InvalidArgumentException ex) {
if (retry == 0) {
expires = 3600;
continue;
}
throw new CommunicationsException("Invalid registrations expiration parameter - " + expires, ex);
}
}
request.addHeader(expHeader);
// Contact Header should contain IP - bug report - Eero Vaarnas
ContactHeader contactHeader = sipManCallback.getRegistrationContactHeader();
request.addHeader(contactHeader);
// Transaction
ClientTransaction regTrans = null;
try {
regTrans = sipManCallback.sipProvider.getNewClientTransaction(request);
} catch (TransactionUnavailableException ex) {
// throw was missing - reported by Eero Vaarnas
throw new CommunicationsException("Could not create a register transaction!\n" + "Check that the Registrar address is correct!");
}
try {
regTrans.sendRequest();
}// we sometimes get a null pointer exception here so catch them all
catch (Exception ex) {
// throw was missing - reported by Eero Vaarnas
throw new CommunicationsException("Could not send out the register request!", ex);
}
this.registerRequest = request;
} catch (Exception e) {
Log.error("register", e);
}
}
use of javax.sip.address.SipURI 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);
}
}
}
use of javax.sip.address.SipURI 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;
}
Aggregations