2 new revisions:

Revision: 28992c836220
Author:   vralev <vralev@8e71dc83-d81e-6649-80f2-80b843a9b2be>
Date:     Thu Jul 19 14:20:11 2012
Log:      Update Issue 12...
http://code.google.com/p/jain-sip/source/detail?r=28992c836220

Revision: fa54ad06c966
Author:   vralev <vralev@8e71dc83-d81e-6649-80f2-80b843a9b2be>
Date:     Wed Aug  8 12:20:08 2012
Log:      Update Issue 12...
http://code.google.com/p/jain-sip/source/detail?r=fa54ad06c966

==============================================================================
Revision: 28992c836220
Author:   vralev <vralev@8e71dc83-d81e-6649-80f2-80b843a9b2be>
Date:     Thu Jul 19 14:20:11 2012
Log:      Update Issue 12

Backport to TelScale branch

JSIP-416
Savepoint for TCP/TLS reconnect cleanup.

git-svn-id: https://svn.java.net/svn/jsip~svn/branches/JAIN-SIP-NIO-year-2012@2134 8e71dc83-d81e-6649-80f2-80b843a9b2be
(cherry picked from commit 1f1bf55b1475eef08c04e904a8d865c0f35a91ca)

http://code.google.com/p/jain-sip/source/detail?r=28992c836220

Modified:
 /src/gov/nist/javax/sip/stack/ConnectionOrientedMessageChannel.java
 /src/gov/nist/javax/sip/stack/NIOHandler.java
 /src/gov/nist/javax/sip/stack/NioTcpMessageChannel.java
 /src/gov/nist/javax/sip/stack/NioTcpMessageProcessor.java
 /src/gov/nist/javax/sip/stack/NioTlsMessageChannel.java

=======================================
--- /src/gov/nist/javax/sip/stack/ConnectionOrientedMessageChannel.java Thu May 31 13:40:31 2012 +++ /src/gov/nist/javax/sip/stack/ConnectionOrientedMessageChannel.java Thu Jul 19 14:20:11 2012
@@ -302,7 +302,7 @@
                 // the peer address and tag it appropriately.
Hop hop = sipStack.addressResolver.resolveAddress(v.getHop());
                 this.peerProtocol = v.getTransport();
