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);
}
}
}
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;
}
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;
}
}
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();
}
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!!");
}
}
}
}
Aggregations