/** * Creates a TelURL based on given URI string. The scheme or '+' should not be included in the * phoneNumber string argument. * * @param uri - the new string value of the phoneNumber. * @throws URISyntaxException if the URI string is malformed. */ public javax.sip.address.TelURL createTelURL(String uri) throws ParseException { if (uri == null) throw new NullPointerException("null url"); String telUrl = "tel:" + uri; try { StringMsgParser smp = new StringMsgParser(); TelURLImpl timp = (TelURLImpl) smp.parseUrl(telUrl); return (TelURL) timp; } catch (ParseException ex) { throw new ParseException(ex.getMessage(), 0); } }
/** * create a sip uri. * * @param uri -- the uri to parse. */ public javax.sip.address.SipURI createSipURI(String uri) // throws java.net.URISyntaxException { throws ParseException { if (uri == null) throw new NullPointerException("null URI"); try { StringMsgParser smp = new StringMsgParser(); SipUri sipUri = smp.parseSIPUrl(uri); return (SipURI) sipUri; } catch (ParseException ex) { // throw new java.net.URISyntaxException(uri, ex.getMessage()); throw new ParseException(ex.getMessage(), 0); } }
/** * Creates an Address with the new address string value. The address string is parsed in order to * create the new Address instance. Create with a String value of "*" creates a wildcard address. * The wildcard can be determined if <code>((SipURI)Address.getURI).getUser() == *;</code>. * * @param address - the new string value of the address. * @throws ParseException which signals that an error has been reached unexpectedly while parsing * the address value. */ public javax.sip.address.Address createAddress(String address) throws java.text.ParseException { if (address == null) throw new NullPointerException("null address"); if (address.equals("*")) { AddressImpl addressImpl = new AddressImpl(); addressImpl.setAddressType(AddressImpl.WILD_CARD); SipURI uri = new SipUri(); uri.setUser("*"); addressImpl.setURI(uri); return addressImpl; } else { StringMsgParser smp = new StringMsgParser(); return smp.parseAddress(address); } }
/** Run method specified by runnnable. */ public void run() { // Assume no thread pooling (bug fix by spierhj) ThreadAuditor.ThreadHandle threadHandle = null; while (true) { // Create a new string message parser to parse the list of messages. if (myParser == null) { myParser = new StringMsgParser(); myParser.setParseExceptionListener(this); } // messages that we write out to him. DatagramPacket packet; if (sipStack.threadPoolSize != -1) { synchronized (((UDPMessageProcessor) messageProcessor).messageQueue) { while (((UDPMessageProcessor) messageProcessor).messageQueue.isEmpty()) { // Check to see if we need to exit. if (!((UDPMessageProcessor) messageProcessor).isRunning) return; try { // We're part of a thread pool. Ask the auditor to // monitor this thread. if (threadHandle == null) { threadHandle = sipStack.getThreadAuditor().addCurrentThread(); } // Send a heartbeat to the thread auditor threadHandle.ping(); // Wait for packets // Note: getPingInterval returns 0 (infinite) if the // thread auditor is disabled. ((UDPMessageProcessor) messageProcessor) .messageQueue.wait(threadHandle.getPingIntervalInMillisecs()); } catch (InterruptedException ex) { if (!((UDPMessageProcessor) messageProcessor).isRunning) return; } } packet = (DatagramPacket) ((UDPMessageProcessor) messageProcessor).messageQueue.removeFirst(); } this.incomingPacket = packet; } else { packet = this.incomingPacket; } // Process the packet. Catch and log any exception we may throw. try { processIncomingDataPacket(packet); } catch (Exception e) { sipStack.logWriter.logError("Error while processing incoming UDP packet", e); } if (sipStack.threadPoolSize == -1) { return; } } }
/** * Create a SipURI * * @param user -- the user * @param host -- the host. */ public javax.sip.address.SipURI createSipURI(String user, String host) throws ParseException { if (host == null) throw new NullPointerException("null host"); StringBuffer uriString = new StringBuffer("sip:"); if (user != null) { uriString.append(user); uriString.append("@"); } // if host is an IPv6 string we should enclose it in sq brackets if (host.indexOf(':') != host.lastIndexOf(':') && host.trim().charAt(0) != '[') host = '[' + host + ']'; uriString.append(host); StringMsgParser smp = new StringMsgParser(); try { SipUri sipUri = smp.parseSIPUrl(uriString.toString()); return sipUri; } catch (ParseException ex) { throw new ParseException(ex.getMessage(), 0); } }
/** * This is input reading thread for the pipelined parser. You feed it input through the input * stream (see the constructor) and it calls back an event listener interface for message * processing or error. It cleans up the input - dealing with things like line continuation */ public void run() { Pipeline inputStream = this.rawInputStream; // inputStream = new MyFilterInputStream(this.rawInputStream); // I cannot use buffered reader here because we may need to switch // encodings to read the message body. try { while (true) { this.sizeCounter = this.maxMessageSize; // this.messageSize = 0; StringBuffer inputBuffer = new StringBuffer(); if (Debug.parserDebug) Debug.println("Starting parse!"); String line1; String line2 = null; while (true) { try { line1 = readLine(inputStream); // ignore blank lines. if (line1.equals("\n")) { if (Debug.parserDebug) Debug.println("Discarding " + line1); continue; } else break; } catch (IOException ex) { Debug.printStackTrace(ex); this.rawInputStream.stopTimer(); return; } } inputBuffer.append(line1); // Guard against bad guys. this.rawInputStream.startTimer(); while (true) { try { line2 = readLine(inputStream); inputBuffer.append(line2); if (line2.trim().equals("")) break; } catch (IOException ex) { this.rawInputStream.stopTimer(); Debug.printStackTrace(ex); return; } } // Stop the timer that will kill the read. this.rawInputStream.stopTimer(); inputBuffer.append(line2); StringMsgParser smp = new StringMsgParser(sipMessageListener); smp.readBody = false; SIPMessage sipMessage = null; try { sipMessage = smp.parseSIPMessage(inputBuffer.toString()); if (sipMessage == null) { this.rawInputStream.stopTimer(); continue; } } catch (ParseException ex) { // Just ignore the parse exception. continue; } if (Debug.parserDebug) Debug.println("Completed parsing message"); ContentLength cl = (ContentLength) sipMessage.getContentLength(); int contentLength = 0; if (cl != null) { contentLength = cl.getContentLength(); } else { contentLength = 0; } if (Debug.parserDebug) { Debug.println("contentLength " + contentLength); Debug.println("sizeCounter " + this.sizeCounter); Debug.println("maxMessageSize " + this.maxMessageSize); } if (contentLength == 0) { sipMessage.removeContent(); } else if (maxMessageSize == 0 || contentLength < this.sizeCounter) { byte[] message_body = new byte[contentLength]; int nread = 0; while (nread < contentLength) { // Start my starvation timer. // This ensures that the other end // writes at least some data in // or we will close the pipe from // him. This prevents DOS attack // that takes up all our connections. this.rawInputStream.startTimer(); try { int readlength = inputStream.read(message_body, nread, contentLength - nread); if (readlength > 0) { nread += readlength; } else { break; } } catch (IOException ex) { ex.printStackTrace(); break; } finally { // Stop my starvation timer. this.rawInputStream.stopTimer(); } } sipMessage.setMessageContent(message_body); } // Content length too large - process the message and // return error from there. if (sipMessageListener != null) { try { sipMessageListener.processMessage(sipMessage); } catch (Exception ex) { // fatal error in processing - close the // connection. break; } } } } finally { try { inputStream.close(); } catch (IOException e) { InternalErrorHandler.handleException(e); } } }
/** Called by the sax parser when the start of an element is encountered. */ public void startElement(String nameSpaceURI, String local, String name, Attributes attrs) throws SAXException { try { Debug.println("processing " + name); if (name.compareTo(TagNames.CALLFLOW) == 0) { callFlow = new CallFlow(); callFlow.instantiateOn = attrs.getValue(Attr.instantiateOn); callFlow.description = attrs.getValue(Attr.description); } else if (name.compareTo(TagNames.AGENT) == 0) { Agent agent = new Agent(); agent.agentId = attrs.getValue(Attr.agentId); agent.userName = attrs.getValue(Attr.userName); agent.requestURI = attrs.getValue(Attr.requestURI); agent.host = attrs.getValue(Attr.host); agent.contactPort = attrs.getValue(Attr.contactPort); agent.contactHost = attrs.getValue(Attr.contactHost); addAgent(agent); } else if (name.compareTo(TagNames.EXPECT) == 0) { // Make sure there are no unexpected attributes. for (int i = 0; i < attrs.getLength(); i++) { String attrname = attrs.getLocalName(i); if (attrname.equals(Attr.enablingEvent) || attrname.equals(Attr.triggerMessage) || attrname.equals(Attr.generatedEvent) || attrname.equals(Attr.nodeId) || attrname.equals(Attr.onTrigger) || attrname.equals(Attr.onCompletion)) continue; else throw new SAXException( "Unkown attribute in expect: nodeId = " + attrs.getValue(Attr.nodeId) + " attribute name = " + attrname); } String enablingEvent = attrs.getValue(Attr.enablingEvent); String triggerMessage = attrs.getValue(Attr.triggerMessage); String generatedEvent = attrs.getValue(Attr.generatedEvent); String nodeId = attrs.getValue(Attr.nodeId); currentExpectNode = new Expect(callFlow, enablingEvent, generatedEvent, triggerMessage); String onTrigger = attrs.getValue(Attr.onTrigger); String onCompletion = attrs.getValue(Attr.onCompletion); currentExpectNode.onTrigger = onTrigger; currentExpectNode.onCompletion = onCompletion; currentExpectNode.nodeId = nodeId; } else if (name.compareTo(TagNames.SIP_REQUEST) == 0) { if (this.messageTemplateContext) { // This is a SIPRequest template node. for (int i = 0; i < attrs.getLength(); i++) { String attrname = attrs.getLocalName(i); if (!attrs.getLocalName(i).equals(Attr.templateId)) throw new SAXException( "Unkown attribute in SIP_REQUEST node " + " attribute name = " + attrname); } messageTemplate = new SIPRequest(); id = attrs.getValue(Attr.templateId); jythonCode = null; } } else if (name.compareTo(TagNames.SIP_RESPONSE) == 0) { if (this.messageTemplateContext) { messageTemplate = new SIPResponse(); jythonCode = null; for (int i = 0; i < attrs.getLength(); i++) { String attrname = attrs.getLocalName(i); if (!attrs.getLocalName(i).equals(Attr.templateId)) throw new SAXException( "Unkown attribute in SIP_REQUEST node " + " attribute name = " + attrname); } id = attrs.getValue(Attr.templateId); } } else if (name.compareTo(TagNames.STATUS_LINE) == 0) { String scode = attrs.getValue(Attr.statusCode); if (messageTemplateContext) { StatusLine statusLine = new StatusLine(); try { int statusCode = Integer.parseInt(scode); statusLine.setStatusCode(statusCode); } catch (NumberFormatException ex) { throw new SAXException(ex.getMessage()); } SIPResponse response = (SIPResponse) this.messageTemplate; response.setStatusLine(statusLine); } else { int statusCode = Integer.parseInt(scode); generatedMessage.addStatusLine(statusCode); } } else if (name.compareTo(TagNames.REQUEST_LINE) == 0) { String method = attrs.getValue(Attr.method); Debug.println("tagname = " + TagNames.REQUEST_LINE); Debug.println("messageTemplateContext = " + messageTemplateContext); if (messageTemplateContext) { for (int i = 0; i < attrs.getLength(); i++) { String attrname = attrs.getLocalName(i); if (attrs.getLocalName(i).equals(Attr.requestURI) || attrs.getLocalName(i).equals(Attr.method)) continue; else throw new SAXException( "Unkown attribute in REQUEST_LINE node " + " attribute name = " + attrname); } requestLine = new RequestLine(); requestLine.setMethod(method); String requestURI = attrs.getValue(Attr.requestURI); StringMsgParser smp = new StringMsgParser(); if (requestURI != null) { try { URI uri = smp.parseSIPUrl(requestURI); requestLine.setUri(uri); } catch (SIPParseException e) { throw new SAXException("Bad URL " + requestURI); } } SIPRequest request = (SIPRequest) messageTemplate; request.setRequestLine(requestLine); } else { for (int i = 0; i < attrs.getLength(); i++) { String attrname = attrs.getLocalName(i); if (attrs.getLocalName(i).equals(Attr.method) || attrs.getLocalName(i).equals(Attr.templateId) || attrs.getLocalName(i).equals(Attr.agentId)) continue; else throw new SAXException( "Unkown attribute in REQUEST_LINE node " + " attribute name = " + attrname); } String requestURI = attrs.getValue(Attr.requestURI); if (requestURI == null) { String agentId = attrs.getValue(Attr.agentId); if (agentId != null) { Agent agent = getAgent(agentId); if (agent == null) throw new SAXException("Missing requestURI or agent attribute"); requestURI = agent.requestURI; } } generatedMessage.addRequestLine(method, requestURI); } } else if (name.compareTo(TagNames.FROM) == 0) { for (int i = 0; i < attrs.getLength(); i++) { String attrname = attrs.getLocalName(i); if (attrs.getLocalName(i).equals(Attr.displayName) || attrs.getLocalName(i).equals(Attr.userName) || attrs.getLocalName(i).equals(Attr.host) || attrs.getLocalName(i).equals(Attr.agentId)) continue; else throw new SAXException( "Unkown attribute in FROM node " + " attribute name = " + attrname); } String displayName = attrs.getValue(Attr.displayName); String userName = attrs.getValue(Attr.userName); String hostName = attrs.getValue(Attr.host); String agentId = attrs.getValue(Attr.agentId); if (agentId != null) { Agent agent = getAgent(agentId); if (agent == null) throw new SAXException("agent not found " + agentId); if (displayName == null) displayName = agent.displayName; if (userName == null) userName = agent.userName; if (hostName == null) hostName = agent.host; } if (this.messageTemplateContext) { From from = new From(); Address address = new Address(); address.setDisplayName(displayName); URI uri = new URI(); Host host = new Host(); host.setHostname(hostName); uri.setHost(host); uri.setUser(userName); address.setAddrSpec(uri); from.setAddress(address); try { messageTemplate.attachHeader(from, false); } catch (SIPDuplicateHeaderException ex) { throw new SAXException(ex.getMessage()); } } else { generatedMessage.addFromHeader(displayName, userName, hostName); } } else if (name.compareTo(TagNames.TO) == 0) { for (int i = 0; i < attrs.getLength(); i++) { String attrname = attrs.getLocalName(i); if (attrs.getLocalName(i).equals(Attr.templateId) || attrs.getLocalName(i).equals(Attr.host) || attrs.getLocalName(i).equals(Attr.agentId) || attrs.getLocalName(i).equals(Attr.userName)) continue; else throw new SAXException( "Unkown attribute in FROM node " + " attribute name = " + attrname); } String displayName = attrs.getValue(Attr.displayName); String userName = attrs.getValue(Attr.userName); String hostName = attrs.getValue(Attr.host); String agentId = attrs.getValue(Attr.agentId); if (agentId != null) { Agent agent = getAgent(agentId); if (agent == null) throw new SAXException("agent not found " + agentId); if (displayName == null) displayName = agent.displayName; if (userName == null) userName = agent.userName; if (hostName == null) hostName = agent.host; } if (this.messageTemplateContext) { To to = new To(); Address address = new Address(); address.setDisplayName(displayName); URI uri = new URI(); Host host = new Host(); host.setHostname(hostName); uri.setHost(host); uri.setUser(userName); address.setAddrSpec(uri); to.setAddress(address); try { messageTemplate.attachHeader(to, false); } catch (SIPDuplicateHeaderException ex) { throw new SAXException(ex.getMessage()); } } else { generatedMessage.addToHeader(displayName, userName, hostName); } } else if (name.compareTo(TagNames.CALLID) == 0) { String lid = attrs.getValue(Attr.localId); String host = attrs.getValue(Attr.host); if (this.messageTemplateContext) { CallID cid = new CallID(); CallIdentifier cidf = new CallIdentifier(lid, host); cid.setCallIdentifier(cidf); } else { generatedMessage.addCallIdHeader(); } } else if (name.compareTo(TagNames.CONTACT) == 0) { for (int i = 0; i < attrs.getLength(); i++) { String attrname = attrs.getLocalName(i); if (attrs.getLocalName(i).equals(Attr.displayName) || attrs.getLocalName(i).equals(Attr.userName) || attrs.getLocalName(i).equals(Attr.action) || attrs.getLocalName(i).equals(Attr.contactHost) || attrs.getLocalName(i).equals(Attr.contactPort) || attrs.getLocalName(i).equals(Attr.agentId) || attrs.getLocalName(i).equals(Attr.expires)) continue; else throw new SAXException( "Unkown attribute in CONTACT node " + " attribute name = " + attrname); } String displayName = attrs.getValue(Attr.displayName); String userName = attrs.getValue(Attr.userName); String hostName = attrs.getValue(Attr.contactHost); String portString = attrs.getValue(Attr.contactPort); String expiryTimeString = attrs.getValue(Attr.expires); String action = attrs.getValue(Attr.action); String agentId = attrs.getValue(Attr.agentId); if (action == null) action = "proxy"; if (agentId != null) { Agent agent = getAgent(agentId); if (displayName == null) displayName = agent.displayName; if (userName == null) userName = agent.userName; if (hostName == null) hostName = agent.contactHost; if (portString == null) portString = agent.contactPort; } if (this.messageTemplateContext) { // Generating a message template for the expires header. ContactList clist = new ContactList(); Contact contact = new Contact(); clist.add(contact); URI uri = new URI(); Host host = new Host(); host.setHostname(hostName); uri.setHost(host); uri.setUser(userName); if (portString != null) { int port = new Integer(portString).intValue(); uri.setPort(port); } Address address = new Address(); address.setAddrSpec(uri); contact.setAddress(address); if (expiryTimeString != null) { long expiryTimeSec = new Long(expiryTimeString).longValue(); contact.setExpires(expiryTimeSec); } messageTemplate.attachHeader(clist, false); } else { int port = 5060; if (portString != null) port = new Integer(portString).intValue(); long expiryTimeSec = 3600; if (expiryTimeString != null) { expiryTimeSec = new Long(expiryTimeString).longValue(); } if (userName == null) throw new Exception("Missing attribute userName"); if (action == null) action = Attr.proxy; String uri; if (hostName == null) { uri = SIPKeywords.SIP + Separators.COLON + userName + Separators.AT + EventEngine.theStack.getHostAddress() + Separators.COLON + EventEngine.theStack.getDefaultPort() + Separators.SEMICOLON + SIPKeywords.TRANSPORT + Separators.EQUALS + EventEngine.theStack.getDefaultTransport(); } else uri = SIPKeywords.SIP + Separators.COLON + userName + Separators.AT + hostName + ":" + port; generatedMessage.addContactHeader(displayName, uri, expiryTimeSec, action); } } else if (name.compareTo(TagNames.GENERATE) == 0) { generateContext = true; if (currentExpectNode == null) { throw new SAXException("Bad element nesting."); } String id = attrs.getValue(Attr.messageId); String retransmit = attrs.getValue(Attr.retransmit); String delayString = attrs.getValue(Attr.delay); int delay = 0; if (delayString != null) { try { delay = Integer.parseInt(delayString); } catch (NumberFormatException ex) { throw new SAXException("Bad integer value " + delayString); } } generatedMessage = new GeneratedMessage(id, callFlow, currentExpectNode, retransmit); generatedMessage.delay = delay; currentExpectNode.addGeneratedMessage(generatedMessage); } else if (name.compareTo(TagNames.MESSAGE_TEMPLATES) == 0) { messageTemplateContext = true; } else if (name.compareTo(TagNames.JYTHON_CODE) == 0) { this.jythonCode = null; } else if (name.compareTo(TagNames.STATE_MACHINE) == 0) { } else if (name.compareTo(TagNames.AGENTS) == 0) { } else { throw new SAXException("Unkown tag " + name); } } catch (Exception ex) { ex.printStackTrace(); ex.fillInStackTrace(); throw new SAXException(ex.getMessage()); } }
/** * Process an incoming datagram * * @param packet is the incoming datagram packet. */ private void processIncomingDataPacket(DatagramPacket packet) throws Exception { this.peerAddress = packet.getAddress(); int packetLength = packet.getLength(); // Read bytes and put it in a eueue. byte[] bytes = packet.getData(); byte[] msgBytes = new byte[packetLength]; System.arraycopy(bytes, 0, msgBytes, 0, packetLength); // Do debug logging. if (sipStack.isLoggingEnabled()) { this.sipStack.logWriter.logDebug( "UDPMessageChannel: processIncomingDataPacket : peerAddress = " + peerAddress.getHostAddress() + "/" + packet.getPort() + " Length = " + packetLength); } SIPMessage sipMessage = null; try { this.receptionTime = System.currentTimeMillis(); sipMessage = myParser.parseSIPMessage(msgBytes); myParser = null; } catch (ParseException ex) { myParser = null; // let go of the parser reference. if (sipStack.isLoggingEnabled()) { this.sipStack.logWriter.logDebug("Rejecting message ! " + new String(msgBytes)); this.sipStack.logWriter.logDebug("error message " + ex.getMessage()); this.sipStack.logWriter.logException(ex); } // JvB: send a 400 response for requests (except ACK) // Currently only UDP, @todo also other transports String msgString = new String(msgBytes, 0, packetLength); if (!msgString.startsWith("SIP/") && !msgString.startsWith("ACK ")) { String badReqRes = createBadReqRes(msgString, ex); if (badReqRes != null) { if (sipStack.isLoggingEnabled()) { sipStack.getLogWriter().logDebug("Sending automatic 400 Bad Request:"); sipStack.getLogWriter().logDebug(badReqRes); } try { this.sendMessage(badReqRes.getBytes(), peerAddress, packet.getPort(), "UDP", false); } catch (IOException e) { this.sipStack.logWriter.logException(e); } } else { if (sipStack.isLoggingEnabled()) { sipStack.getLogWriter().logDebug("Could not formulate automatic 400 Bad Request"); } } } return; } // No parse exception but null message - reject it and // march on (or return). // exit this message processor if the message did not parse. if (sipMessage == null) { if (sipStack.isLoggingEnabled()) { this.sipStack.logWriter.logDebug("Rejecting message ! + Null message parsed."); } return; } ViaList viaList = sipMessage.getViaHeaders(); // Check for the required headers. if (sipMessage.getFrom() == null || sipMessage.getTo() == null || sipMessage.getCallId() == null || sipMessage.getCSeq() == null || sipMessage.getViaHeaders() == null) { String badmsg = new String(msgBytes); if (sipStack.isLoggingEnabled()) { this.sipStack.logWriter.logError("bad message " + badmsg); this.sipStack.logWriter.logError( ">>> Dropped Bad Msg " + "From = " + sipMessage.getFrom() + "To = " + sipMessage.getTo() + "CallId = " + sipMessage.getCallId() + "CSeq = " + sipMessage.getCSeq() + "Via = " + sipMessage.getViaHeaders()); } sipStack.logWriter.logError("BAD MESSAGE!"); return; } // For a request first via header tells where the message // is coming from. // For response, just get the port from the packet. if (sipMessage instanceof SIPRequest) { Via v = (Via) viaList.getFirst(); Hop hop = sipStack.addressResolver.resolveAddress(v.getHop()); this.peerPort = hop.getPort(); this.peerProtocol = v.getTransport(); this.peerPacketSourceAddress = packet.getAddress(); this.peerPacketSourcePort = packet.getPort(); try { this.peerAddress = packet.getAddress(); // Check to see if the received parameter matches // the peer address and tag it appropriately. boolean hasRPort = v.hasParameter(Via.RPORT); if (hasRPort || !hop.getHost().equals(this.peerAddress.getHostAddress())) { v.setParameter(Via.RECEIVED, this.peerAddress.getHostAddress()); } if (hasRPort) { v.setParameter(Via.RPORT, Integer.toString(this.peerPacketSourcePort)); } } catch (java.text.ParseException ex1) { InternalErrorHandler.handleException(ex1); } } else { this.peerPacketSourceAddress = packet.getAddress(); this.peerPacketSourcePort = packet.getPort(); this.peerAddress = packet.getAddress(); this.peerPort = packet.getPort(); this.peerProtocol = ((Via) viaList.getFirst()).getTransport(); } this.processMessage(sipMessage); }