-                if(peerPortAdvertisedInHeaders <= 0) {
+                //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);
@@ -316,7 +316,7 @@
                        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();
=======================================
--- /src/gov/nist/javax/sip/stack/NIOHandler.java       Fri Jul  6 15:40:57 2012
+++ /src/gov/nist/javax/sip/stack/NIOHandler.java       Thu Jul 19 14:20:11 2012
@@ -129,8 +129,7 @@
* writes can occur from multiple threads. We write in chunks to allow the
      * other side to synchronize for large sized writes.
      */
- private void writeChunks(SocketChannel channel, byte[] bytes, int length)
-            throws IOException {
+ private void writeChunks(SocketChannel channel, byte[] bytes, int length) {
         // Chunk size is 16K - this hack is for large
         // writes over slow connections.
         synchronized (channel) {
@@ -184,9 +183,15 @@
             SocketChannel clientSock = null;
             keyedSemaphore.enterIOCriticalSection(key);

+            boolean newSocket = false;
             try {
                 clientSock = getSocket(key);
                 while (retry_count < max_retry) {
+ if(clientSock != null && (!clientSock.isConnected() | | !clientSock.isOpen()) ) {
+                               removeSocket(key);
+                               clientSock = null;
+                               newSocket = true;
+                       }
                     if (clientSock == null) {
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
                             logger.logDebug(
@@ -202,52 +207,25 @@
// the IP address is on a per listening point basis.
                         try {
clientSock = messageProcessor.blockingConnect(new InetSocketAddress(receiverAddress, contactPort), 10000);
+                               newSocket = true;
                                //sipStack.getNetworkLayer().createSocket(
// receiverAddress, contactPort, senderAddress); TODO: sender address needed } catch (SocketException e) { // We must catch the socket timeout exceptions here, any SocketException not just ConnectException
                                logger.logError("Problem connecting " +
- receiverAddress + " " + contactPort + " " + senderAddress + " for message " + new String(bytes, "UTF-8")); + receiverAddress + " " + contactPort + " " + senderAddress + " for message " + (messageChannel.isSecure()?"<<<ENCRYPTED MESSAGE>>>":new String(bytes, "UTF-8")));
                                // new connection is bad.
// remove from our table the socket and its semaphore
                                removeSocket(key);
throw new SocketException(e.getClass() + " " + e.getMessage() + " " + e.getCause() + " Problem connecting " + receiverAddress + " " + contactPort + " " + senderAddress + " for message " + new String(bytes, "UTF-8"));
                         }
-                        writeChunks(clientSock, bytes, length);
                         putSocket(key, clientSock);
                         break;
                     } else {
-                        try {
-                            writeChunks(clientSock, bytes, length);
-                            break;
-                        } catch (IOException ex) {
-                            if (logger
-                                    .isLoggingEnabled(LogWriter.TRACE_WARN))
-                                logger.logWarning(
-                                        "IOException occured retryCount "
-                                                + retry_count);
-                            try {
-                                clientSock.close();
-                            } catch (Exception e) {
-                            }
-                            clientSock = null;
-                            retry_count++;
- // This is a server tx trying to send a response.
-                            if ( !isClient ) {
-                                                               
removeSocket(key);
-                                throw ex;
-                            }
-                            if(retry_count >= max_retry) {
-                                                               // old 
connection is bad.
-                                                               // remove from 
our table the socket and its semaphore
-                                                               
removeSocket(key);
-                                                       } else {
-                                                               // don't remove 
the semaphore on retry
-                                                               
socketTable.remove(key);
-                                                       }
-                        }
+                       break;
                     }
                 }
+
             } catch (IOException ex) {
                 if (logger.isLoggingEnabled(LogWriter.TRACE_ERROR)) {
                     logger.logError(
@@ -285,12 +263,12 @@
                 if (!isClient) {
                     receiverAddress = InetAddress.getByName(messageChannel
                             .getViaHost());
-                    contactPort = messageChannel.getViaPort();
-                    if (contactPort == -1)
+ contactPort = messageChannel.peerPortAdvertisedInHeaders;
+                    if (contactPort <= 0)
                         contactPort = 5060;

                     key = makeKey(receiverAddress, messageChannel
-                            .getViaPort());
+                            .peerPortAdvertisedInHeaders);
                     clientSock = this.getSocket(key);
                     if (clientSock == null) {
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
@@ -299,45 +277,36 @@
                                     " port = " + contactPort);
                         }
clientSock = messageProcessor.blockingConnect(new InetSocketAddress(receiverAddress, contactPort), 10000);
-
-
-                        writeChunks(clientSock, bytes, length);
+                                               newSocket = true;
+                                               messageChannel.peerPort = 
contactPort;
                         putSocket(key, clientSock);
-                        return clientSock;
-                    } else {
- if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
-                            logger.logDebug(
-                                    "sending to " + key );
-                        }
-                        try {
-                            writeChunks(clientSock, bytes, length);
-                            return clientSock;
-                        } catch (IOException ioe) {
-                            if (logger
-                                    .isLoggingEnabled(LogWriter.TRACE_ERROR))
-                                logger.logError(
-                                        "IOException occured  ", ioe);
-                            if (logger
-                                    .isLoggingEnabled(LogWriter.TRACE_DEBUG))
-                                logger.logDebug(
-                                        "Removing and Closing socket");
-                            // old connection is bad.
-                            // remove from our table.
-                            removeSocket(key);
-                            try {
-                                clientSock.close();
-                            } catch (Exception e) {
-                            }
-                            clientSock = null;
-                            throw ioe;
-                        }
+                    }
+
+                    if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
+                       logger.logDebug(
+                                       "sending to " + key );
                     }
+
+
                 } else {
                     logger.logError("IOException occured at " , ex);
                     throw ex;
                 }
+
+                return clientSock;
             } finally {
-                keyedSemaphore.leaveIOCriticalSection(key);
+               try {
+                       if(clientSock != null) {
+ if(newSocket && messageChannel instanceof NioTlsMessageChannel) {
+                                       //messageChannel.onNewSocket();
+                               } else {
+                                       writeChunks(clientSock, bytes, length);
+                               }
+                       }
+
+               } finally {
+                       keyedSemaphore.leaveIOCriticalSection(key);
+               }
             }

             if (clientSock == null) {
=======================================
--- /src/gov/nist/javax/sip/stack/NioTcpMessageChannel.java Mon Jul 16 02:49:59 2012 +++ /src/gov/nist/javax/sip/stack/NioTcpMessageChannel.java Thu Jul 19 14:20:11 2012
@@ -228,102 +228,14 @@
logger.logDebug("sendMessage isClient = " + isClient + " this = " + this);
                }
                lastActivityTimeStamp = System.currentTimeMillis();
-               /*
-                * /* Patch from [email protected] (Issue 119 ) This patch 
avoids the
-                * case where two TCPMessageChannels are now pointing to the 
same
-                * socket.getInputStream().
-                *
-                * JvB 22/5 removed
-                */
-               SocketChannel sock = null;
+
NIOHandler nioHandler = ((NioTcpMessageProcessor) messageProcessor).nioHandler; if(this.socketChannel != null && this.socketChannel.isConnected() && this.socketChannel.isOpen()) { nioHandler.putSocket(NIOHandler.makeKey(this.peerAddress, this.peerPort), this.socketChannel);
                }
-               IOException problem = null;
-               try {
- sock = ((NioTcpMessageProcessor) messageProcessor).nioHandler.sendBytes(this.messageProcessor
-                                       .getIpAddress(), this.peerAddress, 
this.peerPort,
-                                       this.peerProtocol, msg, isClient, this);
-               } catch (IOException any) {
-                       problem = any;
-                       logger.logWarning("Failed to connect " + this.peerAddress + 
":"
-                                       + this.peerPort + " but trying the 
advertised port="
-                                       + this.peerPortAdvertisedInHeaders
-                                       + " if it's different than the port we just 
failed on");
-               }
-               if (sock == null) { // If we couldn't connect to the host, try 
the
-                                                       // advertised port as 
failsafe
-                       if (this.peerPort != this.peerPortAdvertisedInHeaders
-                                       && peerPortAdvertisedInHeaders > 0) { 
// no point in trying
-                                                                               
                                        // same port
-                               logger.logWarning("Couldn't connect to peerAddress = 
"
-                                               + peerAddress + " peerPort = " + peerPort 
+ " key = "
-                                               + key + " retrying on 
peerPortAdvertisedInHeaders "
-                                               + peerPortAdvertisedInHeaders);
-
- sock = ((NioTcpMessageProcessor) messageProcessor).nioHandler.sendBytes(this.messageProcessor
-                                               .getIpAddress(), 
this.peerAddress,
-                                               
this.peerPortAdvertisedInHeaders, this.peerProtocol,
-                                               msg, isClient, this);
-                               this.peerPort = 
this.peerPortAdvertisedInHeaders;
-                               this.key = MessageChannel.getKey(peerAddress, peerPort, 
"TCP");
-                               logger.logWarning("retry suceeded to peerAddress = 
"
-                                               + peerAddress + " 
peerPortAdvertisedInHeaders = "
-                                               + peerPortAdvertisedInHeaders + " 
key = " + key);
-                       } else {
-                               throw problem; // throw the original excpetion 
we had from the
-                                                               // first attempt
-                       }
-               }
-
-               // Created a new socket so close the old one and stick the new
-               // one in its place but dont do this if it is a datagram socket.
-               // (could have replied via udp but received via tcp!).
-               // if (mySock == null && s != null) {
-               // this.uncache();
-               // } else
-               if (sock != socketChannel && sock != null) {
-                       if (socketChannel != null) {
-                               if 
(logger.isLoggingEnabled(LogWriter.TRACE_WARN)) {
-                                       logger
-                                                       .logWarning("Old socket 
different than new socket on channel "
-                                                                       + sock + " 
" + socketChannel);
-                                       logger.logStackTrace();
-                                       logger.logWarning("Old socket local ip 
address "
-                                                       + 
socketChannel.socket().getLocalSocketAddress());
-                                       logger.logWarning("Old socket remote ip 
address "
-                                                       + 
socketChannel.socket().getRemoteSocketAddress());
-                                       logger.logWarning("New socket local ip 
address "
-                                                       + 
sock.socket().getLocalSocketAddress());
-                                       logger.logWarning("New socket remote ip 
address "
-                                                       + 
sock.socket().getRemoteSocketAddress());
-                               }
-                               close(false);
-                       }
-                       if (problem == null) {
-                               if (socketChannel != null) {
-                                       if 
(logger.isLoggingEnabled(LogWriter.TRACE_WARN)) {
-                                               logger
- .logWarning("There was no exception for the retry mechanism so creating a new thread based on the new socket for incoming "
-                                                                               
+ key);
-                                       }
-                               }
-                               socketChannel = sock;
-
-                       } else {
-                               if 
(logger.isLoggingEnabled(LogWriter.TRACE_WARN)) {
-                                       logger
- .logWarning("There was an exception for the retry mechanism so not creating a new thread based on the new socket for incoming "
-                                                                       + key);
-                               }
-                               socketChannel = sock;
-                       }
-               }
-
+               sendTCPMessage(msg, this.peerAddress, this.peerPort, isClient);
        }

-
        /**
         * Send a message to a specified address.
         *
@@ -338,6 +250,22 @@
         */
        public void sendMessage(byte message[], InetAddress receiverAddress,
                        int receiverPort, boolean retry) throws IOException {
+               sendTCPMessage(message, receiverAddress, receiverPort, retry);
+       }
+       /**
+        * Send a message to a specified address.
+        *
+        * @param message
+        *            Pre-formatted message to send.
+        * @param receiverAddress
+        *            Address to send it to.
+        * @param receiverPort
+        *            Receiver port.
+        * @throws IOException
+        *             If there is a problem connecting or sending.
+        */
+       public void sendTCPMessage(byte message[], InetAddress receiverAddress,
+                       int receiverPort, boolean retry) throws IOException {
                if (message == null || receiverAddress == null) {
                        logger.logError("receiverAddress = " + receiverAddress);
                        throw new IllegalArgumentException("Null argument");
@@ -361,48 +289,11 @@
                                                + this + " key " + key);
                        }
                }
-
-               SocketChannel sock = null;
-               IOException problem = null;
-               try {
- sock = ((NioTcpMessageProcessor) messageProcessor).nioHandler.sendBytes(this.messageProcessor + NIOHandler nioHandler = ((NioTcpMessageProcessor) messageProcessor).nioHandler;
+
+               SocketChannel sock = nioHandler.sendBytes(this.messageProcessor
                                        .getIpAddress(), receiverAddress, receiverPort, 
"TCP",
                                        message, retry, this);
-               } catch (IOException any) {
-                       problem = any;
-                       logger.logWarning("Failed to connect " + this.peerAddress + 
":"
-                                       + receiverPort + " but trying the advertised 
port="
-                                       + this.peerPortAdvertisedInHeaders
-                                       + " if it's different than the port we just 
failed on");
-                       logger.logError("Error is ", any);
-
-               }
-               if (sock == null) { // If we couldn't connect to the host, try 
the
-                                                       // advertised port as 
failsafe
-                       if (receiverPort != this.peerPortAdvertisedInHeaders
-                                       && peerPortAdvertisedInHeaders > 0) { 
// no point in trying
-                                                                               
                                        // same port
-                               logger.logWarning("Couldn't connect to 
receiverAddress = "
-                                               + receiverAddress + " receiverPort = 
" + receiverPort
-                                               + " key = " + key
-                                               + " retrying on 
peerPortAdvertisedInHeaders "
-                                               + peerPortAdvertisedInHeaders);
- sock = ((NioTcpMessageProcessor) messageProcessor).nioHandler.sendBytes(this.messageProcessor
-                                               .getIpAddress(), 
receiverAddress,
-                                               this.peerPortAdvertisedInHeaders, 
"TCP", message,
-                                               retry, this);
-                               this.peerPort = 
this.peerPortAdvertisedInHeaders;
-                               this.key = MessageChannel.getKey(peerAddress,
-                                               peerPortAdvertisedInHeaders, 
"TCP");
-
-                               logger.logWarning("retry suceeded to receiverAddress 
= "
-                                               + receiverAddress + " 
peerPortAdvertisedInHeaders = "
-                                               + peerPortAdvertisedInHeaders + " 
key = " + key);
-                       } else {
-                               throw problem; // throw the original excpetion 
we had from the
-                                                               // first attempt
-                       }
-               }

                if (sock != socketChannel && sock != null) {
                        if (socketChannel != null) {
@@ -420,29 +311,31 @@
                                        logger.logWarning("New socket remote ip 
address "
                                                        + 
sock.socket().getRemoteSocketAddress());
                                }
-                               close(false);
-                       }
-                       if (problem == null) {
-                               if (socketChannel != null) {
-                                       if 
(logger.isLoggingEnabled(LogWriter.TRACE_WARN)) {
-                                               logger
- .logWarning("There was no exception for the retry mechanism so we keep going "
-                                                                               
+ key);
-                                       }
-                               }
+ close(false); // we can call socketChannel.close() directly but we better use the inherited method
+
                                socketChannel = sock;
-                       } else {
+                               putMessageChannel(socketChannel, this);
+
+                               onNewSocket();
+                       }
+
+                       if (socketChannel != null) {
                                if 
(logger.isLoggingEnabled(LogWriter.TRACE_WARN)) {
                                        logger
- .logWarning("There was an exception for the retry mechanism so stop "
-                                                                       + key);
+ .logWarning("There was no exception for the retry mechanism so we keep going "
+                                                       + key);
                                }
-                               socketChannel = sock;
                        }
+                       socketChannel = sock;
                }

        }

+       public void onNewSocket() {
+
+       }
+
+
        /**
         * Exception processor for exceptions detected from the parser. (This is
         * invoked by the parser when an error is detected).
=======================================
--- /src/gov/nist/javax/sip/stack/NioTcpMessageProcessor.java Wed Apr 11 12:02:54 2012 +++ /src/gov/nist/javax/sip/stack/NioTcpMessageProcessor.java Thu Jul 19 14:20:11 2012
@@ -78,9 +78,10 @@
        return initiateConnection(address, timeout);
     }

-    public void send(SocketChannel socket, byte[] data) {
+    public void send(SocketChannel socket, byte[] data)  {
        if(logger.isLoggingEnabled(LogWriter.TRACE_DEBUG))
logger.logDebug("Sending data " + data.length + " bytes on socket " + socket);
+
        synchronized (this.changeRequests) {
this.changeRequests.add(new ChangeRequest(socket, ChangeRequest.CHANGEOPS, SelectionKey.OP_WRITE));

=======================================
--- /src/gov/nist/javax/sip/stack/NioTlsMessageChannel.java Wed Aug 1 03:00:34 2012 +++ /src/gov/nist/javax/sip/stack/NioTlsMessageChannel.java Thu Jul 19 14:20:11 2012
@@ -115,16 +115,25 @@
                appFrameBuffer.clear();
                return appFrameBuffer;
        }
+
+       public static class SSLReconnectedException extends IOException {
+               private static final long serialVersionUID = 1L;}

        @Override
- protected void sendMessage(byte[] msg, final boolean isClient) throws IOException { + protected void sendMessage(final byte[] msg, final boolean isClient) throws IOException {
+               lastMessage = new byte[msg.length];
+               for(int q=0;q<msg.length;q++) lastMessage[q] = msg[q];
+               String s = new String(lastMessage);
+               //logger.logError(">>>>>>>>>>>>>>FFF>>>>>" + s);
                ByteBuffer b = ByteBuffer.wrap(msg);
                try {
sslStateMachine.wrap(b, encryptedFrameBuffer, new MessageSendCallback() {

                                @Override
                                public void doSend(byte[] bytes) throws 
IOException {
-                                       
NioTlsMessageChannel.super.sendMessage(bytes, isClient);
+
+                                               
NioTlsMessageChannel.super.sendMessage(bytes, isClient);
+
                                }
                        });
                } catch (Exception e) {
@@ -134,12 +143,34 @@

        public void sendEncryptedData(byte[] msg) throws IOException {
                // bypass the encryption for already encrypted data or TLS 
metadata
-               super.sendMessage(msg, false);
+               if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
+ logger.logDebug("sendEncryptedData " + " this = " + this + " peerPort = " + peerPort + " addr = " + peerAddress);
+               }
+               lastActivityTimeStamp = System.currentTimeMillis();
+
+ NIOHandler nioHandler = ((NioTcpMessageProcessor) messageProcessor).nioHandler; + if(this.socketChannel != null && this.socketChannel.isConnected() && this.socketChannel.isOpen()) { + nioHandler.putSocket(NIOHandler.makeKey(this.peerAddress, this.peerPort), this.socketChannel);
+               }
+               super.sendMessage(msg, this.peerAddress, this.peerPort, true);
        }
-
+       private byte[] lastMessage = null;
        @Override
-       public void sendMessage(byte message[], final InetAddress 
receiverAddress,
+ public void sendMessage(final byte message[], final InetAddress receiverAddress,
                        final int receiverPort, final boolean retry) throws 
IOException {
+               lastMessage = new byte[message.length];
+               for(int q=0;q<message.length;q++) {
+
+                       lastMessage[q] = message[q];
+                       if(message[q]<0) {
+                               int r = 0 ;
+                               r++;r=r;
+                       }
+               }
+               String s = new String(lastMessage);
+
+               //logger.logError(">>>>>>>>>>>>>>FFF>>>>>" + s);
+
                ByteBuffer b = ByteBuffer.wrap(message);
                try {
sslStateMachine.wrap(b, encryptedFrameBuffer, new MessageSendCallback() {
@@ -148,6 +179,7 @@
                                public void doSend(byte[] bytes) throws 
IOException {
                                        
NioTlsMessageChannel.super.sendMessage(bytes,
                                                        receiverAddress, 
receiverPort, retry);
+
                                }
                        });
                } catch (IOException e) {
@@ -194,5 +226,24 @@
        public String getTransport() {
                return "TLS";
        }
+
+       @Override
+       public void onNewSocket() {
+               super.onNewSocket();
+               logger.logError("NEW SOCKET", new RuntimeException());
+               try {
+                       init(true);
+                       createBuffers();
+                       String s = new String(lastMessage, "UTF-8");
+                       sendMessage(lastMessage, false);
+               } catch (Exception e) {
+                       logger.logError("Cant reinit", e);
+               }
+       }
+
+       @Override
+       public boolean isSecure() {
+               return true;
+       }

 }

==============================================================================
Revision: fa54ad06c966
Author:   vralev <vralev@8e71dc83-d81e-6649-80f2-80b843a9b2be>
Date:     Wed Aug  8 12:20:08 2012
Log:      Update Issue 12

Backport to TelScale

JSIP-416
Add missing crpyto APIs, fix the outbound connect lock and cleanup.

git-svn-id: https://svn.java.net/svn/jsip~svn/branches/JAIN-SIP-NIO-year-2012@2140 8e71dc83-d81e-6649-80f2-80b843a9b2be
(cherry picked from commit 54aae50bdbd66bc3b05f44e39915dd25eb94246b)

http://code.google.com/p/jain-sip/source/detail?r=fa54ad06c966

Modified:
 /src/gov/nist/javax/sip/stack/NIOHandler.java
 /src/gov/nist/javax/sip/stack/NioTlsMessageChannel.java
 /src/gov/nist/javax/sip/stack/SIPTransaction.java

=======================================
--- /src/gov/nist/javax/sip/stack/NIOHandler.java       Thu Jul 19 14:20:11 2012
+++ /src/gov/nist/javax/sip/stack/NIOHandler.java       Wed Aug  8 12:20:08 2012
@@ -46,18 +46,13 @@
 import java.util.TimerTask;
 import java.util.concurrent.ConcurrentHashMap;

-/*
- * TLS support Added by Daniel J.Martinez Manzano <[email protected]>
- *
- */
-
 /**
* Low level Input output to a socket. Caches TCP connections and takes care of
  * re-connecting to the remote party if the other end drops the connection
  *
  * @version 1.2
  *
- * @author M. Ranganathan <br/>
+ * @author Vladimir Ralev <br/>
  *
  *
  */
@@ -69,11 +64,6 @@
     private SipStackImpl sipStack;

     private NioTcpMessageProcessor messageProcessor;
-
-    private static final String TCP = "tcp";
-
-    // Added by Daniel J. Martinez Manzano <[email protected]>
-    private static final String TLS = "tls";

     Timer timer = new Timer();

@@ -83,6 +73,7 @@


     KeyedSemaphore keyedSemaphore = new KeyedSemaphore();
+
     protected static String makeKey(InetAddress addr, int port) {
         return addr.getHostAddress() + ":" + port;

@@ -172,164 +163,157 @@

         }
         if (logger.isLoggingEnabled(LogLevels.TRACE_INFO)
-                && sipStack.isLogStackTraceOnMessageSend()) {
-            logger.logStackTrace(StackLogger.TRACE_INFO);
+                       && sipStack.isLogStackTraceOnMessageSend()) {
+               logger.logStackTrace(StackLogger.TRACE_INFO);
         }
- if (transport.compareToIgnoreCase(TCP) == 0 || transport.compareToIgnoreCase(TLS) == 0) {
-            String key = makeKey(receiverAddress, contactPort);
-            // This should be in a synchronized block ( reported by
-            // Jayashenkhar ( lucent ).
+
+        String key = makeKey(receiverAddress, contactPort);
+        // This should be in a synchronized block ( reported by
+        // Jayashenkhar ( lucent ).

-            SocketChannel clientSock = null;
-            keyedSemaphore.enterIOCriticalSection(key);
+        SocketChannel clientSock = null;
+        keyedSemaphore.enterIOCriticalSection(key);

-            boolean newSocket = false;
-            try {
-                clientSock = getSocket(key);
-                while (retry_count < max_retry) {
- if(clientSock != null && (!clientSock.isConnected() | | !clientSock.isOpen()) ) {
-                               removeSocket(key);
-                               clientSock = null;
-                               newSocket = true;
-                       }
-                    if (clientSock == null) {
- if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
-                            logger.logDebug(
-                                    "inaddr = " + receiverAddress);
-                            logger.logDebug(
-                                    "port = " + contactPort);
-                        }
-                        // note that the IP Address for stack may not be
-                        // assigned.
- // sender address is the address of the listening point. - // in version 1.1 all listening points have the same IP
-                        // address (i.e. that of the stack). In version 1.2
- // the IP address is on a per listening point basis.
-                        try {
- clientSock = messageProcessor.blockingConnect(new InetSocketAddress(receiverAddress, contactPort), 10000);
-                               newSocket = true;
-                               //sipStack.getNetworkLayer().createSocket(
- // receiverAddress, contactPort, senderAddress); TODO: sender address needed - } catch (SocketException e) { // We must catch the socket timeout exceptions here, any SocketException not just ConnectException
-                               logger.logError("Problem connecting " +
- receiverAddress + " " + contactPort + " " + senderAddress + " for message " + (messageChannel.isSecure()?"<<<ENCRYPTED MESSAGE>>>":new String(bytes, "UTF-8")));
-                               // new connection is bad.
- // remove from our table the socket and its semaphore
-                               removeSocket(key);
- throw new SocketException(e.getClass() + " " + e.getMessage() + " " + e.getCause() + " Problem connecting " + - receiverAddress + " " + contactPort + " " + senderAddress + " for message " + new String(bytes, "UTF-8"));
-                        }
-                        putSocket(key, clientSock);
-                        break;
-                    } else {
-                       break;
-                    }
-                }
-
-            } catch (IOException ex) {
-                if (logger.isLoggingEnabled(LogWriter.TRACE_ERROR)) {
-                    logger.logError(
-                            "Problem sending: sendBytes " + transport
-                                    + " inAddr "
-                                    + receiverAddress.getHostAddress()
-                                    + " port = " + contactPort +
- " remoteHost " + messageChannel.getPeerAddress() +
-                            " remotePort " + messageChannel.getPeerPort() +
-                            " peerPacketPort "
- + messageChannel.getPeerPacketSourcePort() + " isClient " + isClient);
-                }
+        boolean newSocket = false;
+        try {
+               clientSock = getSocket(key);
+               while (retry_count < max_retry) {
+ if(clientSock != null && (!clientSock.isConnected() | | !clientSock.isOpen()) ) {
+                               removeSocket(key);
+                               clientSock = null;
+                               newSocket = true;
+                       }
+                       if (clientSock == null) {
+                               if 
(logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
+                                       logger.logDebug(
+                                                       "inaddr = " + 
receiverAddress);
+                                       logger.logDebug(
+                                                       "port = " + 
contactPort);
+                               }
+                               // note that the IP Address for stack may not be
+                               // assigned.
+                               // sender address is the address of the 
listening point.
+                               // in version 1.1 all listening points have the 
same IP
+                               // address (i.e. that of the stack). In version 
1.2
+                               // the IP address is on a per listening point 
basis.
+                               try {
+ clientSock = messageProcessor.blockingConnect(new InetSocketAddress(receiverAddress, contactPort), 10000);
+                                       newSocket = true;
+                                       
//sipStack.getNetworkLayer().createSocket(
+ // receiverAddress, contactPort, senderAddress); TODO: sender address needed + } catch (SocketException e) { // We must catch the socket timeout exceptions here, any SocketException not just ConnectException
+                                       logger.logError("Problem connecting " +
+ receiverAddress + " " + contactPort + " " + senderAddress + " for message " + (messageChannel.isSecure()?"<<<ENCRYPTED MESSAGE>>>":new String(bytes, "UTF-8")));
+                                       // new connection is bad.
+                                       // remove from our table the socket and 
its semaphore
+                                       removeSocket(key);
+ throw new SocketException(e.getClass() + " " + e.getMessage() + " " + e.getCause() + " Problem connecting " + + receiverAddress + " " + contactPort + " " + senderAddress + " for message " + new String(bytes, "UTF-8"));
+                               }
+                               putSocket(key, clientSock);
+                               break;
+                       } else {
+                               break;
+                       }
+               }

-                removeSocket(key);
+        } catch (IOException ex) {
+               if (logger.isLoggingEnabled(LogWriter.TRACE_ERROR)) {
+                       logger.logError(
+                                       "Problem sending: sendBytes " + 
transport
+                                       + " inAddr "
+                                       + receiverAddress.getHostAddress()
+                                       + " port = " + contactPort +
+                                       " remoteHost " + 
messageChannel.getPeerAddress() +
+                                       " remotePort " + 
messageChannel.getPeerPort() +
+                                       " peerPacketPort "
+ + messageChannel.getPeerPacketSourcePort() + " isClient " + isClient);
+               }

-                /*
-                 * For TCP responses, the transmission of responses is
-                 * controlled by RFC 3261, section 18.2.2 :
-                 *
- * o If the "sent-protocol" is a reliable transport protocol - * such as TCP or SCTP, or TLS over those, the response MUST be
-                 * sent using the existing connection to the source of the
-                 * original request that created the transaction, if that
- * connection is still open. This requires the server transport - * to maintain an association between server transactions and - * transport connections. If that connection is no longer open, - * the server SHOULD open a connection to the IP address in the
-                 * "received" parameter, if present, using the port in the
- * "sent-by" value, or the default port for that transport, if - * no port is specified. If that connection attempt fails, the - * server SHOULD use the procedures in [4] for servers in order - * to determine the IP address and port to open the connection
-                 * and send the response to.
-                 */
-                if (!isClient) {
-                    receiverAddress = InetAddress.getByName(messageChannel
-                            .getViaHost());
- contactPort = messageChannel.peerPortAdvertisedInHeaders;
-                    if (contactPort <= 0)
-                        contactPort = 5060;
+               removeSocket(key);

-                    key = makeKey(receiverAddress, messageChannel
-                            .peerPortAdvertisedInHeaders);
-                    clientSock = this.getSocket(key);
-                    if (clientSock == null) {
- if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
-                            logger.logDebug(
-                                    "inaddr = " + receiverAddress +
-                                    " port = " + contactPort);
-                        }
- clientSock = messageProcessor.blockingConnect(new InetSocketAddress(receiverAddress, contactPort), 10000);
-                                               newSocket = true;
-                                               messageChannel.peerPort = 
contactPort;
-                        putSocket(key, clientSock);
-                    }
-
-                    if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
-                       logger.logDebug(
-                                       "sending to " + key );
-                    }
-
-
-                } else {
-                    logger.logError("IOException occured at " , ex);
-                    throw ex;
-                }
-
-                return clientSock;
-            } finally {
-               try {
-                       if(clientSock != null) {
- if(newSocket && messageChannel instanceof NioTlsMessageChannel) {
-                                       //messageChannel.onNewSocket();
-                               } else {
-                                       writeChunks(clientSock, bytes, length);
-                               }
-                       }
+               /*
+                * For TCP responses, the transmission of responses is
+                * controlled by RFC 3261, section 18.2.2 :
+                *
+                * o If the "sent-protocol" is a reliable transport protocol
+                * such as TCP or SCTP, or TLS over those, the response MUST be
+                * sent using the existing connection to the source of the
+                * original request that created the transaction, if that
+                * connection is still open. This requires the server transport
+                * to maintain an association between server transactions and
+                * transport connections. If that connection is no longer open,
+                * the server SHOULD open a connection to the IP address in the
+                * "received" parameter, if present, using the port in the
+                * "sent-by" value, or the default port for that transport, if
+                * no port is specified. If that connection attempt fails, the
+                * server SHOULD use the procedures in [4] for servers in order
+                * to determine the IP address and port to open the connection
+                * and send the response to.
+                */
+               if (!isClient) {
+                       receiverAddress = InetAddress.getByName(messageChannel
+                                       .peerAddressAdvertisedInHeaders);
+                       contactPort = 
messageChannel.peerPortAdvertisedInHeaders;
+                       if (contactPort <= 0)
+                               contactPort = 5060;

-               } finally {
-                       keyedSemaphore.leaveIOCriticalSection(key);
-               }
-            }
+                       key = makeKey(receiverAddress, contactPort);
+                       clientSock = this.getSocket(key);
+                       if (clientSock == null) {
+                               if 
(logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
+                                       logger.logDebug(
+                                                       "inaddr = " + 
receiverAddress +
+                                                       " port = " + 
contactPort);
+                               }
+ clientSock = messageProcessor.blockingConnect(new InetSocketAddress(receiverAddress, contactPort), 10000);
+                               newSocket = true;
+                               messageChannel.peerPort = contactPort;
+                               putSocket(key, clientSock);
+                       }

-            if (clientSock == null) {
+                       if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
+                               logger.logDebug(
+                                               "sending to " + key );
+                       }

-                if (logger.isLoggingEnabled(LogWriter.TRACE_ERROR)) {
-                    logger.logError(
-                            this.socketTable.toString());
-                    logger.logError(
-                            "Could not connect to " + receiverAddress + ":"
-                                    + contactPort);
-                }

- throw new IOException("Could not connect to " + receiverAddress
-                        + ":" + contactPort);
-            } else {
-                return clientSock;
-            }
+               } else {
+                       logger.logError("IOException occured at " , ex);
+                       throw ex;
+               }

-            // Added by Daniel J. Martinez Manzano <[email protected]>
-            // Copied and modified from the former section for TCP
+               return clientSock;
+        } finally {
+               try {
+                       if(clientSock != null) {
+ if(newSocket && messageChannel instanceof NioTlsMessageChannel) { + //We dont write data when using TLS, the new socket needs to handshake first
+                               } else {
+                                       writeChunks(clientSock, bytes, length);
+                               }
+                       }
+
+               } finally {
+                       keyedSemaphore.leaveIOCriticalSection(key);
+               }
         }
