replace : iotivity -> iotivity-sec
[platform/upstream/iotivity.git] / resource / csdk / connectivity / src / tcp_adapter / catcpadapter.c
old mode 100755 (executable)
new mode 100644 (file)
index b08d3c0..67905f6
@@ -34,7 +34,7 @@
 #include "catcpinterface.h"
 #include "caqueueingthread.h"
 #include "caadapterutils.h"
-#include "camutex.h"
+#include "octhread.h"
 #include "uarraylist.h"
 #include "caremotehandler.h"
 #include "logger.h"
@@ -88,17 +88,17 @@ static CAConnectionChangeCallback g_connectionChangeCallback = NULL;
  */
 static CAErrorHandleCallback g_errorCallback = NULL;
 
-static void CATCPPacketReceivedCB(const CASecureEndpoint_t *sep,
-                                  const void *data, uint32_t dataLength);
-
-static void CATCPErrorHandler(const CAEndpoint_t *endpoint, const void *data,
-                              size_t dataLength, CAResult_t result);
-
 /**
  * KeepAlive Connected or Disconnected Callback to CA adapter.
  */
 static CAKeepAliveConnectionCallback g_connKeepAliveCallback = NULL;
 
+static CAResult_t CATCPPacketReceivedCB(const CASecureEndpoint_t *sep,
+                                        const void *data, uint32_t dataLength);
+
+static void CATCPErrorHandler(const CAEndpoint_t *endpoint, const void *data,
+                              size_t dataLength, CAResult_t result);
+
 static CAResult_t CATCPInitializeQueueHandles();
 
 static void CATCPDeinitializeQueueHandles();
@@ -155,18 +155,23 @@ void CATCPConnectionStateCB(const char *ipAddress, CANetworkStatus_t status)
     (void)status;
 }
 
