/**
   * Return a reply from a pre-constructed reply. This sends the message back to the entity who
   * caused us to create this channel in the first place.
   *
   * @param sipMessage Message string to send.
   * @throws IOException If there is a problem with sending the message.
   */
  public void sendMessage(SIPMessage sipMessage) throws IOException {
    if (sipStack.isLoggingEnabled() && this.sipStack.isLogStackTraceOnMessageSend()) {
      if (sipMessage instanceof SIPRequest && ((SIPRequest) sipMessage).getRequestLine() != null) {
        /*
         * We dont want to log empty trace messages.
         */
        this.sipStack.getStackLogger().logStackTrace(StackLogger.TRACE_INFO);
      } else {
        this.sipStack.getStackLogger().logStackTrace(StackLogger.TRACE_INFO);
      }
    }

    // Test and see where we are going to send the messsage. If the message
    // is sent back to oursleves, just
    // shortcircuit processing.
    long time = System.currentTimeMillis();
    try {
      for (MessageProcessor messageProcessor : sipStack.getMessageProcessors()) {
        if (messageProcessor.getIpAddress().equals(this.peerAddress)
            && messageProcessor.getPort() == this.peerPort
            && messageProcessor.getTransport().equals(this.peerProtocol)) {
          MessageChannel messageChannel =
              messageProcessor.createMessageChannel(this.peerAddress, this.peerPort);
          if (messageChannel instanceof RawMessageChannel) {
            ((RawMessageChannel) messageChannel).processMessage(sipMessage);
            if (sipStack.isLoggingEnabled(LogWriter.TRACE_DEBUG))
              sipStack.getStackLogger().logDebug("Self routing message");
            return;
          }
        }
      }

      byte[] msg = sipMessage.encodeAsBytes(this.getTransport());

      sendMessage(msg, peerAddress, peerPort, peerProtocol, sipMessage instanceof SIPRequest);

    } catch (IOException ex) {
      throw ex;
    } catch (Exception ex) {
      sipStack.getStackLogger().logError("An exception occured while sending message", ex);
      throw new IOException("An exception occured while sending message");
    } finally {
      if (sipStack.getStackLogger().isLoggingEnabled(ServerLogger.TRACE_MESSAGES)
          && !sipMessage.isNullRequest()) logMessage(sipMessage, peerAddress, peerPort, time);
      else if (sipStack.getStackLogger().isLoggingEnabled(ServerLogger.TRACE_DEBUG))
        sipStack.getStackLogger().logDebug("Sent EMPTY Message");
    }
  }
  protected void processHeader(
      char[] header,
      SIPMessage message,
      ParseExceptionListener parseExceptionListener,
      byte[] msgBuffer)
      throws ParseException {
    if (header == null || header.length == 0) return;

    HeaderParser headerParser = null;
    try {
      headerParser = ParserFactory.createParser(header);
    } catch (ParseException ex) {
      parseExceptionListener.handleException(
          ex, message, null, String.valueOf(header), String.valueOf(msgBuffer));
      return;
    }

    try {
      SIPHeader sipHeader = headerParser.parse();
      message.attachHeader(sipHeader, false);
    } catch (ParseException ex) {
      if (parseExceptionListener != null) {
        String headerName = Lexer.getHeaderName(header);
        Class headerClass = NameMap.getClassFromName(headerName);
        if (headerClass == null) {
          headerClass = ExtensionHeaderImpl.class;
        }
        parseExceptionListener.handleException(
            ex, message, headerClass, String.valueOf(header), String.valueOf(msgBuffer));
      }
    }
  }
      public void run() {
        for (int i = 0; i < messages.length; i++) {
          CharsMsgParser smp = new CharsMsgParser();
          try {
            SIPMessage sipMessage = smp.parseSIPMessage(messages[i].getBytes(), true, true, null);
            System.out.println(
                " i = " + i + " branchId = " + sipMessage.getTopmostVia().getBranch());
            // System.out.println("encoded " +
            // sipMessage.toString());
          } catch (ParseException ex) {
            ex.printStackTrace();
          }

          // System.out.println("dialog id = " +
          // sipMessage.getDialogId(false));
        }
      }
  /**
   * Find the transaction corresponding to a given request.
   *
   * @param sipMessage request for which to retrieve the transaction.
   * @param isServer search the server transaction table if true.
   * @return the transaction object corresponding to the request or null if no such mapping exists.
   */
  public SIPTransaction findTransaction(SIPMessage sipMessage, boolean isServer) {
    SIPTransaction retval = null;

    if (isServer) {
      Via via = sipMessage.getTopmostVia();
      if (via.getBranch() != null) {
        String key = sipMessage.getTransactionId();

        synchronized (this.serverTransactionTable) {
          retval = (SIPTransaction) serverTransactionTable.get(key);
          if (LogWriter.needsLogging) logMessage("looking for key " + key);
          if (retval != null && retval.isMessagePartOfTransaction(sipMessage)) return retval;
        }
      }
      // Need to scan the table for old style transactions (RFC 2543
      // style)
      synchronized (this.serverTransactions) {
        Iterator<SIPServerTransaction> it = serverTransactions.iterator();
        while (it.hasNext()) {
          SIPServerTransaction sipServerTransaction = (SIPServerTransaction) it.next();
          if (sipServerTransaction.isMessagePartOfTransaction(sipMessage))
            return sipServerTransaction;
        }
      }
    } else {
      Via via = sipMessage.getTopmostVia();
      if (via.getBranch() != null) {
        String key = sipMessage.getTransactionId();
        synchronized (this.clientTransactionTable) {
          retval = (SIPTransaction) clientTransactionTable.get(key);
          if (retval != null && retval.isMessagePartOfTransaction(sipMessage)) return retval;
        }
      }
      // Need to scan the table for old style transactions (RFC 2543
      // style)
      synchronized (this.clientTransactions) {
        Iterator<SIPClientTransaction> it = clientTransactions.iterator();
        while (it.hasNext()) {
          SIPClientTransaction clientTransaction = (SIPClientTransaction) it.next();
          if (clientTransaction.isMessagePartOfTransaction(sipMessage)) return clientTransaction;
        }
      }
    }
    return null;
  }
  /**
   * Exception processor for exceptions detected from the parser. (This is invoked by the parser
   * when an error is detected).
   *
   * @param sipMessage -- the message that incurred the error.
   * @param ex -- parse exception detected by the parser.
   * @param header -- header that caused the error.
   * @throws ParseException Thrown if we want to reject the message.
   */
  public void handleException(
      ParseException ex, SIPMessage sipMessage, Class hdrClass, String header, String message)
      throws ParseException {
    if (logger.isLoggingEnabled()) logger.logException(ex);
    // Log the bad message for later reference.
    if ((hdrClass != null)
        && (hdrClass.equals(From.class)
            || hdrClass.equals(To.class)
            || hdrClass.equals(CSeq.class)
            || hdrClass.equals(Via.class)
            || hdrClass.equals(CallID.class)
            || hdrClass.equals(ContentLength.class)
            || hdrClass.equals(RequestLine.class)
            || hdrClass.equals(StatusLine.class))) {
      if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
        logger.logDebug("Encountered Bad Message \n" + sipMessage.toString());
      }

      // JvB: send a 400 response for requests (except ACK)
      // Currently only UDP, @todo also other transports
      String msgString = sipMessage.toString();
      if (!msgString.startsWith("SIP/") && !msgString.startsWith("ACK ")) {
        if (mySock != null) {
          if (logger.isLoggingEnabled(LogWriter.TRACE_ERROR)) {
            logger.logError("Malformed mandatory headers: closing socket! :" + mySock.toString());
          }

          try {
            mySock.close();

          } catch (IOException ie) {
            if (logger.isLoggingEnabled(LogWriter.TRACE_ERROR)) {
              logger.logError(
                  "Exception while closing socket! :" + mySock.toString() + ":" + ie.toString());
            }
          }
        }
      }

      throw ex;
    } else {
      sipMessage.addUnparsed(header);
    }
  }
  /**
   * Return a formatted message to the client. We try to re-connect with the peer on the other end
   * if possible.
   *
   * @param sipMessage Message to send.
   * @throws IOException If there is an error sending the message
   */
  public void sendMessage(SIPMessage sipMessage) throws IOException {
    byte[] msg = sipMessage.encodeAsBytes();

    long time = System.currentTimeMillis();

    this.sendMessage(msg, sipMessage instanceof SIPRequest);

    if (this.stack.serverLog.needsLogging(ServerLog.TRACE_MESSAGES))
      logMessage(sipMessage, peerAddress, peerPort, time);
  }
