/** * This gets invoked when thread.start is called from the constructor. Implements a message loop - * reading the tcp connection and processing messages until we are done or the other end has * closed. */ public void run() { String message; Pipeline hispipe = null; // Create a pipeline to connect to our message parser. hispipe = new Pipeline(myClientInputStream, stack.readTimeout, ((SIPTransactionStack) stack).timer); // Create a pipelined message parser to read and parse // messages that we write out to him. myParser = new PipelinedMsgParser(this, hispipe, this.stack.getMaxMessageSize()); // Start running the parser thread. myParser.processInput(); // bug fix by Emmanuel Proulx int bufferSize = 4096; this.tlsMessageProcessor.useCount++; this.isRunning = true; try { while (true) { try { byte[] msg = new byte[bufferSize]; int nbytes = myClientInputStream.read(msg, 0, bufferSize); // no more bytes to read... if (nbytes == -1) { hispipe.write("\r\n\r\n".getBytes("UTF-8")); try { if (stack.maxConnections != -1) { synchronized (tlsMessageProcessor) { tlsMessageProcessor.nConnections--; tlsMessageProcessor.notify(); } } hispipe.close(); mySock.close(); } catch (IOException ioex) { } return; } hispipe.write(msg, 0, nbytes); } catch (IOException ex) { // Terminate the message. try { hispipe.write("\r\n\r\n".getBytes("UTF-8")); } catch (Exception e) { // InternalErrorHandler.handleException(e); } try { if (LogWriter.needsLogging) stack.logWriter.logMessage("IOException closing sock " + ex); try { if (stack.maxConnections != -1) { synchronized (tlsMessageProcessor) { tlsMessageProcessor.nConnections--; tlsMessageProcessor.notify(); } } mySock.close(); hispipe.close(); } catch (IOException ioex) { } } catch (Exception ex1) { // Do nothing. } return; } catch (Exception ex) { InternalErrorHandler.handleException(ex); } } } finally { this.isRunning = false; this.tlsMessageProcessor.remove(this); this.tlsMessageProcessor.useCount--; } }
/** * 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); } } }
/** * Gets invoked by the parser as a callback on successful message parsing (i.e. no parser errors). * * @param sipMessage Mesage to process (this calls the application for processing the message). */ public void processMessage(SIPMessage sipMessage) throws Exception { try { if (sipMessage.getFrom() == null || // sipMessage.getFrom().getTag() == null || sipMessage.getTo() == null || sipMessage.getCallId() == null || sipMessage.getCSeq() == null || sipMessage.getViaHeaders() == null) { String badmsg = sipMessage.encode(); if (LogWriter.needsLogging) { stack.logWriter.logMessage("bad message " + badmsg); stack.logWriter.logMessage(">>> Dropped Bad Msg"); } stack.logBadMessage(badmsg); return; } ViaList viaList = sipMessage.getViaHeaders(); // For a request // first via header tells where the message is coming from. // For response, this has already been recorded in the outgoing // message. if (sipMessage instanceof SIPRequest) { Via v = (Via) viaList.first(); if (v.hasPort()) { this.peerPort = v.getPort(); } else this.peerPort = 5061; this.peerProtocol = v.getTransport(); try { this.peerAddress = mySock.getInetAddress(); // Check to see if the received parameter matches // the peer address and tag it appropriately. // Bug fix by [email protected] // Should record host address not host name // bug fix by Joost Yervante Damand if (!v.getSentBy().getInetAddress().equals(this.peerAddress)) { v.setParameter(Via.RECEIVED, this.peerAddress.getHostAddress()); // @@@ hagai v.setParameter(Via.RPORT, new Integer(this.peerPort).toString()); } } catch (java.net.UnknownHostException ex) { // Could not resolve the sender address. if (LogWriter.needsLogging) { stack.logWriter.logMessage("Rejecting message -- could not resolve Via Address"); } return; } catch (java.text.ParseException ex) { InternalErrorHandler.handleException(ex); } // Use this for outgoing messages as well. if (!this.isCached) { ((TLSMessageProcessor) this.messageProcessor).cacheMessageChannel(this); this.isCached = true; String key = IOHandler.makeKey(mySock.getInetAddress(), this.peerPort); stack.ioHandler.putSocket(key, mySock); } } // Foreach part of the request header, fetch it and process it long receptionTime = System.currentTimeMillis(); // if (sipMessage instanceof SIPRequest) { // This is a request - process the request. SIPRequest sipRequest = (SIPRequest) sipMessage; // Create a new sever side request processor for this // message and let it handle the rest. if (LogWriter.needsLogging) { stack.logWriter.logMessage("----Processing Message---"); } // Check for reasonable size - reject message // if it is too long. if (stack.getMaxMessageSize() > 0 && sipRequest.getSize() + (sipRequest.getContentLength() == null ? 0 : sipRequest.getContentLength().getContentLength()) > stack.getMaxMessageSize()) { SIPResponse sipResponse = sipRequest.createResponse(SIPResponse.MESSAGE_TOO_LARGE); byte[] resp = sipResponse.encodeAsBytes(); this.sendMessage(resp, false); throw new Exception("Message size exceeded"); } ServerRequestInterface sipServerRequest = stack.newSIPServerRequest(sipRequest, this); sipServerRequest.processRequest(sipRequest, this); if (this.stack.serverLog.needsLogging(ServerLog.TRACE_MESSAGES)) { if (sipServerRequest.getProcessingInfo() == null) { stack.serverLog.logMessage( sipMessage, sipRequest.getViaHost() + ":" + sipRequest.getViaPort(), stack.getHostAddress() + ":" + stack.getPort(this.getTransport()), false, receptionTime); } else { this.stack.serverLog.logMessage( sipMessage, sipRequest.getViaHost() + ":" + sipRequest.getViaPort(), stack.getHostAddress() + ":" + stack.getPort(this.getTransport()), sipServerRequest.getProcessingInfo(), false, receptionTime); } } } else { SIPResponse sipResponse = (SIPResponse) sipMessage; // This is a response message - process it. // Check the size of the response. // If it is too large dump it silently. if (stack.getMaxMessageSize() > 0 && sipResponse.getSize() + (sipResponse.getContentLength() == null ? 0 : sipResponse.getContentLength().getContentLength()) > stack.getMaxMessageSize()) { if (LogWriter.needsLogging) this.stack.logWriter.logMessage("Message size exceeded"); return; } ServerResponseInterface sipServerResponse = stack.newSIPServerResponse(sipResponse, this); sipServerResponse.processResponse(sipResponse, this); } } finally { } }