-void CATCPPacketReceivedCB(const CASecureEndpoint_t *sep, const void *data,
-                           uint32_t dataLength)
+CAResult_t CATCPPacketReceivedCB(const CASecureEndpoint_t *sep, const void *data,
+                                 uint32_t dataLength)
 {
-    VERIFY_NON_NULL_VOID(sep, TAG, "sep is NULL");
-    VERIFY_NON_NULL_VOID(data, TAG, "data is NULL");
+    VERIFY_NON_NULL(sep, TAG, "sep is NULL");
+    VERIFY_NON_NULL(data, TAG, "data is NULL");
 
     OIC_LOG_V(DEBUG, TAG, "Address: %s, port:%d", sep->endpoint.addr, sep->endpoint.port);
 
+    CAResult_t res = CA_STATUS_OK;
 #ifdef SINGLE_THREAD
     if (g_networkPacketCallback)
     {
-        g_networkPacketCallback(sep, data, dataLength);
+        res = g_networkPacketCallback(sep, data, dataLength);
+        if (CA_STATUS_OK != res)
+        {
+            OIC_LOG(ERROR, TAG, "Error parsing CoAP data");
+        }
     }
 #else
     unsigned char *buffer = (unsigned char*)data;
@@ -178,22 +183,22 @@ void CATCPPacketReceivedCB(const CASecureEndpoint_t *sep, const void *data,
     if (!svritem)
     {
         OIC_LOG(ERROR, TAG, "there is no connection information in list");
-        return;
+        return CA_STATUS_INVALID_PARAM;
     }
     if (UNKNOWN == svritem->protocol)
     {
         OIC_LOG(ERROR, TAG, "invalid protocol type");
-        return;
+        return CA_STATUS_INVALID_PARAM;
     }
 
     //totalLen filled only when header fully read and parsed
     while (0 != bufferLen)
     {
-        CAResult_t res = CAConstructCoAP(svritem, &buffer, &bufferLen);
+        res = CAConstructCoAP(svritem, &buffer, &bufferLen);
         if (CA_STATUS_OK != res)
         {
             OIC_LOG_V(ERROR, TAG, "CAConstructCoAP return error : %d", res);
-            return;
+            return res;
         }
 
         //when successfully read all required data - pass them to upper layer.
@@ -201,7 +206,12 @@ void CATCPPacketReceivedCB(const CASecureEndpoint_t *sep, const void *data,
         {
             if (g_networkPacketCallback)
             {
-                g_networkPacketCallback(sep, svritem->data, svritem->totalLen);
+                res = g_networkPacketCallback(sep, svritem->data, svritem->totalLen);
+                if (CA_STATUS_OK != res)
+                {
+                    OIC_LOG(ERROR, TAG, "Error parsing CoAP data");
+                    return res;
+                }
             }
             CACleanData(svritem);
         }
@@ -212,6 +222,7 @@ void CATCPPacketReceivedCB(const CASecureEndpoint_t *sep, const void *data,
         }
     }
 #endif
+    return res;
 }
 
 #ifdef __WITH_TLS__
@@ -242,12 +253,12 @@ static void CATCPErrorHandler(const CAEndpoint_t *endpoint, const void *data,
     }
 }
 
-static void CATCPConnectionHandler(const CAEndpoint_t *endpoint, bool isConnected)
+static void CATCPConnectionHandler(const CAEndpoint_t *endpoint, bool isConnected, bool isClient)
 {
     // Pass the changed connection status to RI Layer for keepalive.
     if (g_connKeepAliveCallback)
     {
-        g_connKeepAliveCallback(endpoint, isConnected);
+        g_connKeepAliveCallback(endpoint, isConnected, isClient);
     }
 
     // Pass the changed connection status to CAUtil.
@@ -271,12 +282,19 @@ void CATCPAdapterHandler(CATransportAdapter_t adapter, CANetworkStatus_t status)
 
     if (CA_INTERFACE_DOWN == status)
     {
-        OIC_LOG(DEBUG, TAG, "Network status is down, close all session");
+        OIC_LOG(INFO, TAG, "Network status is down, close all session");
+
+        CAResult_t res = CAQueueingThreadClearData(g_sendQueueHandle);
+        if (res != CA_STATUS_OK)
+        {
+            OIC_LOG_V(ERROR, TAG, "CAQueueingThreadClearData failed[%d]", res);
+        }
+
         CATCPStopServer();
     }
     else if (CA_INTERFACE_UP == status)
     {
-        OIC_LOG(DEBUG, TAG, "Network status is up, create new socket for listening");
+        OIC_LOG(INFO, TAG, "Network status is up, create new socket for listening");
 
         CAResult_t ret = CA_STATUS_FAILED;
 #ifndef SINGLE_THREAD
@@ -286,7 +304,7 @@ void CATCPAdapterHandler(CATransportAdapter_t adapter, CANetworkStatus_t status)
 #endif
         if (CA_STATUS_OK != ret)
         {
-            OIC_LOG_V(DEBUG, TAG, "CATCPStartServer failed[%d]", ret);
+            OIC_LOG_V(ERROR, TAG, "CATCPStartServer failed[%d]", ret);
         }
     }
 }
@@ -342,6 +360,20 @@ CAResult_t CAInitializeTCP(CARegisterConnectivityCallback registerCallback,
     g_errorCallback = errorCallback;
 
     CAInitializeTCPGlobals();
+
+    CAResult_t res = CATCPCreateMutex();
+    if (CA_STATUS_OK == res)
+    {
+        res = CATCPCreateCond();
+    }
+    if (CA_STATUS_OK != res)
+    {
+        OIC_LOG(ERROR, TAG, "failed to create mutex/cond");
+        CATCPDestroyMutex();
+        CATCPDestroyCond();
+        return res;
+    }
+
 #ifndef SINGLE_THREAD
     caglobals.tcp.threadpool = handle;
 #endif
@@ -351,14 +383,7 @@ CAResult_t CAInitializeTCP(CARegisterConnectivityCallback registerCallback,
     CATCPSetErrorHandler(CATCPErrorHandler);
 
 #ifdef __WITH_TLS__
-    if (CA_STATUS_OK != CAinitSslAdapter())
-    {
-        OIC_LOG(ERROR, TAG, "Failed to init SSL adapter");
-    }
-    else
-    {
-        CAsetSslAdapterCallbacks(CATCPPacketReceivedCB, CATCPPacketSendCB, CA_ADAPTER_TCP);
-    }
+    CAsetSslAdapterCallbacks(CATCPPacketReceivedCB, CATCPPacketSendCB, CA_ADAPTER_TCP);
 #endif
 
     CAConnectivityHandler_t tcpHandler = {
@@ -384,9 +409,6 @@ CAResult_t CAStartTCP()
 {
     OIC_LOG(DEBUG, TAG, "IN");
 
-    // Start network monitoring to receive adapter status changes.
-    CAIPStartNetworkMonitor(CATCPAdapterHandler, CA_ADAPTER_TCP);
-
 #ifndef SINGLE_THREAD
     if (CA_STATUS_OK != CATCPInitializeQueueHandles())
     {
@@ -396,7 +418,11 @@ CAResult_t CAStartTCP()
     }
 
     // Start send queue thread
+#ifndef __TIZENRT__
     if (CA_STATUS_OK != CAQueueingThreadStart(g_sendQueueHandle))
+#else
+    if (CA_STATUS_OK != CAQueueingThreadStart(g_sendQueueHandle, "IoT_TCPSendQueue"))
+#endif
     {
         OIC_LOG(ERROR, TAG, "Failed to Start Send Data Thread");
         return CA_STATUS_FAILED;
@@ -410,9 +436,55 @@ CAResult_t CAStartTCP()
     }
 #endif
 
+    // Start network monitoring to receive adapter status changes.
+    CAIPStartNetworkMonitor(CATCPAdapterHandler, CA_ADAPTER_TCP);
+
     return CA_STATUS_OK;
 }
 
+static bool CAClearQueueEndpointDataContext(void *data, uint32_t size, void *ctx)
+{
+    if (NULL == data || NULL == ctx)
+    {
+        return false;
+    }
+
+    CATCPData *tcpData = (CATCPData *)data;
+    CAEndpoint_t *endpoint = (CAEndpoint_t *)ctx;
+
+    if (NULL != tcpData && NULL != tcpData->remoteEndpoint)
+    {
+        if (strcmp(tcpData->remoteEndpoint->addr, endpoint->addr) == 0
+            && tcpData->remoteEndpoint->port == endpoint->port)
+        {
+            return true;
+        }
+    }
+    return false;
+}
+
+CAResult_t CATCPDisconnectSession(const CAEndpoint_t *endpoint)
+{
+    CAResult_t res = CA_STATUS_OK;
+#ifdef __WITH_TLS__
+    res = CAcloseSslConnection(endpoint);
+    if (CA_STATUS_OK != res)
+    {
+        OIC_LOG(ERROR, TAG, "failed to close TLS session");
+        return res;
+    }
+#endif
+    res = CASearchAndDeleteTCPSession(endpoint);
+    if (CA_STATUS_OK != res)
+    {
+        OIC_LOG(ERROR, TAG, "failed to close TCP session");
+    }
+    res = CAQueueingThreadClearContextData(g_sendQueueHandle,
+                                           CAClearQueueEndpointDataContext,
+                                           endpoint);
+    return res;
+}
+
 CAResult_t CAStartTCPListeningServer()
 {
 #ifndef SINGLE_THREAD
@@ -528,17 +600,15 @@ CAResult_t CAStopTCP()
     //Re-initializing the Globals to start them again
     CAInitializeTCPGlobals();
 
-#ifdef __WITH_TLS__
-    CAdeinitSslAdapter();
-#endif
-
     return CA_STATUS_OK;
 }
 
 void CATerminateTCP()
 {
-    CAStopTCP();
     CATCPSetPacketReceiveCallback(NULL);
+
+    CATCPDestroyMutex();
+    CATCPDestroyCond();
 }
 
 void CATCPSendDataThread(void *threadData)
@@ -566,40 +636,24 @@ void CATCPSendDataThread(void *threadData)
     }
     else
     {
-        // Check payload length from CoAP over TCP format header.
-        CAResult_t result = CA_STATUS_OK;
-        size_t payloadLen = CACheckPayloadLengthFromHeader(tcpData->data, tcpData->dataLen);
-        if (!payloadLen)
-        {
-            // if payload length is zero, disconnect from remote device.
-            OIC_LOG(DEBUG, TAG, "payload length is zero, disconnect from remote device");
 #ifdef __WITH_TLS__
-            if (CA_STATUS_OK != CAcloseSslConnection(tcpData->remoteEndpoint))
+        if (tcpData->remoteEndpoint && tcpData->remoteEndpoint->flags & CA_SECURE)
+        {
+            CAResult_t result = CA_STATUS_OK;
+            OIC_LOG(DEBUG, TAG, "CAencryptSsl called!");
+            result = CAencryptSsl(tcpData->remoteEndpoint, tcpData->data, tcpData->dataLen);
+
+            if (CA_STATUS_OK != result)
             {
-                OIC_LOG(ERROR, TAG, "Failed to close TLS session");
+                OIC_LOG(ERROR, TAG, "CAAdapterNetDtlsEncrypt failed!");
+                CASearchAndDeleteTCPSession(tcpData->remoteEndpoint);
+                CATCPErrorHandler(tcpData->remoteEndpoint, tcpData->data, tcpData->dataLen,
+                                  CA_SEND_FAILED);
             }
-#endif
-            CASearchAndDeleteTCPSession(tcpData->remoteEndpoint);
+            OIC_LOG_V(DEBUG, TAG,
+                      "CAAdapterNetDtlsEncrypt returned with result[%d]", result);
             return;
         }
-
-#ifdef __WITH_TLS__
-         if (tcpData->remoteEndpoint && tcpData->remoteEndpoint->flags & CA_SECURE)
-         {
-             OIC_LOG(DEBUG, TAG, "CAencryptSsl called!");
-             result = CAencryptSsl(tcpData->remoteEndpoint, tcpData->data, tcpData->dataLen);
-
-             if (CA_STATUS_OK != result)
-             {
-                 OIC_LOG(ERROR, TAG, "CAAdapterNetDtlsEncrypt failed!");
-                 CASearchAndDeleteTCPSession(tcpData->remoteEndpoint);
-                 CATCPErrorHandler(tcpData->remoteEndpoint, tcpData->data, tcpData->dataLen,
-                                   CA_SEND_FAILED);
-             }
-             OIC_LOG_V(DEBUG, TAG,
-                       "CAAdapterNetDtlsEncrypt returned with result[%d]", result);
-            return;
-         }
 #endif
         //Processing for sending unicast
          ssize_t dlen = CATCPSendData(tcpData->remoteEndpoint, tcpData->data, tcpData->dataLen);
@@ -656,7 +710,9 @@ void CADataDestroyer(void *data, uint32_t size)
 {
     if (size < sizeof(CATCPData))
     {
+#ifndef __TIZENRT__
         OIC_LOG_V(ERROR, TAG, "Destroy data too small %p %" PRIu32, data, size);
+#endif
     }
     CATCPData *TCPData = (CATCPData *) data;