use of javax.sip.header.Header in project XobotOS by xamarin.
the class SIPHeaderList method getHeadersAsEncodedStrings.
/**
* Return a list of encoded strings (one for each sipheader).
*
* @return LinkedList containing encoded strings in this header list. an
* empty list is returned if this header list contains no sip
* headers.
*/
public List<String> getHeadersAsEncodedStrings() {
List<String> retval = new LinkedList<String>();
ListIterator<HDR> li = hlist.listIterator();
while (li.hasNext()) {
Header sipheader = li.next();
retval.add(sipheader.toString());
}
return retval;
}
use of javax.sip.header.Header in project XobotOS by xamarin.
the class SipUri method equals.
/**
* Compare two URIs and return true if they are equal.
* @param that the object to compare to.
* @return true if the object is equal to this object.
*
* JvB: Updated to define equality in terms of API methods, according to the rules
* in RFC3261 section 19.1.4
*
* Jean Deruelle: Updated to define equality of API methods, according to the rules
* in RFC3261 section 19.1.4 convert potential ie :
* %HEX HEX encoding parts of the URI before comparing them
* transport param added in comparison
* header equality enforced in comparison
*
*/
@SuppressWarnings("unchecked")
@Override
public boolean equals(Object that) {
// Shortcut for same object
if (that == this)
return true;
if (that instanceof SipURI) {
final SipURI a = this;
final SipURI b = (SipURI) that;
// A SIP and SIPS URI are never equivalent
if (a.isSecure() ^ b.isSecure())
return false;
// components must match; comparison of userinfo is case-sensitive
if (a.getUser() == null ^ b.getUser() == null)
return false;
if (a.getUserPassword() == null ^ b.getUserPassword() == null)
return false;
if (a.getUser() != null && !RFC2396UrlDecoder.decode(a.getUser()).equals(RFC2396UrlDecoder.decode(b.getUser())))
return false;
if (a.getUserPassword() != null && !RFC2396UrlDecoder.decode(a.getUserPassword()).equals(RFC2396UrlDecoder.decode(b.getUserPassword())))
return false;
if (a.getHost() == null ^ b.getHost() == null)
return false;
if (a.getHost() != null && !a.getHost().equalsIgnoreCase(b.getHost()))
return false;
if (a.getPort() != b.getPort())
return false;
// URI parameters
for (Iterator i = a.getParameterNames(); i.hasNext(); ) {
String pname = (String) i.next();
String p1 = a.getParameter(pname);
String p2 = b.getParameter(pname);
// those present in both must match (case-insensitive)
if (p1 != null && p2 != null && !RFC2396UrlDecoder.decode(p1).equalsIgnoreCase(RFC2396UrlDecoder.decode(p2)))
return false;
}
// transport, user, ttl or method must match when present in either
if (a.getTransportParam() == null ^ b.getTransportParam() == null)
return false;
if (a.getUserParam() == null ^ b.getUserParam() == null)
return false;
if (a.getTTLParam() == -1 ^ b.getTTLParam() == -1)
return false;
if (a.getMethodParam() == null ^ b.getMethodParam() == null)
return false;
if (a.getMAddrParam() == null ^ b.getMAddrParam() == null)
return false;
// Headers: must match according to their definition.
if (a.getHeaderNames().hasNext() && !b.getHeaderNames().hasNext())
return false;
if (!a.getHeaderNames().hasNext() && b.getHeaderNames().hasNext())
return false;
if (a.getHeaderNames().hasNext() && b.getHeaderNames().hasNext()) {
HeaderFactory headerFactory = null;
try {
headerFactory = SipFactory.getInstance().createHeaderFactory();
} catch (PeerUnavailableException e) {
Debug.logError("Cannot get the header factory to parse the header of the sip uris to compare", e);
return false;
}
for (Iterator i = a.getHeaderNames(); i.hasNext(); ) {
String hname = (String) i.next();
String h1 = a.getHeader(hname);
String h2 = b.getHeader(hname);
if (h1 == null && h2 != null)
return false;
if (h2 == null && h1 != null)
return false;
// The following check should not be needed but we add it for findbugs.
if (h1 == null && h2 == null)
continue;
try {
Header header1 = headerFactory.createHeader(hname, RFC2396UrlDecoder.decode(h1));
Header header2 = headerFactory.createHeader(hname, RFC2396UrlDecoder.decode(h2));
// those present in both must match according to the equals method of the corresponding header
if (!header1.equals(header2))
return false;
} catch (ParseException e) {
Debug.logError("Cannot parse one of the header of the sip uris to compare " + a + " " + b, e);
return false;
}
}
}
// Finally, we can conclude that they are indeed equal
return true;
}
return false;
}
use of javax.sip.header.Header in project smscgateway by RestComm.
the class SipMessageTest method init.
public void init() {
SipFactory sipFactory = null;
sipStack = null;
sipFactory = SipFactory.getInstance();
sipFactory.setPathName("gov.nist");
Properties properties = new Properties();
// If you want to try TCP transport change the following to
String transport = "udp";
String peerHostPort = "127.0.0.1:5060";
properties.setProperty("javax.sip.OUTBOUND_PROXY", peerHostPort + "/" + transport);
// If you want to use UDP then uncomment this.
properties.setProperty("javax.sip.STACK_NAME", "shootist");
// The following properties are specific to nist-sip
// and are not necessarily part of any other jain-sip
// implementation.
// You can set a max message size for tcp transport to
// guard against denial of service attack.
properties.setProperty("gov.nist.javax.sip.MAX_MESSAGE_SIZE", "1048576");
properties.setProperty("gov.nist.javax.sip.DEBUG_LOG", "shootistdebuglog.txt");
properties.setProperty("gov.nist.javax.sip.SERVER_LOG", "shootistlog.txt");
// Drop the client connection after we are done with the transaction.
properties.setProperty("gov.nist.javax.sip.CACHE_CLIENT_CONNECTIONS", "false");
// Set to 0 in your production code for max speed.
// You need 16 for logging traces. 32 for debug + traces.
// Your code will limp at 32 but it is best for debugging.
properties.setProperty("gov.nist.javax.sip.TRACE_LEVEL", "DEBUG");
try {
// Create SipStack object
sipStack = sipFactory.createSipStack(properties);
System.out.println("createSipStack " + sipStack);
} catch (PeerUnavailableException e) {
// could not find
// gov.nist.jain.protocol.ip.sip.SipStackImpl
// in the classpath
e.printStackTrace();
System.err.println(e.getMessage());
System.exit(0);
}
try {
headerFactory = sipFactory.createHeaderFactory();
addressFactory = sipFactory.createAddressFactory();
messageFactory = sipFactory.createMessageFactory();
udpListeningPoint = sipStack.createListeningPoint("127.0.0.1", 5066, "udp");
sipProvider = sipStack.createSipProvider(udpListeningPoint);
SipMessageTest listener = this;
sipProvider.addSipListener(listener);
String fromName = "123456789";
String fromSipAddress = "127.0.0.1:5066";
String fromDisplayName = "123456789";
String toSipAddress = "127.0.0.1:5060";
String toUser = "6666";
String toDisplayName = "6666";
// 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 viaHeaders = new ArrayList();
ViaHeader viaHeader = headerFactory.createViaHeader("127.0.0.1", sipProvider.getListeningPoint(transport).getPort(), transport, null);
// add via headers
viaHeaders.add(viaHeader);
// Create ContentTypeHeader
ContentTypeHeader contentTypeHeader = headerFactory.createContentTypeHeader("text", "plain");
// Create a new CallId header
CallIdHeader callIdHeader = sipProvider.getNewCallId();
// Create a new Cseq header
CSeqHeader cSeqHeader = headerFactory.createCSeqHeader(1L, Request.MESSAGE);
// Create a new MaxForwardsHeader
MaxForwardsHeader maxForwards = headerFactory.createMaxForwardsHeader(70);
// Create the request.
Request request = messageFactory.createRequest(requestURI, Request.MESSAGE, callIdHeader, cSeqHeader, fromHeader, toHeader, viaHeaders, maxForwards);
// Create contact headers
String host = "127.0.0.1";
SipURI contactUrl = addressFactory.createSipURI(fromName, host);
contactUrl.setPort(udpListeningPoint.getPort());
// 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);
// UDH Header
Header udhHeader = headerFactory.createHeader("X-SMS-UDH", "06050413011301");
request.addHeader(udhHeader);
// Add the extension header.
Header extensionHeader = headerFactory.createHeader("My-Header", "my header value");
request.addHeader(extensionHeader);
String s = this.getBody();
byte[] contents = s.getBytes();
request.setContent(contents, contentTypeHeader);
// Create the client transaction.
inviteTid = sipProvider.getNewClientTransaction(request);
// send the request out.
inviteTid.sendRequest();
} catch (Exception ex) {
System.out.println(ex.getMessage());
ex.printStackTrace();
}
}
use of javax.sip.header.Header in project smscgateway by RestComm.
the class RxSipServerSbb method sendMessage.
// *********
// Main service methods
/**
* Sending of a SIP message after initial message or when all sent messages was sent
*
* @param smsSet
* @throws SmscProcessingException
*/
private void sendMessage(SmsSet smsSet) throws SmscProcessingException {
smscStatAggregator.updateMsgOutTryAll();
smscStatAggregator.updateMsgOutTrySip();
Sms sms = this.obtainNextMessage(ProcessingType.SIP);
if (sms == null) {
this.markDeliveringIsEnded(true);
return;
}
try {
// TODO: let make here a special check if SIP is in a good state
// if not - skip sending and set temporary error
String fromAddressStr = sms.getSourceAddr();
String toAddressStr = smsSet.getDestAddr();
Sip sip = sipManagement.getSipByName(SipManagement.SIP_NAME);
ListeningPoint listeningPoint = sipRA.getListeningPoints()[0];
SipURI fromAddressUri = addressFactory.createSipURI(fromAddressStr, listeningPoint.getIPAddress() + ":" + listeningPoint.getPort());
javax.sip.address.Address fromAddress = addressFactory.createAddress(fromAddressUri);
FromHeader fromHeader = headerFactory.createFromHeader(fromAddress, null);
SipURI toAddressUri = addressFactory.createSipURI(toAddressStr, sip.getSipAddress());
javax.sip.address.Address toAddress = addressFactory.createAddress(toAddressUri);
ToHeader toHeader = headerFactory.createToHeader(toAddress, null);
List<ViaHeader> viaHeaders = new ArrayList<ViaHeader>(1);
ViaHeader viaHeader = headerFactory.createViaHeader(listeningPoint.getIPAddress(), listeningPoint.getPort(), listeningPoint.getTransport(), null);
viaHeaders.add(viaHeader);
ContentTypeHeader contentTypeHeader = headerFactory.createContentTypeHeader("text", "plain");
CSeqHeader cSeqHeader = headerFactory.createCSeqHeader(2L, Request.MESSAGE);
MaxForwardsHeader maxForwardsHeader = headerFactory.createMaxForwardsHeader(70);
CallIdHeader callId = this.sipRA.getNewCallId();
String msgStr = sms.getShortMessageText();
byte[] msgUdh = sms.getShortMessageBin();
byte[] msg;
msg = recodeShortMessage(sms.getDataCoding(), msgStr, msgUdh);
// create request
Request request = messageFactory.createRequest(toAddressUri, Request.MESSAGE, callId, cSeqHeader, fromHeader, toHeader, viaHeaders, maxForwardsHeader, contentTypeHeader, msg);
// Custom X Headers
// SMSC-ID
String originEsmeName = sms.getOrigEsmeName();
if (originEsmeName != null) {
Header smsIdHeader = headerFactory.createHeader(SipXHeaders.XSmscId, originEsmeName);
request.addHeader(smsIdHeader);
}
// data-coding
DataCodingScheme dataCodingScheme = new DataCodingSchemeImpl(sms.getDataCoding());
Header smsIdHeader = headerFactory.createHeader(SipXHeaders.XSmsCoding, Integer.toString(dataCodingScheme.getCharacterSet().getCode()));
request.addHeader(smsIdHeader);
// TODO X header message class
// X header delivery time, use SUBMIT_DATE
Date submitDate = sms.getSubmitDate();
if (submitDate != null) {
String submitDateStr = MessageUtil.formatDate(submitDate);
Header submitDateHeader = headerFactory.createHeader(SipXHeaders.XDeliveryTime, submitDateStr);
request.addHeader(submitDateHeader);
}
// Validity Period
Date validityPeriod = sms.getValidityPeriod();
if (validityPeriod != null) {
String validityPeriodStr = MessageUtil.formatDate(validityPeriod);
Header validityHeader = headerFactory.createHeader(SipXHeaders.XSmsValidty, validityPeriodStr);
request.addHeader(validityHeader);
}
// X header UDH
if (msgUdh != null) {
String udhString = hexStringToByteArray(msgUdh);
Header udhHeader = headerFactory.createHeader(SipXHeaders.XSmsUdh, udhString);
request.addHeader(udhHeader);
}
// create client transaction and send request
ClientTransaction clientTransaction = sipRA.getNewClientTransaction(request);
ActivityContextInterface sipClientTxaci = this.sipACIFactory.getActivityContextInterface(clientTransaction);
sipClientTxaci.attach(this.sbbContext.getSbbLocalObject());
clientTransaction.sendRequest();
} catch (Exception e) {
throw new SmscProcessingException("RxSipServerSbb.sendMessage(): Exception while trying to send SIP Message =" + e.getMessage() + "\nMessage: " + sms, 0, 0, SmscProcessingException.HTTP_ERROR_CODE_NOT_SET, null, e);
}
}
use of javax.sip.header.Header in project load-balancer by RestComm.
the class SIPBalancerForwarder method processResponse.
/**
* @param originalRequest
* @param serverTransaction
* @throws ParseException
* @throws SipException
* @throws InvalidArgumentException
* @throws TransactionUnavailableException
*/
/*
* (non-Javadoc)
* @see javax.sip.SipListener#processResponse(javax.sip.ResponseEvent)
*/
public void processResponse(ResponseEvent responseEvent) {
BalancerAppContent content = (BalancerAppContent) responseEvent.getSource();
boolean isIpv6 = content.isIpv6();
SipProvider sipProvider = content.getProvider();
Response originalResponse = responseEvent.getResponse();
if (logger.isDebugEnabled()) {
logger.debug("got response :\n" + originalResponse);
}
updateStats(originalResponse);
final Response response = (Response) originalResponse;
Node senderNode = getSenderNode(response);
if (senderNode != null) {
if (logger.isDebugEnabled()) {
logger.debug("Updating Timestamp of sendernode: " + senderNode);
}
senderNode.updateTimerStamp();
}
// Topmost via headers is me. As it is response to external request
ViaHeader viaHeader = (ViaHeader) response.getHeader(ViaHeader.NAME);
String branch = viaHeader.getBranch();
int versionDelimiter = branch.lastIndexOf('_');
String version = branch.substring(versionDelimiter + 1);
InvocationContext ctx = balancerRunner.getInvocationContext(version);
if (viaHeader != null && !isHeaderExternal(viaHeader.getHost(), viaHeader.getPort(), viaHeader.getTransport(), isIpv6)) {
response.removeFirst(ViaHeader.NAME);
}
viaHeader = (ViaHeader) response.getHeader(ViaHeader.NAME);
String transport = viaHeader.getTransport();
if (viaHeader != null && !isHeaderExternal(viaHeader.getHost(), viaHeader.getPort(), viaHeader.getTransport(), isIpv6)) {
response.removeFirst(ViaHeader.NAME);
}
boolean fromServer = false;
if (balancerRunner.balancerContext.isTwoEntrypoints()) {
if (!isIpv6)
fromServer = sipProvider.equals(balancerRunner.balancerContext.internalSipProvider);
else
fromServer = sipProvider.equals(balancerRunner.balancerContext.internalIpv6SipProvider);
if (logger.isDebugEnabled()) {
if (!isIpv6)
logger.debug("fromServer : " + fromServer + ", sipProvider " + sipProvider + ", internalSipProvider " + balancerRunner.balancerContext.internalSipProvider);
else
logger.debug("fromServer : " + fromServer + ", sipProvider " + sipProvider + ", internalIpv6SipProvider " + balancerRunner.balancerContext.internalIpv6SipProvider);
}
} else {
fromServer = senderNode == null;
if (logger.isDebugEnabled()) {
logger.debug("fromServer : " + fromServer + ", senderNode " + senderNode);
}
}
// only for external responses
if (balancerRunner.balancerContext.isUseWithNexmo && !fromServer) {
viaHeader = (ViaHeader) response.getHeader(ViaHeader.NAME);
if (viaHeader != null) {
if (logger.isDebugEnabled())
logger.debug("We are going to remove rport and received parametres from :" + viaHeader + " from external response");
response.removeFirst(ViaHeader.NAME);
viaHeader.removeParameter("rport");
viaHeader.removeParameter("received");
try {
response.addFirst(viaHeader);
} catch (NullPointerException | SipException e) {
e.printStackTrace();
}
if (logger.isDebugEnabled())
logger.debug("After removing :" + response);
}
}
if (fromServer) {
if (senderNode != null && senderNode.getIp() != null) {
if (balancerRunner.balancerContext.maxRequestNumberWithoutResponse != null && balancerRunner.balancerContext.maxResponseTime != null) {
KeySip keySip = new KeySip(senderNode, isIpv6);
// adding null check for https://github.com/RestComm/load-balancer/issues/83
Node currNode = ctx.sipNodeMap(isIpv6).get(keySip);
if (currNode != null) {
if (logger.isDebugEnabled())
logger.debug("We are going to reset counters of health check" + currNode.getRequestNumberWithoutResponse() + " : " + currNode.getLastTimeResponse());
currNode.setLastTimeResponse(System.currentTimeMillis());
currNode.setRequestNumberWithoutResponse(0);
if (logger.isDebugEnabled())
logger.debug("Counter of request without responses is : " + currNode.getRequestNumberWithoutResponse() + " : " + currNode.getLastTimeResponse());
} else {
logger.warn("Node is null, we will not reset counters");
}
}
mediaFailureDetection(response, ctx, senderNode);
}
/*
if("true".equals(balancerRunner.balancerContext.properties.getProperty("removeNodesOn500Response")) && response.getStatusCode() == 500) {
// If the server is broken remove it from the list and try another one with the next retransmission
if(!(sourceNode instanceof ExtraServerNode)) {
if(balancerRunner.balancerContext.nodes.size()>1) {
balancerRunner.balancerContext.nodes.remove(sourceNode);
balancerRunner.balancerContext.balancerAlgorithm.nodeRemoved(sourceNode);
}
}
}
*/
String publicIp = null;
if (!isIpv6)
publicIp = balancerRunner.balancerContext.publicIP;
else
publicIp = balancerRunner.balancerContext.publicIPv6;
if (publicIp != null && publicIp.trim().length() > 0) {
if (logger.isDebugEnabled()) {
logger.debug("Will add Record-Route header to response with public IP Address: " + publicIp);
}
patchSipMessageForNAT(response, isIpv6);
}
// https://github.com/RestComm/load-balancer/issues/45 Adding sender node for the algorithm to be available
((ResponseExt) response).setApplicationData(senderNode);
ctx.balancerAlgorithm.processInternalResponse(response, isIpv6);
try {
if (logger.isDebugEnabled()) {
logger.debug("from server sending response externally " + response);
}
if (!isIpv6)
balancerRunner.balancerContext.externalSipProvider.sendResponse(response);
else
balancerRunner.balancerContext.externalIpv6SipProvider.sendResponse(response);
} catch (Exception ex) {
logger.error("Unexpected exception while forwarding the response \n" + response, ex);
}
} else {
try {
SIPMessage message = (SIPMessage) response;
String initialRemoteAddr = message.getPeerPacketSourceAddress().getHostAddress();
String initialRemotePort = String.valueOf(message.getPeerPacketSourcePort());
Header remoteAddrHeader = null;
Header remotePortHeader = null;
try {
HeaderFactory hf = SipFactory.getInstance().createHeaderFactory();
remoteAddrHeader = hf.createHeader("X-Sip-Balancer-InitialRemoteAddr", initialRemoteAddr);
remotePortHeader = hf.createHeader("X-Sip-Balancer-InitialRemotePort", initialRemotePort);
} catch (PeerUnavailableException e) {
logger.error("Unexpected exception while creating custom headers for REGISTER message ", e);
} catch (ParseException e) {
logger.error("Unexpected exception while creating custom headers for REGISTER message ", e);
}
if (remoteAddrHeader != null)
response.addHeader(remoteAddrHeader);
if (remotePortHeader != null)
response.addHeader(remotePortHeader);
if (balancerRunner.balancerContext.isTwoEntrypoints()) {
ctx.balancerAlgorithm.processExternalResponse(response, isIpv6);
if (logger.isDebugEnabled()) {
logger.debug("two entry points: from external sending response " + response);
}
if (!isIpv6)
balancerRunner.balancerContext.internalSipProvider.sendResponse(response);
else
balancerRunner.balancerContext.internalIpv6SipProvider.sendResponse(response);
} else {
if (!comesFromInternalNode(response, ctx, initialRemoteAddr, message.getPeerPacketSourcePort(), transport, isIpv6))
ctx.balancerAlgorithm.processExternalResponse(response, isIpv6);
else
ctx.balancerAlgorithm.processInternalResponse(response, isIpv6);
if (logger.isDebugEnabled()) {
logger.debug("one entry point: from external sending response " + response);
}
if (!isIpv6)
balancerRunner.balancerContext.externalSipProvider.sendResponse(response);
else
balancerRunner.balancerContext.externalIpv6SipProvider.sendResponse(response);
}
} catch (Exception ex) {
logger.error("Unexpected exception while forwarding the response \n" + response, ex);
}
}
}
Aggregations