-        return null;

+        if (clientSock == null) {
+
+               if (logger.isLoggingEnabled(LogWriter.TRACE_ERROR)) {
+                       logger.logError(
+                                       this.socketTable.toString());
+                       logger.logError(
+                                       "Could not connect to " + receiverAddress + 
":"
+                                                       + contactPort);
+               }
+
+               throw new IOException("Could not connect to " + receiverAddress
+                               + ":" + contactPort);
+        } else {
+               return clientSock;
+        }
     }

     /**
@@ -387,31 +371,33 @@
         }
     }

-
- // TODO: FIXME: It is absolutely essential to have this method synchrnized based on the makeKey(addr, port), - // it is not needed to sync per class instance like it's done now, this is just temporary fix - // UAC case with rapid outbound socket creation might end up overwriting the assigned socket - public synchronized SocketChannel createOrReuseSocket(InetAddress inetAddress, int port) throws IOException { - SocketChannel channel = getSocket(NIOHandler.makeKey(inetAddress, port));
-       if(channel != null && !channel.isConnected()) {
-               if(logger.isLoggingEnabled(LogWriter.TRACE_DEBUG))
-                               logger.logDebug("Channel disconnected " + 
channel);
-               channel = null;
+ public SocketChannel createOrReuseSocket(InetAddress inetAddress, int port) throws IOException {
+       String key = NIOHandler.makeKey(inetAddress, port);
+       keyedSemaphore.enterIOCriticalSection(key);
+       try {
+               SocketChannel channel = getSocket(key);
+               if(channel != null && !channel.isConnected()) {
+                       if(logger.isLoggingEnabled(LogWriter.TRACE_DEBUG))
+                               logger.logDebug("Channel disconnected " + 
channel);
+                       channel = null;
+               }
+               if(channel == null) { // this is where the threads will race
+                       SocketAddress sockAddr = new 
InetSocketAddress(inetAddress, port);
+ channel = messageProcessor.blockingConnect((InetSocketAddress) sockAddr, 10000);
+                       if(logger.isLoggingEnabled(LogWriter.TRACE_DEBUG))
+ logger.logDebug("create channel = " + channel + " " + inetAddress + " " + port);
+                       if(channel != null && channel.isConnected()) {
+                               putSocket(NIOHandler.makeKey(inetAddress, 
port), channel);
+                               
if(logger.isLoggingEnabled(LogWriter.TRACE_DEBUG))
+                                       logger.logDebug("channel cached channel = 
" + channel);
+                       }
+               }
+               return channel;
+       } finally {
+               keyedSemaphore.leaveIOCriticalSection(key);
        }
-               if(channel == null) { // this is where the threads will race
-                       SocketAddress sockAddr = new 
InetSocketAddress(inetAddress, port);
- channel = messageProcessor.blockingConnect((InetSocketAddress) sockAddr, 10000);
-                       if(logger.isLoggingEnabled(LogWriter.TRACE_DEBUG))
- logger.logDebug("create channel = " + channel + " " + inetAddress + " " + port);
-                       if(channel != null && channel.isConnected()) {
-                               putSocket(NIOHandler.makeKey(inetAddress, 
port), channel);
-                               
if(logger.isLoggingEnabled(LogWriter.TRACE_DEBUG))
-                                                               
logger.logDebug("channel cached channel = " + channel);
-                       }
-               }
-               return channel;
     }
-
+
     private class SocketTimeoutAuditor extends TimerTask {
        public void run() {
                synchronized(socketTable) {
=======================================
--- /src/gov/nist/javax/sip/stack/NioTlsMessageChannel.java Thu Jul 19 14:20:11 2012 +++ /src/gov/nist/javax/sip/stack/NioTlsMessageChannel.java Wed Aug 8 12:20:08 2012
@@ -26,6 +26,7 @@
 package gov.nist.javax.sip.stack;

 import gov.nist.core.CommonLogger;
+import gov.nist.core.LogLevels;
 import gov.nist.core.LogWriter;
 import gov.nist.core.StackLogger;
 import gov.nist.javax.sip.SipStackImpl;
@@ -226,15 +227,20 @@
        public String getTransport() {
                return "TLS";
        }
-
+
        @Override
        public void onNewSocket() {
                super.onNewSocket();
-               logger.logError("NEW SOCKET", new RuntimeException());
                try {
+                       if(logger.isLoggingEnabled(LogLevels.TRACE_DEBUG)) {
+                               String last = null;
+                               if(lastMessage != null) {
+                                       last = new String(lastMessage, "UTF-8");
+                               }
+                               logger.logDebug("New socket for " + this + " last 
message = " + last);
+                       }
                        init(true);
                        createBuffers();
-                       String s = new String(lastMessage, "UTF-8");
                        sendMessage(lastMessage, false);
                } catch (Exception e) {
                        logger.logError("Cant reinit", e);
=======================================
--- /src/gov/nist/javax/sip/stack/SIPTransaction.java Wed Jul 18 07:59:33 2012 +++ /src/gov/nist/javax/sip/stack/SIPTransaction.java Wed Aug 8 12:20:08 2012
@@ -60,6 +60,8 @@
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;

+import javax.net.ssl.SSLEngine;
+import javax.net.ssl.SSLEngineResult.HandshakeStatus;
 import javax.net.ssl.SSLPeerUnverifiedException;
 import javax.sip.Dialog;
 import javax.sip.IOExceptionEvent;
@@ -1391,6 +1393,14 @@
else if ( ((TLSMessageChannel) this.getMessageChannel()).getHandshakeCompletedListener().getHandshakeCompletedEvent() == null)
                 return null;
else return ((TLSMessageChannel) this.getMessageChannel()).getHandshakeCompletedListener().getHandshakeCompletedEvent().getCipherSuite(); + } else if(this.getMessageChannel() instanceof NioTlsMessageChannel) { + SSLEngine sslEngine = ((NioTlsMessageChannel) this.getMessageChannel()).sslStateMachine.sslEngine; + if(sslEngine.getHandshakeStatus().equals(HandshakeStatus.FINISHED)) {
+                       String[] cs = sslEngine.getEnabledCipherSuites();
+                       return cs[0];
+               } else {
+                       return null;
+               }
} else throw new UnsupportedOperationException("Not a TLS channel");

     }
@@ -1403,6 +1413,13 @@
else if ( ((TLSMessageChannel) this.getMessageChannel()).getHandshakeCompletedListener().getHandshakeCompletedEvent() == null)
                 return null;
else return ((TLSMessageChannel) this.getMessageChannel()).getHandshakeCompletedListener().getHandshakeCompletedEvent().getLocalCertificates(); + } else if (this.getMessageChannel() instanceof NioTlsMessageChannel) { + SSLEngine sslEngine = ((NioTlsMessageChannel) this.getMessageChannel()).sslStateMachine.sslEngine; + if(sslEngine.getHandshakeStatus().equals(HandshakeStatus.FINISHED)) { + return ((NioTlsMessageChannel) this.getMessageChannel()).sslStateMachine.sslEngine.getSession().getLocalCertificates();
+               } else {
+                       return null;
+               }
} else throw new UnsupportedOperationException("Not a TLS channel");
     }

@@ -1415,7 +1432,12 @@
                 return null;
else return ((TLSMessageChannel) this.getMessageChannel()).getHandshakeCompletedListener().getHandshakeCompletedEvent().getPeerCertificates(); } else if(this.getMessageChannel() instanceof NioTlsMessageChannel) { - return ((NioTlsMessageChannel) this.getMessageChannel()).sslStateMachine.sslEngine.getSession().getPeerCertificates(); + SSLEngine sslEngine = ((NioTlsMessageChannel) this.getMessageChannel()).sslStateMachine.sslEngine; + if(sslEngine.getHandshakeStatus().equals(HandshakeStatus.FINISHED)) { + return ((NioTlsMessageChannel) this.getMessageChannel()).sslStateMachine.sslEngine.getSession().getPeerCertificates();
+               } else {
+                       return null;
+               }
         }
         else
                throw new UnsupportedOperationException("Not a TLS channel");

Reply via email to