Exemple #7
0
 /**
  * Log a message into the log directory.
  *
  * @param message a SIPMessage to log
  * @param from from header of the message to log into the log directory
  * @param to to header of the message to log into the log directory
  * @param sender is the server the sender
  * @param time is the time to associate with the message.
  */
 public void logMessage(SIPMessage message, String from, String to, boolean sender, long time) {
   checkLogFile();
   if (message.getFirstLine() == null) return;
   CallID cid = (CallID) message.getCallId();
   String callId = null;
   if (cid != null) callId = cid.getCallId();
   String firstLine = message.getFirstLine().trim();
   String inputText = (logContent ? message.encode() : message.encodeMessage());
   String tid = message.getTransactionId();
   TimeStampHeader tsHdr = (TimeStampHeader) message.getHeader(TimeStampHeader.NAME);
   long tsval = tsHdr == null ? 0 : tsHdr.getTime();
   logMessage(inputText, from, to, sender, callId, firstLine, null, tid, time, tsval);
 }
 /**
  * Exception processor for exceptions detected from the parser. (This is invoked by the parser
  * when an error is detected).
  *
  * @param sipMessage -- the message that incurred the error.
  * @param ex -- parse exception detected by the parser.
  * @param header -- header that caused the error.
  * @throws ParseException Thrown if we want to reject the message.
  */
 public void handleException(
     ParseException ex, SIPMessage sipMessage, Class hdrClass, String header, String message)
     throws ParseException {
   if (LogWriter.needsLogging) stack.logWriter.logException(ex);
   // Log the bad message for later reference.
   if ((hdrClass != null)
       && (hdrClass.equals(From.class)
           || hdrClass.equals(To.class)
           || hdrClass.equals(CSeq.class)
           || hdrClass.equals(Via.class)
           || hdrClass.equals(CallID.class)
           || hdrClass.equals(RequestLine.class)
           || hdrClass.equals(StatusLine.class))) {
     stack.logBadMessage(message);
     throw ex;
   } else {
     sipMessage.addUnparsed(header);
   }
 }
 /**
  * Implementation of the ParseExceptionListener interface.
  *
  * @param ex Exception that is given to us by the parser.
  * @throws ParseException If we choose to reject the header or message.
  */
 public void handleException(
     ParseException ex, SIPMessage sipMessage, Class hdrClass, String header, String message)
     throws ParseException {
   if (sipStack.isLoggingEnabled()) this.sipStack.logWriter.logException(ex);
   // Log the bad message for later reference.
   if ((hdrClass != null)
       && (hdrClass.equals(From.class)
           || hdrClass.equals(To.class)
           || hdrClass.equals(CSeq.class)
           || hdrClass.equals(Via.class)
           || hdrClass.equals(CallID.class)
           || hdrClass.equals(RequestLine.class)
           || hdrClass.equals(StatusLine.class))) {
     sipStack.logWriter.logError("BAD MESSAGE!");
     sipStack.logWriter.logError(message);
     throw ex;
   } else {
     sipMessage.addUnparsed(header);
   }
 }
  /**
   * 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(LogWriter.TRACE_DEBUG)) {
      this.sipStack
          .getStackLogger()
          .logDebug(
              "UDPMessageChannel: processIncomingDataPacket : peerAddress = "
                  + peerAddress.getHostAddress()
                  + "/"
                  + packet.getPort()
                  + " Length = "
                  + packetLength);
    }

    SIPMessage sipMessage = null;
    try {
      this.receptionTime = System.currentTimeMillis();
      sipMessage = myParser.parseSIPMessage(msgBytes, true, false, this);
      //            myParser = null;
    } catch (ParseException ex) {
      //            myParser = null; // let go of the parser reference.
      if (sipStack.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
        this.sipStack.getStackLogger().logDebug("Rejecting message !  " + new String(msgBytes));
        this.sipStack.getStackLogger().logDebug("error message " + ex.getMessage());
        this.sipStack.getStackLogger().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(LogWriter.TRACE_DEBUG)) {
            sipStack.getStackLogger().logDebug("Sending automatic 400 Bad Request:");
            sipStack.getStackLogger().logDebug(badReqRes);
          }
          try {
            this.sendMessage(badReqRes.getBytes(), peerAddress, packet.getPort(), "UDP", false);
          } catch (IOException e) {
            this.sipStack.getStackLogger().logException(e);
          }
        } else {
          if (sipStack.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
            sipStack.getStackLogger().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(LogWriter.TRACE_DEBUG)) {
        this.sipStack.getStackLogger().logDebug("Rejecting message !  + Null message parsed.");
      }
      String key = packet.getAddress().getHostAddress() + ":" + packet.getPort();
      if (pingBackRecord.get(key) == null && sipStack.getMinKeepAliveInterval() > 0) {
        byte[] retval = "\r\n\r\n".getBytes();
        DatagramPacket keepalive =
            new DatagramPacket(retval, 0, retval.length, packet.getAddress(), packet.getPort());
        PingBackTimerTask task =
            new PingBackTimerTask(packet.getAddress().getHostAddress(), packet.getPort());
        this.pingBackRecord.put(key, task);
        this.sipStack.getTimer().schedule(task, sipStack.getMinKeepAliveInterval() * 1000);
        ((UDPMessageProcessor) this.messageProcessor).sock.send(keepalive);
      } else {
        sipStack.getStackLogger().logDebug("Not sending ping back");
      }
      return;
    }
    Via topMostVia = sipMessage.getTopmostVia();
    // Check for the required headers.
    if (sipMessage.getFrom() == null
        || sipMessage.getTo() == null
        || sipMessage.getCallId() == null
        || sipMessage.getCSeq() == null
        || topMostVia == null) {
      String badmsg = new String(msgBytes);
      if (sipStack.isLoggingEnabled()) {
        this.sipStack.getStackLogger().logError("bad message " + badmsg);
        this.sipStack
            .getStackLogger()
            .logError(
                ">>> Dropped Bad Msg "
                    + "From = "
                    + sipMessage.getFrom()
                    + "To = "
                    + sipMessage.getTo()
                    + "CallId = "
                    + sipMessage.getCallId()
                    + "CSeq = "
                    + sipMessage.getCSeq()
                    + "Via = "
                    + sipMessage.getViaHeaders());
      }
      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) {
      Hop hop = sipStack.addressResolver.resolveAddress(topMostVia.getHop());
      this.peerPort = hop.getPort();
      this.peerProtocol = topMostVia.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 = topMostVia.hasParameter(Via.RPORT);
        if (hasRPort || !hop.getHost().equals(this.peerAddress.getHostAddress())) {
          topMostVia.setParameter(Via.RECEIVED, this.peerAddress.getHostAddress());
        }

        if (hasRPort) {
          topMostVia.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 = topMostVia.getTransport();
    }

    this.processMessage(sipMessage);
  }
  /**
   * 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 {
    }
  }
  /**
   * 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);
  }
Exemple #14
0
  /**
   * Logs the specified message and details to the packet logging service if enabled.
   *
   * @param message the message to log
   * @param sender determines whether we are the origin of this message.
   */
  private void logPacket(SIPMessage message, boolean sender) {
    try {
      PacketLoggingService packetLogging = SipActivator.getPacketLogging();
      if (packetLogging == null
          || !packetLogging.isLoggingEnabled(PacketLoggingService.ProtocolName.SIP)
          /* Via not present in CRLF packet on TCP - causes NPE */
          || message.getTopmostVia() == null) return;

      String transport = message.getTopmostVia().getTransport();
      boolean isTransportUDP = transport.equalsIgnoreCase("UDP");

      byte[] srcAddr;
      int srcPort;
      byte[] dstAddr;
      int dstPort;

      // if addresses are not set use empty byte array with length
      // equals to the other address or just empty
      // byte array with length 4 (ipv4 0.0.0.0)
      if (sender) {
        if (!isTransportUDP) {
          InetSocketAddress localAddress =
              getLocalAddressForDestination(
                  message.getRemoteAddress(),
                  message.getRemotePort(),
                  message.getLocalAddress(),
                  transport);
          srcPort = localAddress.getPort();
          srcAddr = localAddress.getAddress().getAddress();
        } else {
          srcPort = message.getLocalPort();
          if (message.getLocalAddress() != null) srcAddr = message.getLocalAddress().getAddress();
          else if (message.getRemoteAddress() != null)
            srcAddr = new byte[message.getRemoteAddress().getAddress().length];
          else srcAddr = new byte[4];
        }

        dstPort = message.getRemotePort();
        if (message.getRemoteAddress() != null) dstAddr = message.getRemoteAddress().getAddress();
        else dstAddr = new byte[srcAddr.length];
      } else {
        if (!isTransportUDP) {
          InetSocketAddress dstAddress =
              getLocalAddressForDestination(
                  message.getRemoteAddress(),
                  message.getRemotePort(),
                  message.getLocalAddress(),
                  transport);
          dstPort = dstAddress.getPort();
          dstAddr = dstAddress.getAddress().getAddress();
        } else {
          dstPort = message.getLocalPort();
          if (message.getLocalAddress() != null) dstAddr = message.getLocalAddress().getAddress();
          else if (message.getRemoteAddress() != null)
            dstAddr = new byte[message.getRemoteAddress().getAddress().length];
          else dstAddr = new byte[4];
        }

        srcPort = message.getRemotePort();
        if (message.getRemoteAddress() != null) srcAddr = message.getRemoteAddress().getAddress();
        else srcAddr = new byte[dstAddr.length];
      }

      byte[] msg = null;
      if (message instanceof SIPRequest) {
        SIPRequest req = (SIPRequest) message;
        if (req.getMethod().equals(SIPRequest.MESSAGE)
            && message.getContentTypeHeader() != null
            && message.getContentTypeHeader().getContentType().equalsIgnoreCase("text")) {
          int len = req.getContentLength().getContentLength();

          if (len > 0) {
            SIPRequest newReq = (SIPRequest) req.clone();

            byte[] newContent = new byte[len];
            Arrays.fill(newContent, (byte) '.');
            newReq.setMessageContent(newContent);
            msg = newReq.toString().getBytes("UTF-8");
          }
        }
      }

      if (msg == null) {
        msg = message.toString().getBytes("UTF-8");
      }

      packetLogging.logPacket(
          PacketLoggingService.ProtocolName.SIP,
          srcAddr,
          srcPort,
          dstAddr,
          dstPort,
          isTransportUDP
              ? PacketLoggingService.TransportName.UDP
              : PacketLoggingService.TransportName.TCP,
          sender,
          msg);
    } catch (Throwable e) {
      logger.error("Cannot obtain message body", e);
    }
  }
  /**
   * Return a formatted message to the client. We try to re-connect with the peer on the other end
   * if possible.
   *
   * @param sipMessage Message to send.
   * @throws IOException If there is an error sending the message
   */
  public void sendMessage(final SIPMessage sipMessage) throws IOException {

    if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG) && !sipMessage.isNullRequest()) {
      logger.logDebug(
          "sendMessage:: "
              + sipMessage.getFirstLine()
              + " cseq method = "
              + sipMessage.getCSeq().getMethod());
    }

    for (MessageProcessor messageProcessor : getSIPStack().getMessageProcessors()) {
      if (messageProcessor.getIpAddress().getHostAddress().equals(this.getPeerAddress())
          && messageProcessor.getPort() == this.getPeerPort()
          && messageProcessor.getTransport().equalsIgnoreCase(this.getPeerProtocol())) {
        Runnable processMessageTask =
            new Runnable() {

              public void run() {
                try {
                  processMessage((SIPMessage) sipMessage.clone());
                } catch (Exception ex) {
                  if (logger.isLoggingEnabled(ServerLogger.TRACE_ERROR)) {
                    logger.logError("Error self routing message cause by: ", ex);
                  }
                }
              }
            };
        getSIPStack().getSelfRoutingThreadpoolExecutor().execute(processMessageTask);

        if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) logger.logDebug("Self routing message");
        return;
      }
    }

    byte[] msg = sipMessage.encodeAsBytes(this.getTransport());

    long time = System.currentTimeMillis();

    // need to store the peerPortAdvertisedInHeaders in case the response has an rport (ephemeral)
    // that failed to retry on the regular via port
    // for responses, no need to store anything for subsequent requests.
    if (peerPortAdvertisedInHeaders <= 0) {
      if (sipMessage instanceof SIPResponse) {
        SIPResponse sipResponse = (SIPResponse) sipMessage;
        Via via = sipResponse.getTopmostVia();
        if (via.getRPort() > 0) {
          if (via.getPort() <= 0) {
            // if port is 0 we assume the default port for TCP
            this.peerPortAdvertisedInHeaders = 5060;
          } else {
            this.peerPortAdvertisedInHeaders = via.getPort();
          }
          if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
            logger.logDebug(
                "1.Storing peerPortAdvertisedInHeaders = "
                    + peerPortAdvertisedInHeaders
                    + " for via port = "
                    + via.getPort()
                    + " via rport = "
                    + via.getRPort()
                    + " and peer port = "
                    + peerPort
                    + " for this channel "
                    + this
                    + " key "
                    + key);
          }
        }
      }
    }

    // JvB: also retry for responses, if the connection is gone we should
    // try to reconnect
    this.sendMessage(msg, sipMessage instanceof SIPRequest);

    // message was sent without any exception so let's set set port and
    // address before we feed it to the logger
    sipMessage.setRemoteAddress(this.peerAddress);
    sipMessage.setRemotePort(this.peerPort);
    sipMessage.setLocalAddress(this.getMessageProcessor().getIpAddress());
    sipMessage.setLocalPort(this.getPort());

    if (logger.isLoggingEnabled(ServerLogger.TRACE_MESSAGES))
      logMessage(sipMessage, peerAddress, peerPort, time);
  }
  /**
   * Gets invoked by the parser as a callback on successful message parsing (i.e. no parser errors).
   *
   * @param sipMessage Message to process (this calls the application for processing the message).
   *     <p>Jvb: note that this code is identical to TCPMessageChannel, refactor some day
   */
  public void processMessage(SIPMessage sipMessage) throws Exception {
    try {
      if (sipMessage.getFrom() == null
          || sipMessage.getTo() == null
          || sipMessage.getCallId() == null
          || sipMessage.getCSeq() == null
          || sipMessage.getViaHeaders() == null) {

        if (logger.isLoggingEnabled()) {
          String badmsg = sipMessage.encode();
          logger.logError("bad message " + badmsg);
          logger.logError(">>> Dropped Bad Msg");
        }
        return;
      }

      sipMessage.setRemoteAddress(this.peerAddress);
      sipMessage.setRemotePort(this.getPeerPort());
      sipMessage.setLocalAddress(this.getMessageProcessor().getIpAddress());
      sipMessage.setLocalPort(this.getPort());
      // Issue 3: https://telestax.atlassian.net/browse/JSIP-3
      sipMessage.setPeerPacketSourceAddress(this.peerAddress);
      sipMessage.setPeerPacketSourcePort(this.peerPort);

      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.getFirst();
        // the peer address and tag it appropriately.
        Hop hop = sipStack.addressResolver.resolveAddress(v.getHop());
        this.peerProtocol = v.getTransport();
        // if(peerPortAdvertisedInHeaders <= 0) {
        int hopPort = v.getPort();
        if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
          logger.logDebug(
              "hop port = "
                  + hopPort
                  + " for request "
                  + sipMessage
                  + " for this channel "
                  + this
                  + " key "
                  + key);
        }
        if (hopPort <= 0) {
          // if port is 0 we assume the default port for TCP
          this.peerPortAdvertisedInHeaders = 5060;
        } else {
          this.peerPortAdvertisedInHeaders = hopPort;
        }
        if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
          logger.logDebug(
              "3.Storing peerPortAdvertisedInHeaders = "
                  + peerPortAdvertisedInHeaders
                  + " for this channel "
                  + this
                  + " key "
                  + key);
        }
        // }
        // may be needed to reconnect, when diff than peer address
        if (peerAddressAdvertisedInHeaders == null) {
          peerAddressAdvertisedInHeaders = hop.getHost();
          if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
            logger.logDebug(
                "3.Storing peerAddressAdvertisedInHeaders = "
                    + peerAddressAdvertisedInHeaders
                    + " for this channel "
                    + this
                    + " key "
                    + key);
          }
        }

        try {
          if (mySock != null) { // selfrouting makes socket = null
            // https://jain-sip.dev.java.net/issues/show_bug.cgi?id=297
            this.peerAddress = mySock.getInetAddress();
          }
          // Check to see if the received parameter matches
          // the peer address and tag it appropriately.

          // JvB: dont do this. It is both costly and incorrect
          // Must set received also when it is a FQDN, regardless
          // whether
          // it resolves to the correct IP address
          // InetAddress sentByAddress =
          // InetAddress.getByName(hop.getHost());
          // JvB: if sender added 'rport', must always set received
          boolean hasRPort = v.hasParameter(Via.RPORT);
          if (!hasRPort && v.getPort() != peerPort) {
            // https://github.com/RestComm/jain-sip/issues/79
            if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
              logger.logDebug(
                  "setting rport since viaPort "
                      + v.getPort()
                      + " different than peerPacketSourcePort "
                      + peerPort
                      + " so that the response can be routed back");
            }
            hasRPort = true;
          }
          if (hasRPort || !hop.getHost().equals(this.peerAddress.getHostAddress())) {
            v.setParameter(Via.RECEIVED, this.peerAddress.getHostAddress());
          }
          // @@@ hagai
          // JvB: technically, may only do this when Via already
          // contains
          // rport
          v.setParameter(Via.RPORT, Integer.toString(this.peerPort));
        } catch (java.text.ParseException ex) {
          InternalErrorHandler.handleException(ex);
        }
        // Use this for outgoing messages as well.
        if (!this.isCached && mySock != null) { // self routing makes
          // mySock=null
          // https://jain-sip.dev.java.net/issues/show_bug.cgi?id=297
          this.isCached = true;
          int remotePort = ((java.net.InetSocketAddress) mySock.getRemoteSocketAddress()).getPort();
          String key = IOHandler.makeKey(mySock.getInetAddress(), remotePort);
          if (this.messageProcessor instanceof NioTcpMessageProcessor) {
            // https://java.net/jira/browse/JSIP-475 don't use iohandler in case of NIO
            // communications of the socket will leak in the iohandler sockettable
            ((NioTcpMessageProcessor) this.messageProcessor)
                .nioHandler.putSocket(key, mySock.getChannel());
          } else {
            sipStack.ioHandler.putSocket(key, mySock);
          }
          // since it can close the socket it needs to be after the mySock usage otherwise
          // it the socket will be disconnected and NPE will be thrown in some edge cases
          ((ConnectionOrientedMessageProcessor) this.messageProcessor).cacheMessageChannel(this);
        }
      }

      // 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 (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
          logger.logDebug("----Processing Message---");
        }
        if (logger.isLoggingEnabled(ServerLogger.TRACE_MESSAGES)) {

          sipStack.serverLogger.logMessage(
              sipMessage,
              this.getPeerHostPort().toString(),
              this.messageProcessor.getIpAddress().getHostAddress()
                  + ":"
                  + this.messageProcessor.getPort(),
              false,
              receptionTime);
        }
        // Check for reasonable size - reject message
        // if it is too long.
        if (sipStack.getMaxMessageSize() > 0
            && sipRequest.getSize()
                    + (sipRequest.getContentLength() == null
                        ? 0
                        : sipRequest.getContentLength().getContentLength())
                > sipStack.getMaxMessageSize()) {
          SIPResponse sipResponse = sipRequest.createResponse(SIPResponse.MESSAGE_TOO_LARGE);
          byte[] resp = sipResponse.encodeAsBytes(this.getTransport());
          this.sendMessage(resp, false);
          throw new Exception("Message size exceeded");
        }

        String sipVersion = ((SIPRequest) sipMessage).getRequestLine().getSipVersion();
        if (!sipVersion.equals("SIP/2.0")) {
          SIPResponse versionNotSupported =
              ((SIPRequest) sipMessage)
                  .createResponse(Response.VERSION_NOT_SUPPORTED, "Bad SIP version " + sipVersion);
          this.sendMessage(versionNotSupported.encodeAsBytes(this.getTransport()), false);
          throw new Exception("Bad version ");
        }

        String method = ((SIPRequest) sipMessage).getMethod();
        String cseqMethod = ((SIPRequest) sipMessage).getCSeqHeader().getMethod();

        if (!method.equalsIgnoreCase(cseqMethod)) {
          SIPResponse sipResponse = sipRequest.createResponse(SIPResponse.BAD_REQUEST);
          byte[] resp = sipResponse.encodeAsBytes(this.getTransport());
          this.sendMessage(resp, false);
          throw new Exception("Bad CSeq method" + sipMessage + " method " + method);
        }

        // Stack could not create a new server request interface.
        // maybe not enough resources.
        ServerRequestInterface sipServerRequest = sipStack.newSIPServerRequest(sipRequest, this);

        if (sipServerRequest != null) {
          try {
            sipServerRequest.processRequest(sipRequest, this);
          } finally {
            if (sipServerRequest instanceof SIPTransaction) {
              SIPServerTransaction sipServerTx = (SIPServerTransaction) sipServerRequest;
              if (!sipServerTx.passToListener()) ((SIPTransaction) sipServerRequest).releaseSem();
            }
          }
        } else {
          if (sipStack.sipMessageValve
              == null) { // Allow message valves to nullify messages without error
            SIPResponse response = sipRequest.createResponse(Response.SERVICE_UNAVAILABLE);

            RetryAfter retryAfter = new RetryAfter();

            // Be a good citizen and send a decent response code back.
            try {
              retryAfter.setRetryAfter((int) (10 * (Math.random())));
              response.setHeader(retryAfter);
              this.sendMessage(response);
            } catch (Exception e) {
              // IGNore
            }
            if (logger.isLoggingEnabled())
              logger.logWarning("Dropping message -- could not acquire semaphore");
          }
        }
      } else {
        SIPResponse sipResponse = (SIPResponse) sipMessage;
        // JvB: dont do this
        // if (sipResponse.getStatusCode() == 100)
        // sipResponse.getTo().removeParameter("tag");
        try {
          sipResponse.checkHeaders();
        } catch (ParseException ex) {
          if (logger.isLoggingEnabled())
            logger.logError("Dropping Badly formatted response message >>> " + sipResponse);
          return;
        }
        // This is a response message - process it.
        // Check the size of the response.
        // If it is too large dump it silently.
        if (sipStack.getMaxMessageSize() > 0
            && sipResponse.getSize()
                    + (sipResponse.getContentLength() == null
                        ? 0
                        : sipResponse.getContentLength().getContentLength())
                > sipStack.getMaxMessageSize()) {
          if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG))
            logger.logDebug("Message size exceeded");
          return;
        }

        ServerResponseInterface sipServerResponse =
            sipStack.newSIPServerResponse(sipResponse, this);
        if (sipServerResponse != null) {
          try {
            if (sipServerResponse instanceof SIPClientTransaction
                && !((SIPClientTransaction) sipServerResponse).checkFromTag(sipResponse)) {
              if (logger.isLoggingEnabled())
                logger.logError("Dropping response message with invalid tag >>> " + sipResponse);
              return;
            }

            sipServerResponse.processResponse(sipResponse, this);
          } finally {
            if (sipServerResponse instanceof SIPTransaction
                && !((SIPTransaction) sipServerResponse).passToListener()) {
              // Note that the semaphore is released in event
              // scanner if the
              // request is actually processed by the Listener.
              ((SIPTransaction) sipServerResponse).releaseSem();
            }
          }
        } else {
          logger.logWarning(
              "Application is blocked -- could not acquire semaphore -- dropping response");
        }
      }
    } finally {
    }
  }
  /**
   * Parse a buffer containing a single SIP Message where the body is an array of un-interpreted
   * bytes. This is intended for parsing the message from a memory buffer when the buffer.
   * Incorporates a bug fix for a bug that was noted by Will Sullin of Callcast
   *
   * @param msgBuffer a byte buffer containing the messages to be parsed. This can consist of
   *     multiple SIP Messages concatenated together.
   * @return a SIPMessage[] structure (request or response) containing the parsed SIP message.
   * @exception ParseException is thrown when an illegal message has been encountered (and the rest
   *     of the buffer is discarded).
   * @see ParseExceptionListener
   */
  public SIPMessage parseSIPMessage(
      byte[] msgBuffer, boolean readBody, boolean strict, ParseExceptionListener exhandler)
      throws ParseException {
    if (msgBuffer == null || msgBuffer.length == 0) return null;

    int i = 0;

    // Squeeze out any leading control character.
    try {
      while (msgBuffer[i] < 0x20) i++;
    } catch (ArrayIndexOutOfBoundsException e) {
      // Array contains only control char, return null.
      return null;
    }

    // Iterate thru the request/status line and headers.
    char[] currentLine = null;
    char[] currentHeader = null;
    boolean isFirstLine = true;
    SIPMessage message = null;
    do {
      currentLine = null;
      int lineStart = i;

      // Find the length of the line.
      try {
        while (msgBuffer[i] != '\r' && msgBuffer[i] != '\n') i++;
      } catch (ArrayIndexOutOfBoundsException e) {
        // End of the message.
        break;
      }
      int lineLength = i - lineStart;

      ByteBuffer bb = ByteBuffer.wrap(msgBuffer, lineStart, lineLength);
      currentLine = charset.decode(bb).array();

      currentLine = trimEndOfLine(currentLine);

      if (currentLine.length == 0) {
        // Last header line, process the previous buffered header.
        if (currentHeader != null && message != null) {
          processHeader(currentHeader, message, exhandler, msgBuffer);
        }

      } else {
        if (isFirstLine) {
          message = processFirstLine(currentLine, exhandler, msgBuffer);
        } else {
          char firstChar = currentLine[0];
          if (firstChar == '\t' || firstChar == ' ') {
            if (currentHeader == null) throw new ParseException("Bad header continuation.", 0);

            // This is a continuation, append it to the previous line.
            //                        currentHeader += currentLine.substring(1);
            char[] retval = new char[currentHeader.length + currentLine.length - 1];
            System.arraycopy(currentHeader, 0, retval, 0, currentHeader.length);
            System.arraycopy(
                currentHeader, currentHeader.length, currentLine, 1, currentLine.length);
          } else {
            if (currentHeader != null && message != null) {
              processHeader(currentHeader, message, exhandler, msgBuffer);
            }
            currentHeader = new char[currentLine.length + 1];
            System.arraycopy(currentLine, 0, currentHeader, 0, currentLine.length);
            currentHeader[currentLine.length] = '\n';
          }
        }
      }

      if (msgBuffer[i] == '\r' && msgBuffer.length > i + 1 && msgBuffer[i + 1] == '\n') i++;

      i++;

      isFirstLine = false;
    } while (currentLine.length > 0); // End do - while

    currentLine = null;
    currentHeader = null;

    if (message == null) throw new ParseException("Bad message", 0);
    message.setSize(i);

    // Check for content legth header
    if (readBody && message.getContentLength() != null) {
      if (message.getContentLength().getContentLength() != 0) {
        int bodyLength = msgBuffer.length - i;

        byte[] body = new byte[bodyLength];
        System.arraycopy(msgBuffer, i, body, 0, bodyLength);
        message.setMessageContent(
            body,
            !strict,
            computeContentLengthFromMessage,
            message.getContentLength().getContentLength());
      } else if (!computeContentLengthFromMessage
          && message.getContentLength().getContentLength() == 0 & strict) {
        String last4Chars = new String(msgBuffer, msgBuffer.length - 4, 4);
        if (!"\r\n\r\n".equals(last4Chars)) {
          throw new ParseException("Extraneous characters at the end of the message ", i);
        }
      }
    }

    return message;
  }