Replace/examine usages of mem* and strcat/strcpy
authorErich Keane <erich.keane@intel.com>
Thu, 4 Jun 2015 23:33:04 +0000 (16:33 -0700)
committerErich Keane <erich.keane@intel.com>
Tue, 16 Jun 2015 16:18:57 +0000 (16:18 +0000)
The codebase has a large number of mis-uses of memset, memcpy,
strcat, and strcpy.  This patch replaces them with OICStrdup,
OICStrcpy, and OICStrcat where possible, and fixes a number of
issues with memcpy/memset usages throughout the code.

Change-Id: Ifa03ed611778488c28f261266eb9a8821fa4db5c
Signed-off-by: Erich Keane <erich.keane@intel.com>
Reviewed-on: https://gerrit.iotivity.org/gerrit/1208
Tested-by: jenkins-iotivity <jenkins-iotivity@opendaylight.org>
Reviewed-by: Doug Hudson <douglas.hudson@intel.com>
39 files changed:
resource/csdk/connectivity/common/src/logger.c
resource/csdk/connectivity/common/src/oic_logger.c
resource/csdk/connectivity/src/adapter_util/caadapternetdtls.c
resource/csdk/connectivity/src/adapter_util/caadapterutils.c
resource/csdk/connectivity/src/bt_edr_adapter/android/caedrclient.c
resource/csdk/connectivity/src/bt_edr_adapter/android/caedrserver.c
resource/csdk/connectivity/src/bt_edr_adapter/android/caedrutils.c
resource/csdk/connectivity/src/bt_edr_adapter/linux/caedradapter.c
resource/csdk/connectivity/src/bt_le_adapter/android/caleclient.c
resource/csdk/connectivity/src/bt_le_adapter/caleadapter.c
resource/csdk/connectivity/src/bt_le_adapter/linux/caleadapter.c
resource/csdk/connectivity/src/bt_le_adapter/tizen/cableclient.c
resource/csdk/connectivity/src/bt_le_adapter/tizen/cableserver.c
resource/csdk/connectivity/src/bt_le_adapter/tizen/cableutil.c
resource/csdk/connectivity/src/cainterfacecontroller.c
resource/csdk/connectivity/src/cainterfacecontroller_singlethread.c
resource/csdk/connectivity/src/camessagehandler.c
resource/csdk/connectivity/src/camessagehandler_singlethread.c
resource/csdk/connectivity/src/caprotocolmessage.c
resource/csdk/connectivity/src/caremotehandler.c
resource/csdk/connectivity/src/caretransmission_singlethread.c
resource/csdk/connectivity/src/ip_adapter/android/caipnwmonitor.c
resource/csdk/connectivity/src/ip_adapter/caipadapter.c
resource/csdk/connectivity/src/ip_adapter/caipserver.c
resource/csdk/connectivity/src/ip_adapter/linux/caipnwmonitor.c
resource/csdk/connectivity/src/ip_adapter/tizen/caipnwmonitor.c
resource/csdk/logger/src/logger.c
resource/csdk/ocrandom/test/android/randomtest.cpp
resource/csdk/ocrandom/test/arduino/randomtest.cpp
resource/csdk/ocrandom/test/linux/randomtest.cpp
resource/csdk/stack/include/internal/ocstackinternal.h
resource/csdk/stack/src/occollection.c
resource/csdk/stack/src/ocobserve.c
resource/csdk/stack/src/ocresource.c
resource/csdk/stack/src/ocserverrequest.c
resource/csdk/stack/src/ocstack.c
resource/oc_logger/c/oc_logger.c
resource/src/InProcClientWrapper.cpp
resource/src/InProcServerWrapper.cpp

index 9772f99..a5d48d9 100644 (file)
@@ -196,8 +196,7 @@ void OICLogv(LogLevel level, const char *tag, const char *format, ...)
     {
         return;
     }
-    char buffer[MAX_LOG_V_BUFFER_SIZE];
-    memset(buffer, 0, sizeof buffer);
+    char buffer[MAX_LOG_V_BUFFER_SIZE] = {};
     va_list args;
     va_start(args, format);
     vsnprintf(buffer, sizeof buffer - 1, format, args);
@@ -220,6 +219,8 @@ void OICLogBuffer(LogLevel level, const char *tag, const uint8_t *buffer, uint16
         return;
     }
 
+    // I've got no idea why static initialization doesn't work here.  It seems that the compiler
+    // seems to think that this is a variable-sized object
     char lineBuffer[LINE_BUFFER_SIZE];
     memset(lineBuffer, 0, sizeof lineBuffer);
     int lineIndex = 0;
@@ -272,7 +273,7 @@ void OICLogInit()
          return;
      }
 
-     char buffer[LINE_BUFFER_SIZE] = {0};
+     char buffer[LINE_BUFFER_SIZE] = {};
      strcpy_P(buffer, (char*)pgm_read_word(&(LEVEL[level])));
      Serial.print(buffer);
 
index 46106c6..9347c27 100644 (file)
@@ -19,6 +19,7 @@
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
 #include "oic_logger.h"
+#include "oic_string.h"
 
 #include <string.h>
 #include <stdlib.h>
@@ -123,16 +124,12 @@ size_t oic_log_write_level(oic_log_ctx_t *ctx, const oic_log_level ll, const cha
 int oic_log_set_module(oic_log_ctx_t *ctx, const char *module_name)
 {
     char *mn;
-    size_t l;
 
     if (0 == ctx)
         return 0;
 
     /* Swap pointers so that module data's not erased in the event of failure: */
-    l = strlen(module_name);
-
-    mn = (char *) malloc(1 + l);
-
+    mn = OICStrdup(module_name);
     if (0 == mn)
     {
         if (0 != ctx->module_name)
@@ -140,8 +137,6 @@ int oic_log_set_module(oic_log_ctx_t *ctx, const char *module_name)
         return 0;
     }
 
-    memcpy(mn, module_name, 1 + l);
-
     if (0 != ctx->module_name)
         free(ctx->module_name);
 
index 8f01c06..59919ef 100644 (file)
@@ -22,6 +22,7 @@
 #include "caipinterface.h"
 #include "dtls.h"
 #include "oic_malloc.h"
+#include "oic_string.h"
 #include "global.h"
 
 /**
@@ -102,9 +103,10 @@ static CAResult_t CAAddIdToPeerInfoList(const char *peerAddr, uint32_t port,
         return CA_MEMORY_ALLOC_FAILED;
     }
 
-    strncpy(peerInfo->address.IP.ipAddress, peerAddr, CA_IPADDR_SIZE);
+    OICStrcpy(peerInfo->address.IP.ipAddress, sizeof(peerInfo->address.IP.ipAddress),
+            peerAddr);
     peerInfo->address.IP.port = port;
-    memcpy(peerInfo->identity.id, id, id_length);
+    OICStrcpyPartial(peerInfo->identity.id, sizeof(peerInfo->identity.id), id, id_length);
     peerInfo->identity.id_length = id_length;
 
     CAResult_t result = u_arraylist_add(g_caDtlsContext->peerInfoList, (void *)peerInfo);
index 8479c55..3209d8b 100644 (file)
 
 #include <string.h>
 #include <ctype.h>
+#include "oic_string.h"
+#include "oic_malloc.h"
 
 #ifdef __ANDROID__
 #include <jni.h>
 #endif
 
-#include "oic_malloc.h"
-#include "oic_string.h"
-
 #define CA_ADAPTER_UTILS_TAG "CA_ADAPTER_UTILS"
 
 #ifdef __ANDROID__
@@ -75,18 +74,18 @@ CALocalConnectivity_t *CAAdapterCreateLocalEndpoint(CATransportType_t type, cons
     {
         if (CA_EDR == type)
         {
-            strncpy(info->addressInfo.BT.btMacAddress, address, CA_MACADDR_SIZE - 1);
-            info->addressInfo.BT.btMacAddress[CA_MACADDR_SIZE - 1] = '\0';
+            OICStrcpy(info->addressInfo.BT.btMacAddress, sizeof(info->addressInfo.BT.btMacAddress),
+                    address);
         }
         else if (CA_LE == type)
         {
-            strncpy(info->addressInfo.LE.leMacAddress, address, CA_MACADDR_SIZE - 1);
-            info->addressInfo.LE.leMacAddress[CA_MACADDR_SIZE - 1] = '\0';
+            OICStrcpy(info->addressInfo.LE.leMacAddress, sizeof(info->addressInfo.LE.leMacAddress),
+                    address);
         }
         else if (CA_IPV4 == type)
         {
-            strncpy(info->addressInfo.IP.ipAddress, address, CA_IPADDR_SIZE - 1);
-            info->addressInfo.IP.ipAddress[CA_IPADDR_SIZE - 1] = '\0';
+            OICStrcpy(info->addressInfo.IP.ipAddress, sizeof(info->addressInfo.IP.ipAddress),
+                    address);
         }
         else if (CA_IPV6 == type)
         {
@@ -120,23 +119,20 @@ CALocalConnectivity_t *CAAdapterCopyLocalEndpoint(const CALocalConnectivity_t *c
     info->type = connectivity->type;
     if (CA_EDR == info->type && strlen(connectivity->addressInfo.BT.btMacAddress))
     {
-        strncpy(info->addressInfo.BT.btMacAddress, connectivity->addressInfo.BT.btMacAddress,
-                CA_MACADDR_SIZE - 1);
-        info->addressInfo.BT.btMacAddress[CA_MACADDR_SIZE - 1] = '\0';
+        OICStrcpy(info->addressInfo.BT.btMacAddress, sizeof(info->addressInfo.BT.btMacAddress),
+                connectivity->addressInfo.BT.btMacAddress);
     }
     else if (CA_LE == info->type && strlen(connectivity->addressInfo.LE.leMacAddress))
     {
-        strncpy(info->addressInfo.LE.leMacAddress, connectivity->addressInfo.LE.leMacAddress,
-                CA_MACADDR_SIZE - 1);
-        info->addressInfo.LE.leMacAddress[CA_MACADDR_SIZE - 1] = '\0';
+        OICStrcpy(info->addressInfo.LE.leMacAddress, sizeof(info->addressInfo.LE.leMacAddress),
+            connectivity->addressInfo.LE.leMacAddress);
     }
     else if ((CA_IPV4 == info->type)
 
             && strlen(connectivity->addressInfo.IP.ipAddress))
     {
-        strncpy(info->addressInfo.IP.ipAddress, connectivity->addressInfo.IP.ipAddress,
-                CA_IPADDR_SIZE - 1);
-        info->addressInfo.IP.ipAddress[CA_IPADDR_SIZE - 1] = '\0';
+        OICStrcpy(info->addressInfo.IP.ipAddress, sizeof(info->addressInfo.IP.ipAddress),
+                connectivity->addressInfo.IP.ipAddress);
         info->addressInfo.IP.port = connectivity->addressInfo.IP.port;
     }
     else if (CA_IPV6 == info->type)
@@ -177,18 +173,18 @@ CARemoteEndpoint_t *CAAdapterCreateRemoteEndpoint(CATransportType_t type, const
     {
         if (CA_EDR == type)
         {
-            strncpy(info->addressInfo.BT.btMacAddress, address, CA_MACADDR_SIZE - 1);
-            info->addressInfo.BT.btMacAddress[CA_MACADDR_SIZE - 1] = '\0';
+            OICStrcpy(info->addressInfo.BT.btMacAddress, sizeof(info->addressInfo.BT.btMacAddress),
+                    address);
         }
         else if (CA_LE == type)
         {
-            strncpy(info->addressInfo.LE.leMacAddress, address, CA_MACADDR_SIZE - 1);
-            info->addressInfo.LE.leMacAddress[CA_MACADDR_SIZE - 1] = '\0';
+            OICStrcpy(info->addressInfo.LE.leMacAddress, sizeof(info->addressInfo.LE.leMacAddress),
+                    address);
         }
         else if (CA_IPV4 == type)
         {
-            strncpy(info->addressInfo.IP.ipAddress, address, CA_IPADDR_SIZE - 1);
-            info->addressInfo.IP.ipAddress[CA_IPADDR_SIZE - 1] = '\0';
+            OICStrcpy(info->addressInfo.IP.ipAddress, sizeof(info->addressInfo.IP.ipAddress),
+                    address);
         }
         else if (CA_IPV6 == type)
         {
@@ -227,23 +223,20 @@ CARemoteEndpoint_t *CAAdapterCopyRemoteEndpoint(const CARemoteEndpoint_t *remote
     info->transportType = remoteEndpoint->transportType;
     if (CA_EDR == info->transportType && ('\0' != remoteEndpoint->addressInfo.BT.btMacAddress[0]))
     {
-        strncpy(info->addressInfo.BT.btMacAddress, remoteEndpoint->addressInfo.BT.btMacAddress,
-                CA_MACADDR_SIZE - 1);
-        info->addressInfo.BT.btMacAddress[CA_MACADDR_SIZE - 1] = '\0';
+        OICStrcpy(info->addressInfo.BT.btMacAddress, sizeof(info->addressInfo.BT.btMacAddress),
+                remoteEndpoint->addressInfo.BT.btMacAddress);
     }
     else if (CA_LE == info->transportType
              && ('\0' != remoteEndpoint->addressInfo.LE.leMacAddress[0]))
     {
-        strncpy(info->addressInfo.LE.leMacAddress, remoteEndpoint->addressInfo.LE.leMacAddress,
-                CA_MACADDR_SIZE - 1);
-        info->addressInfo.LE.leMacAddress[CA_MACADDR_SIZE - 1] = '\0';
+        OICStrcpy(info->addressInfo.LE.leMacAddress, sizeof(info->addressInfo.LE.leMacAddress),
+                remoteEndpoint->addressInfo.LE.leMacAddress);
     }
     else if ((CA_IPV4 == info->transportType)
             && ('\0' != remoteEndpoint->addressInfo.IP.ipAddress[0]))
     {
-        strncpy(info->addressInfo.IP.ipAddress, remoteEndpoint->addressInfo.IP.ipAddress,
-                CA_IPADDR_SIZE - 1);
-        info->addressInfo.IP.ipAddress[CA_IPADDR_SIZE - 1] = '\0';
+        OICStrcpy(info->addressInfo.IP.ipAddress, sizeof(info->addressInfo.IP.ipAddress),
+                remoteEndpoint->addressInfo.IP.ipAddress);
         info->addressInfo.IP.port = remoteEndpoint->addressInfo.IP.port;
     }
     else if (CA_IPV6 == info->transportType)
index d0f9d99..4536343 100644 (file)
@@ -27,6 +27,7 @@
 #include "caedrclient.h"
 #include "logger.h"
 #include "oic_malloc.h"
+#include "oic_string.h"
 #include "cathreadpool.h" /* for thread pool */
 #include "camutex.h"
 #include "uarraylist.h"
@@ -575,7 +576,7 @@ void CAEDRGetLocalAddress(char **address)
     if (jni_address)
     {
         const char* localAddress = (*env)->GetStringUTFChars(env, jni_address, NULL);
-        *address = (char*) OICMalloc(strlen(localAddress) + 1);
+        *address = OICStrdup(localAddress);
         if (*address == NULL)
         {
             if (isAttached)
@@ -584,7 +585,7 @@ void CAEDRGetLocalAddress(char **address)
             }
             return;
         }
-        memcpy(*address, localAddress, strlen(localAddress));
+
         (*env)->ReleaseStringUTFChars(env, jni_address, localAddress);
     }
 
index 3aa2487..d5533ea 100644 (file)
@@ -33,6 +33,7 @@
 #include "uarraylist.h"
 #include "caadapterutils.h"
 #include "org_iotivity_ca_CaEdrInterface.h"
+#include "oic_string.h"
 
 //#define DEBUG_MODE
 #define TAG PCF("CA_EDR_SERVER")
@@ -822,7 +823,7 @@ CAResult_t CAEDRNativeReadData(JNIEnv *env, uint32_t id, CAAdapterServerType_t t
         OIC_LOG_V(DEBUG, TAG, "[EDR][Native] btReadData: read %s, %d", buf, length);
 
         char responseData[MAX_PDU_BUFFER] = { 0 };
-        memcpy(responseData, (const char*) buf, length);
+        OICStrcpy(responseData, sizeof(responseData), buf, length);
 
         switch (type)
         {
index 5044c58..7c8d870 100644 (file)
@@ -24,6 +24,7 @@
 #include "caedrutils.h"
 #include "logger.h"
 #include "oic_malloc.h"
+#include "oic_string.h"
 #include "cathreadpool.h"
 #include "uarraylist.h"
 
@@ -335,7 +336,7 @@ void CAEDRUpdateDeviceState(CAConnectedState_t state, const char *address)
         OIC_LOG(ERROR, TAG, "[EDR][Native] newstate is null");
         return;
     }
-    strcpy(newstate->address, address);
+    OICStrcpy(newstate->address, sizeof(newstate->address), address);
     newstate->state = state;
 
     CAEDRNativeAddDeviceStateToList(newstate);
index a33d708..ff65d33 100644 (file)
@@ -40,8 +40,7 @@ CAResult_t CAInitializeEDR(CARegisterConnectivityCallback registerCallback,
     g_threadPoolHandle = handle;
 
     // register handlers
-    CAConnectivityHandler_t handler;
-    memset(&handler, 0, sizeof(CAConnectivityHandler_t));
+    CAConnectivityHandler_t handler = {};
 
     handler.startAdapter = CAStartEDR;
     handler.startListenServer = CAStartEDRListeningServer;
index a3a2ccc..645ff1d 100644 (file)
@@ -2614,7 +2614,7 @@ CAResult_t CALEClientUpdateDeviceState(const char* address, uint32_t connectedSt
         return CA_STATUS_FAILED;
     }
 
-    strcpy(newstate->address, address);
+    OICStrcpy(newstate->address, sizeof(newstate->address), address);
     newstate->connectedState = connectedState;
     newstate->notificationState = notificationState;
     newstate->sendState = sendState;
index 282cf88..ae85eff 100644 (file)
@@ -29,6 +29,7 @@
 #include "caqueueingthread.h"
 #include "camsgparser.h"
 #include "oic_malloc.h"
+#include "oic_string.h"
 
 /**
  * @var CALEADAPTER_TAG
@@ -564,12 +565,10 @@ CAResult_t CAGetLEInterfaceInformation(CALocalConnectivity_t **info, uint32_t *s
         return CA_STATUS_FAILED;
     }
 
-    strncpy((*info)->addressInfo.BT.btMacAddress, local_address,
-            sizeof((*info)->addressInfo.BT.btMacAddress) - 1);
-    (*info)->addressInfo.BT.btMacAddress[sizeof((*info)->addressInfo.BT.btMacAddress)-1] = '\0';
+    OICStrcpy((*info)->addressInfo.BT.btMacAddress, sizeof ((*info)->addressInfo.BT.btMacAddress),
+            local_address);
     ca_mutex_lock(g_bleLocalAddressMutex);
-    strncpy(g_localBLEAddress, local_address, sizeof(g_localBLEAddress) - 1);
-    g_localBLEAddress[sizeof(g_localBLEAddress)-1] = '\0';
+    OICStrcpy(g_localBLEAddress, sizeof(g_localBLEAddress), local_address);
     ca_mutex_unlock(g_bleLocalAddressMutex);
 
     (*info)->type = CA_LE;
@@ -617,7 +616,9 @@ void CALEDeviceStateChangedCb( CAAdapterState_t adapter_state)
     CALocalConnectivity_t localEndpoint = {};
 
     ca_mutex_lock(g_bleLocalAddressMutex);
-    strncpy(localEndpoint.addressInfo.BT.btMacAddress, g_localBLEAddress, strlen(g_localBLEAddress));
+    OICStrcpy(localEndpoint.addressInfo.BT.btMacAddress,
+            sizeof(localEndpoint.addressInfo.BT.btMacAddress),
+            g_localBLEAddress);
     ca_mutex_unlock(g_bleLocalAddressMutex);
 
     // Start a GattServer/Client if gLeServerStatus is SET
index 92d1990..f4b4df2 100644 (file)
@@ -40,8 +40,7 @@ CAResult_t CAInitializeLE(CARegisterConnectivityCallback registerCallback,
     g_threadPoolHandle = handle;
 
     // register handlers
-    CAConnectivityHandler_t handler;
-    memset(&handler, 0, sizeof(CAConnectivityHandler_t));
+    CAConnectivityHandler_t handler = {};
 
     handler.startAdapter = CAStartLE;
     handler.startListenServer = CAStartLEListeningServer;
index 30199fa..1d47591 100644 (file)
@@ -289,8 +289,7 @@ bool CABleGattCharacteristicsDiscoveredCb(int result,
 
         VERIFY_NON_NULL_RET(stTemp, TZ_BLE_CLIENT_TAG, "calloc failed!", false);
 
-        size_t len = strlen(bdAddress);
-        stTemp->address = (char *)OICMalloc(sizeof(char) * (len + 1));
+        stTemp->address = OICStrdup(bdAddress);
         if (NULL == stTemp->address)
         {
             OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG , "Malloc failed!");
@@ -298,7 +297,6 @@ bool CABleGattCharacteristicsDiscoveredCb(int result,
             return false;
         }
 
-        strncpy(stTemp->address, bdAddress, len + 1);
         bt_gatt_clone_attribute_handle(&(stTemp->serviceInfo), characteristic);
 
         ca_mutex_lock(g_bleClientThreadPoolMutex);
@@ -376,9 +374,8 @@ bool CABleGattPrimaryServiceCb(bt_gatt_attribute_h service, int index, int count
         VERIFY_NON_NULL_RET(stTemp, TZ_BLE_CLIENT_TAG, "Calloc Failed", false);
 
         char *bdAddress = (char *)userData;
-        size_t len = strlen(bdAddress);
 
-        stTemp->address = (char *)OICMalloc(sizeof(char) * (len + 1));
+        stTemp->address = OICStrdup(bdAddress);
         if (NULL == stTemp->address)
         {
             OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG , "Malloc failed!");
@@ -386,8 +383,6 @@ bool CABleGattPrimaryServiceCb(bt_gatt_attribute_h service, int index, int count
             return false;
         }
 
-        strncpy(stTemp->address, bdAddress, len + 1);
-
         BLEServiceInfo *bleServiceInfo = NULL;
 
         result = CACreateBLEServiceInfo(bdAddress, service, &bleServiceInfo);
@@ -567,12 +562,8 @@ void CABtAdapterLeDeviceDiscoveryStateChangedCb(int result,
                 CAResult_t res = CAVerifyOICServiceByUUID(discoveryInfo->service_uuid[i]);
                 if (CA_STATUS_OK == res)
                 {
-
-                    size_t len = strlen(discoveryInfo->remote_address);
-
-                    char *addr = (char *)OICMalloc(sizeof(char) * (len + 1));
+                    char *addr = OICStrdup(discoveryInfo->remote_address);
                     VERIFY_NON_NULL_VOID(addr, TZ_BLE_CLIENT_TAG, "Malloc failed");
-                    strncpy(addr, discoveryInfo->remote_address, len + 1);
 
                     OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG,
                               "Trying to do Gatt connection to [%s]", addr);
@@ -1192,12 +1183,9 @@ CAResult_t CABleGattDiscoverServices(const char *remoteAddress)
     VERIFY_NON_NULL_RET(remoteAddress, TZ_BLE_CLIENT_TAG,
                         "remote address is NULL", CA_STATUS_FAILED);
 
-    size_t len = strlen(remoteAddress);
-    char *addr = (char *)OICMalloc(sizeof(char) * (len + 1));
+    char *addr = OICStrdup(remoteAddress);
     VERIFY_NON_NULL_RET(addr, TZ_BLE_CLIENT_TAG, "Malloc failed", CA_STATUS_FAILED);
 
-    strncpy(addr, remoteAddress, len + 1);
-
     int32_t ret = bt_gatt_foreach_primary_services(remoteAddress, CABleGattPrimaryServiceCb,
                   (void *)addr); // addr memory will be free in callback.
     if (BT_ERROR_NONE != ret)
@@ -1254,11 +1242,8 @@ CAResult_t CABleGattDiscoverCharacteristics(bt_gatt_attribute_h service,
 
     VERIFY_NON_NULL_RET(remoteAddress, NULL, "remoteAddress is NULL", CA_STATUS_FAILED);
 
-    size_t len = strlen(remoteAddress);
-
-    char *addr = (char *)OICMalloc(sizeof(char) * (len + 1));
+    char *addr = OICStrdup(remoteAddress);
     VERIFY_NON_NULL_RET(addr, TZ_BLE_CLIENT_TAG, "Malloc failed", CA_STATUS_FAILED);
-    strncpy(addr, remoteAddress, len + 1);
 
     int32_t ret = bt_gatt_discover_characteristics(service, CABleGattCharacteristicsDiscoveredCb,
                   (void *)addr); // addr will be freed in callback.
index 36889f2..bfe3d8a 100644 (file)
@@ -590,14 +590,14 @@ void CABleGattRemoteCharacteristicWriteCb(char *charPath,
     OIC_LOG_V(DEBUG, TZ_BLE_SERVER_TAG, "charPath = [%s] charValue = [%s] len [%d]", charPath,
               charValue, charValueLen);
 
-    char *data = (char *)OICMalloc(sizeof(char) * charValueLen);
+    char *data = (char *)OICMalloc(sizeof(char) * charValueLen + 1);
     if (NULL == data)
     {
         OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "Malloc failed!");
         return;
     }
 
-    strncpy(data, (char *)charValue, charValueLen);
+    OICStrcpy(data, charValueLen + 1, charValue);
 
     ca_mutex_lock(g_bleReqRespCbMutex);
     if (NULL == g_bleServerDataReceivedCallback)
@@ -725,16 +725,15 @@ CAResult_t CAUpdateCharacteristicsToGattClient(const char* address, const char *
         return CA_STATUS_FAILED;
     }
 
-    char *data = (char *) OICMalloc(sizeof(char) * (charValueLen + 1));
+    char *data = (char *) OICCalloc(sizeof(char), (charValueLen + 1));
     if (NULL == data)
     {
         OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "malloc failed!");
         ca_mutex_unlock(g_bleCharacteristicMutex);
         return CA_STATUS_FAILED;
     }
-    memset(data, 0x0, (charValueLen + 1));
 
-    strncpy(data, charValue, charValueLen);
+    OICStrcpy(data, charValueLen + 1, charValue);
 
     OIC_LOG_V(DEBUG, TZ_BLE_SERVER_TAG, "updating characteristics char [%s] data [%s] dataLen [%d]",
               (const char *)g_gattReadCharPath, data, charValueLen);
@@ -780,7 +779,7 @@ CAResult_t CAUpdateCharacteristicsToAllGattClients(const char *charValue,
         return CA_STATUS_FAILED;
     }
 
-    strncpy(data, charValue, charValueLen + 1);
+    OICStrcpy(data, charValueLen + 1, charValue);
 
     OIC_LOG_V(DEBUG, TZ_BLE_SERVER_TAG, "updating characteristics char [%s] data [%s] dataLen [%d]",
               (const char *)g_gattReadCharPath, data, charValueLen);
index cc2eb81..b03cf17 100644 (file)
@@ -81,8 +81,7 @@ CAResult_t CACreateBLEServiceInfo(const char *bdAddress, bt_gatt_attribute_h ser
         return CA_STATUS_FAILED;
     }
 
-    size_t len = strlen(bdAddress);
-    (*bleServiceInfo)->bdAddress = (char *) OICMalloc(sizeof(char) * (len + 1));
+    (*bleServiceInfo)->bdAddress = OICStrdup(bdAddress);
 
     if (NULL == (*bleServiceInfo)->bdAddress)
     {
@@ -91,8 +90,6 @@ CAResult_t CACreateBLEServiceInfo(const char *bdAddress, bt_gatt_attribute_h ser
         return CA_STATUS_FAILED;
     }
 
-    strncpy((*bleServiceInfo)->bdAddress, bdAddress, len + 1);
-
     if (service)
     {
         int32_t ret = bt_gatt_clone_attribute_handle(&((*bleServiceInfo)->service_clone), service);
index a5380e1..4f0dd5d 100644 (file)
@@ -40,7 +40,7 @@
 
 #define CA_TRANSPORT_TYPE_NUM   4
 
-static CAConnectivityHandler_t g_adapterHandler[CA_TRANSPORT_TYPE_NUM];
+static CAConnectivityHandler_t g_adapterHandler[CA_TRANSPORT_TYPE_NUM] = {};
 
 static CANetworkPacketReceivedCallback g_networkPacketReceivedCallback = NULL;
 
@@ -93,7 +93,7 @@ static void CARegisterCallback(CAConnectivityHandler_t handler, CATransportType_
         return;
     }
 
-    memcpy(&g_adapterHandler[index], &handler, sizeof(CAConnectivityHandler_t));
+    g_adapterHandler[index] = handler;
 
     OIC_LOG_V(DEBUG, TAG, "%d type adapter, register complete!", cType);
 }
index fc2690e..a77afe3 100644 (file)
@@ -94,7 +94,7 @@ static void CARegisterCallback(CAConnectivityHandler_t handler, CATransportType_
         return;
     }
 
-    memcpy(&g_adapterHandler[index], &handler, sizeof(CAConnectivityHandler_t));
+    g_adapterHandler[index] = handler;
 
     OIC_LOG_V(DEBUG, TAG, "%d type adapter", cType);
     OIC_LOG(DEBUG, TAG, "OUT");
index 65bb218..b680b81 100644 (file)
@@ -37,6 +37,7 @@
 #include "caqueueingthread.h"
 #include "camutex.h"
 #include "oic_malloc.h"
+#include "oic_string.h"
 #include "canetworkconfigurator.h"
 
 #define TAG PCF("CA")
@@ -344,8 +345,7 @@ static void CAReceivedPacketCallback(CARemoteEndpoint_t *endpoint, void *data, u
         return;
     }
 
-    char uri[CA_MAX_URI_LENGTH] = { 0, };
-    uint32_t bufLen = sizeof(uri);
+    char uri[CA_MAX_URI_LENGTH] = { };
 
     if (CA_GET == code || CA_POST == code || CA_PUT == code || CA_DELETE == code)
     {
@@ -358,7 +358,7 @@ static void CAReceivedPacketCallback(CARemoteEndpoint_t *endpoint, void *data, u
             return;
         }
 
-        CAResult_t res = CAGetRequestInfoFromPDU(pdu, ReqInfo, uri, bufLen);
+        CAResult_t res = CAGetRequestInfoFromPDU(pdu, ReqInfo, uri, sizeof(uri));
         if (CA_STATUS_OK != res)
         {
             OIC_LOG_V(ERROR, TAG, "CAGetRequestInfoFromPDU failed : %d", res);
@@ -397,7 +397,7 @@ static void CAReceivedPacketCallback(CARemoteEndpoint_t *endpoint, void *data, u
         OIC_LOG_V(DEBUG, TAG, "Request- msgID : %d", ReqInfo->info.messageId);
         if (NULL != endpoint)
         {
-            endpoint->resourceUri = (char *) OICMalloc(bufLen + 1);
+            endpoint->resourceUri = (char *) OICMalloc(sizeof(uri) + 1);
             if (NULL == endpoint->resourceUri)
             {
                 OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, Memory allocation failed!");
@@ -406,8 +406,8 @@ static void CAReceivedPacketCallback(CARemoteEndpoint_t *endpoint, void *data, u
                 CAAdapterFreeRemoteEndpoint(endpoint);
                 return;
             }
-            memcpy(endpoint->resourceUri, uri, bufLen);
-            endpoint->resourceUri[bufLen] = '\0';
+            memcpy(endpoint->resourceUri, uri, sizeof(uri));
+            endpoint->resourceUri[sizeof(uri)] = '\0';
             OIC_LOG_V(DEBUG, TAG, "URI : %s", endpoint->resourceUri);
         }
         // store the data at queue.
@@ -439,7 +439,7 @@ static void CAReceivedPacketCallback(CARemoteEndpoint_t *endpoint, void *data, u
             return;
         }
 
-        CAResult_t res = CAGetResponseInfoFromPDU(pdu, ResInfo, uri, bufLen);
+        CAResult_t res = CAGetResponseInfoFromPDU(pdu, ResInfo, uri, sizeof(uri));
         if (CA_STATUS_OK != res)
         {
             OIC_LOG_V(ERROR, TAG, "CAGetResponseInfoFromPDU failed : %d", res);
@@ -470,7 +470,7 @@ static void CAReceivedPacketCallback(CARemoteEndpoint_t *endpoint, void *data, u
 
         if (NULL != endpoint)
         {
-            endpoint->resourceUri = (char *) OICMalloc(bufLen + 1);
+            endpoint->resourceUri = (char *) OICMalloc(sizeof(uri) + 1);
             if (NULL == endpoint->resourceUri)
             {
                 OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, Memory allocation failed !");
@@ -479,8 +479,8 @@ static void CAReceivedPacketCallback(CARemoteEndpoint_t *endpoint, void *data, u
                 CAAdapterFreeRemoteEndpoint(endpoint);
                 return;
             }
-            memcpy(endpoint->resourceUri, uri, bufLen);
-            endpoint->resourceUri[bufLen] = '\0';
+            memcpy(endpoint->resourceUri, uri, sizeof(uri));
+            endpoint->resourceUri[sizeof(uri)] = '\0';
             OIC_LOG_V(DEBUG, TAG, "URI : %s", endpoint->resourceUri);
         }
 
@@ -1052,9 +1052,7 @@ void CAErrorHandler(const CARemoteEndpoint_t *remoteEndpoint, const void *data,
 
     if(NULL == rep->resourceUri)
     {
-        uint32_t bufLen = sizeof(uri);
-
-        CAURI_t resourceUri = (CAURI_t) OICMalloc(bufLen + 1);
+        CAURI_t resourceUri = OICStrdup(uri);
         if (NULL == resourceUri)
         {
             OIC_LOG(ERROR, TAG, "CAErrorHandler, Memory allocation failed!");
@@ -1063,8 +1061,6 @@ void CAErrorHandler(const CARemoteEndpoint_t *remoteEndpoint, const void *data,
             return;
         }
 
-        memcpy(resourceUri, uri, bufLen);
-        resourceUri[bufLen] = '\0';
         OIC_LOG_V(DEBUG, TAG, "URI : %s", resourceUri);
         rep->resourceUri = resourceUri;
     }
index 0ce2c40..655775d 100644 (file)
@@ -196,8 +196,7 @@ static void CAReceivedPacketCallback(CARemoteEndpoint_t *endpoint, void *data, u
         return;
     }
 
-    char uri[CA_MAX_URI_LENGTH] = { 0, };
-    uint32_t bufLen = sizeof(uri);
+    char uri[CA_MAX_URI_LENGTH] = { };
 
     if (CA_GET == code || CA_POST == code || CA_PUT == code || CA_DELETE == code)
     {
@@ -209,7 +208,7 @@ static void CAReceivedPacketCallback(CARemoteEndpoint_t *endpoint, void *data, u
             return;
         }
 
-        CAResult_t res = CAGetRequestInfoFromPDU(pdu, ReqInfo, uri, bufLen);
+        CAResult_t res = CAGetRequestInfoFromPDU(pdu, ReqInfo, uri, sizeof(uri));
         if (CA_STATUS_OK != res)
         {
             OIC_LOG_V(ERROR, TAG, "CAGetRequestInfoFromPDU failed : %d", res);
@@ -238,7 +237,7 @@ static void CAReceivedPacketCallback(CARemoteEndpoint_t *endpoint, void *data, u
         OIC_LOG_BUFFER(DEBUG, TAG, (const uint8_t *) ReqInfo->info.token, CA_MAX_TOKEN_LEN);
         if (NULL != endpoint)
         {
-            endpoint->resourceUri = (char *) OICMalloc(bufLen + 1);
+            endpoint->resourceUri = (char *) OICMalloc(sizeof(uri) + 1);
             if (NULL == endpoint->resourceUri)
             {
                 OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, Memory allocation failed!");
@@ -246,8 +245,8 @@ static void CAReceivedPacketCallback(CARemoteEndpoint_t *endpoint, void *data, u
                 coap_delete_pdu(pdu);
                 return;
             }
-            memcpy(endpoint->resourceUri, uri, bufLen);
-            endpoint->resourceUri[bufLen] = '\0';
+            memcpy(endpoint->resourceUri, uri, sizeof(uri));
+            endpoint->resourceUri[sizeof(uri)] = '\0';
             OIC_LOG_V(DEBUG, TAG, "URI : %s", endpoint->resourceUri);
         }
 
@@ -271,7 +270,7 @@ static void CAReceivedPacketCallback(CARemoteEndpoint_t *endpoint, void *data, u
             return;
         }
 
-        CAResult_t res = CAGetResponseInfoFromPDU(pdu, ResInfo, uri, bufLen);
+        CAResult_t res = CAGetResponseInfoFromPDU(pdu, ResInfo, uri, sizeof(uri));
         if (CA_STATUS_OK != res)
         {
             OIC_LOG_V(ERROR, TAG, "CAGetResponseInfoFromPDU failed : %d", res);
@@ -298,7 +297,7 @@ static void CAReceivedPacketCallback(CARemoteEndpoint_t *endpoint, void *data, u
 
         if (NULL != endpoint)
         {
-            endpoint->resourceUri = (char *) OICMalloc(bufLen + 1);
+            endpoint->resourceUri = (char *) OICMalloc(sizeof(uri) + 1);
             if (NULL == endpoint->resourceUri)
             {
                 OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, Memory allocation failed !");
@@ -306,8 +305,8 @@ static void CAReceivedPacketCallback(CARemoteEndpoint_t *endpoint, void *data, u
                 coap_delete_pdu(pdu);
                 return;
             }
-            memcpy(endpoint->resourceUri, uri, bufLen);
-            endpoint->resourceUri[bufLen] = '\0';
+            memcpy(endpoint->resourceUri, uri, sizeof(uri));
+            endpoint->resourceUri[sizeof(uri)] = '\0';
             OIC_LOG_V(DEBUG, TAG, "URI : %s", endpoint->resourceUri);
         }
 
index f434bd7..fedc0de 100644 (file)
@@ -49,6 +49,7 @@
 #include "caprotocolmessage.h"
 #include "logger.h"
 #include "oic_malloc.h"
+#include "oic_string.h"
 
 // ARM GCC compiler doesnt define srandom function.
 #if defined(ARDUINO) && !defined(ARDUINO_ARCH_SAM)
@@ -163,8 +164,8 @@ coap_pdu_t *CAGeneratePDU(const char *uri, uint32_t code, const CAInfo_t info)
                 OIC_LOG(ERROR, TAG, "out of memory");
                 return NULL;
             }
-            strcat(coapUri, COAP_URI_HEADER);
-            strcat(coapUri, uri);
+            OICStrcat(coapUri, uriLength, COAP_URI_HEADER);
+            OICStrcat(coapUri, uriLength, uri);
 
             // parsing options in URI
             CAResult_t res = CAParseURI(coapUri, &optlist);
@@ -735,7 +736,6 @@ CAResult_t CAGetInfoFromPDU(const coap_pdu_t *pdu, uint32_t *outCode, CAInfo_t *
     if (buflen >= length)
     {
         memcpy(outUri, optionResult, length);
-        outUri[length] = '\0';
 #ifdef ARDUINO
         OIC_LOG_V(DEBUG, TAG, "made URL:%s\n", optionResult);
 #else
index 7e3f114..08f003f 100644 (file)
@@ -21,6 +21,7 @@
 #include <string.h>
 
 #include "oic_malloc.h"
+#include "oic_string.h"
 #include "caremotehandler.h"
 #include "logger.h"
 
@@ -41,14 +42,12 @@ CARemoteEndpoint_t *CACloneRemoteEndpoint(const CARemoteEndpoint_t *rep)
         OIC_LOG(ERROR, TAG, "CACloneRemoteEndpoint Out of memory");
         return NULL;
     }
-    memcpy(clone, rep, sizeof(CARemoteEndpoint_t));
+    *clone = *rep;
 
     if (NULL != rep->resourceUri)
     {
         // allocate reference uri field
-        size_t len = strlen(rep->resourceUri);
-
-        char *temp = (char *) OICCalloc(len + 1, sizeof(char));
+        char *temp = OICStrdup(rep->resourceUri);
         if (NULL == temp)
         {
             OIC_LOG(ERROR, TAG, "CACloneRemoteEndpoint Out of memory");
@@ -58,8 +57,6 @@ CARemoteEndpoint_t *CACloneRemoteEndpoint(const CARemoteEndpoint_t *rep)
             return NULL;
         }
 
-        strncpy(temp, rep->resourceUri, len);
-
         // save the uri
         clone->resourceUri = temp;
     }
@@ -112,13 +109,13 @@ static int32_t getCAAddress(const char *pAddress, CAAddress_t *outAddress)
     {
         if(ipLen && ipLen < sizeof(outAddress->IP.ipAddress))
         {
-            strncpy(outAddress->IP.ipAddress, pAddress, ipLen);
-            outAddress->IP.ipAddress[ipLen] = '\0';
+            OICStrcpyPartial(outAddress->IP.ipAddress, sizeof(outAddress->IP.ipAddress),
+                    pAddress, ipLen);
         }
         else if (!ipLen && len < sizeof(outAddress->IP.ipAddress))
         {
-            strncpy(outAddress->IP.ipAddress, pAddress, len);
-            outAddress->IP.ipAddress[len] = '\0';
+            OICStrcpy(outAddress->IP.ipAddress, sizeof(outAddress->IP.ipAddress),
+                    pAddress);
         }
         else
         {
@@ -136,7 +133,8 @@ static int32_t getCAAddress(const char *pAddress, CAAddress_t *outAddress)
     }
     else
     {
-        strncpy(outAddress->BT.btMacAddress, pAddress, CA_MACADDR_SIZE - 1);
+        OICStrcpy(outAddress->BT.btMacAddress, sizeof(outAddress->BT.btMacAddress),
+                    pAddress);
 
         OIC_LOG_V(DEBUG, TAG, "mac address : %s", outAddress->BT.btMacAddress);
     }
@@ -269,9 +267,7 @@ CARemoteEndpoint_t *CACreateRemoteEndpointInternal(const CAURI_t resourceUri,
     }
 
     // allocate reference uri field
-    size_t len = strlen(resourceUri);
-
-    char *temp = (char *) OICMalloc(sizeof(char) * (len + 1));
+    char *temp = OICStrdup(resourceUri);
     if (NULL == temp)
     {
         OIC_LOG(ERROR, TAG, "CACreateRemoteEndpointInternal Out of memory");
@@ -280,14 +276,12 @@ CARemoteEndpoint_t *CACreateRemoteEndpointInternal(const CAURI_t resourceUri,
 
         return NULL;
     }
-    strncpy(temp, resourceUri, len);
-    temp[len] = '\0';
 
     // save the uri
     rep->resourceUri = temp;
 
     // save the addressInfo
-    memcpy(&(rep->addressInfo), &addr, sizeof(CAAddress_t));
+    rep->addressInfo = addr;
 
     // save the type
     rep->transportType = type;
@@ -311,7 +305,7 @@ CARequestInfo_t *CACloneRequestInfo(const CARequestInfo_t *rep)
         return NULL;
     }
 
-    memcpy(clone, rep, sizeof(CARequestInfo_t));
+    *clone = *rep;
 
     if (rep->info.token)
     {
@@ -363,9 +357,7 @@ CARequestInfo_t *CACloneRequestInfo(const CARequestInfo_t *rep)
     if (NULL != rep->info.payload)
     {
         // allocate payload field
-        size_t len = strlen(rep->info.payload);
-
-        char *temp = (char *) OICMalloc(sizeof(char) * (len + 1));
+        char *temp = OICStrdup(rep->info.payload);
         if (NULL == temp)
         {
             OIC_LOG(ERROR, TAG, "CACloneRequestInfo Out of memory");
@@ -374,8 +366,6 @@ CARequestInfo_t *CACloneRequestInfo(const CARequestInfo_t *rep)
 
             return NULL;
         }
-        strncpy(temp, rep->info.payload, len);
-        temp[len] = '\0';
 
         // save the payload
         clone->info.payload = temp;
@@ -418,7 +408,7 @@ CAResponseInfo_t *CACloneResponseInfo(const CAResponseInfo_t *rep)
         OIC_LOG(ERROR, TAG, "CACloneResponseInfo Out of memory");
         return NULL;
     }
-    memcpy(clone, rep, sizeof(CAResponseInfo_t));
+    *clone = *rep;
 
     if (rep->info.token)
     {
@@ -471,9 +461,7 @@ CAResponseInfo_t *CACloneResponseInfo(const CAResponseInfo_t *rep)
     if (NULL != rep->info.payload)
     {
         // allocate payload field
-        int32_t len = strlen(rep->info.payload);
-
-        char *temp = (char *) OICCalloc(len + 1, sizeof(char));
+        char *temp = OICStrdup(rep->info.payload);
         if (NULL == temp)
         {
             OIC_LOG(ERROR, TAG, "CACloneResponseInfo Out of memory");
@@ -482,7 +470,6 @@ CAResponseInfo_t *CACloneResponseInfo(const CAResponseInfo_t *rep)
 
             return NULL;
         }
-        strncpy(temp, rep->info.payload, len);
 
         // save the payload
         clone->info.payload = temp;
index e419278..d7d9dba 100644 (file)
@@ -190,8 +190,7 @@ CAResult_t CARetransmissionInitialize(CARetransmission_t *context,
 
     memset(context, 0, sizeof(CARetransmission_t));
 
-    CARetransmissionConfig_t cfg;
-    memset(&cfg, 0, sizeof(CARetransmissionConfig_t));
+    CARetransmissionConfig_t cfg = {};
 
     if (NULL == config)
     {
index a4103eb..ef3a5f7 100644 (file)
@@ -256,7 +256,7 @@ static CAResult_t CAIPUpdateInterfaceInformation(u_arraylist_t **netInterfaceLis
         char interfaceSubnetMask[CA_IPADDR_SIZE] = { 0 };
         socklen_t len = sizeof(struct sockaddr_in);
 
-        strcpy(temp_ifr.ifr_name, item->ifr_name);
+        OICStrcpy(temp_ifr.ifr_name, sizeof(temp_ifr.ifr_name), item->ifr_name);
 
         if (ioctl(sck, SIOCGIFFLAGS, &temp_ifr))
         {
@@ -316,13 +316,13 @@ static CAResult_t CAIPUpdateInterfaceInformation(u_arraylist_t **netInterfaceLis
         }
 
         // set interface name
-        strncpy(netInfo->interfaceName, item->ifr_name, strlen(item->ifr_name));
+        OICStrcpy(netInfo->interfaceName, sizeof(netInfo->interfaceName), item->ifr_name);
 
         // set local ip address
-        strncpy(netInfo->ipAddress, interfaceAddress, strlen(interfaceAddress));
+        OICStrcpy(netInfo->ipAddress, sizeof(netInfo->ipAddress), interfaceAddress);
 
         // set subnet mask
-        strncpy(netInfo->subnetMask, interfaceSubnetMask, strlen(interfaceSubnetMask));
+        OICStrcpy(netInfo->subnetMask, sizeof(netInfo->subnetMask), interfaceSubnetMask);
 
         CAResult_t result = u_arraylist_add(*netInterfaceList, (void *) netInfo);
         if (CA_STATUS_OK != result)
@@ -414,7 +414,7 @@ static bool CACheckIsInterfaceInfoChanged(const CANetInfo_t *info)
         ca_mutex_unlock(g_networkMonitorContextMutex);
         return false;
     }
-    memcpy(newNetInfo, info, sizeof(*newNetInfo));
+    *newNetInfo = *info;
 
     OIC_LOG(DEBUG, IP_MONITOR_TAG, "New Interface found");
 
@@ -657,7 +657,7 @@ CAResult_t CAIPGetInterfaceInfo(u_arraylist_t **netInterfaceList)
             return CA_MEMORY_ALLOC_FAILED;
         }
 
-        memcpy(newNetinfo, info, sizeof(*info));
+        *newNetinfo = *info;
 
         CAResult_t result = u_arraylist_add(*netInterfaceList, (void *) newNetinfo);
         if (CA_STATUS_OK != result)
index 0a455f4..efa6e67 100644 (file)
@@ -34,6 +34,7 @@
 #include "uarraylist.h"
 #include "logger.h"
 #include "oic_malloc.h"
+#include "oic_string.h"
 
 /**
  * @def IP_ADAPTER_TAG
@@ -632,8 +633,9 @@ CAResult_t CAGetIPInterfaceInformation(CALocalConnectivity_t **info, uint32_t *s
         conInfo[count].type = CA_IPV4;
         conInfo[count].isSecured = false;
         conInfo[count].addressInfo.IP.port = CAGetServerPortNum(netInfo->ipAddress, false);
-        strncpy(conInfo[count].addressInfo.IP.ipAddress, netInfo->ipAddress,
-                strlen(netInfo->ipAddress));
+        OICStrcpy(conInfo[count].addressInfo.IP.ipAddress,
+                  sizeof(conInfo[count].addressInfo.IP.ipAddress),
+                  netInfo->ipAddress);
 
 #ifdef __WITH_DTLS__
         // copy secure unicast server information
@@ -642,8 +644,9 @@ CAResult_t CAGetIPInterfaceInformation(CALocalConnectivity_t **info, uint32_t *s
             conInfo[count].type = CA_IPV4;
             conInfo[count].isSecured = true;
             conInfo[count].addressInfo.IP.port = CAGetServerPortNum(netInfo->ipAddress, true);
-            strncpy(conInfo[count].addressInfo.IP.ipAddress, netInfo->ipAddress,
-                    strlen(netInfo->ipAddress));
+            OICStrcpy(conInfo[count].addressInfo.IP.ipAddress,
+                      sizeof(conInfo[count].addressInfo.IP.ipAddress),
+                      netInfo->ipAddress);
         }
 #endif
         count ++;
index e08faed..35e4c77 100644 (file)
@@ -36,6 +36,7 @@
 #endif
 #include "camutex.h"
 #include "oic_malloc.h"
+#include "oic_string.h"
 
 /**
  * @def IP_SERVER_TAG
@@ -160,7 +161,7 @@ static void CAReceiveHandler(void *data)
                 return;
             }
 
-            memcpy(newInfo, info, sizeof(CAServerInfo_t));
+            *newInfo = *info;
 
             CAResult_t result = u_arraylist_add(tempServerInfoList, (void *) newInfo);
             if (CA_STATUS_OK != result)
@@ -623,19 +624,16 @@ CAResult_t CAIPStartUnicastServer(const char *localAddress, uint16_t *port,
         }
         if (netMask)
         {
-            strncpy(info->subNetMask, netMask, sizeof(info->subNetMask) - 1);
-            info->subNetMask[sizeof(info->subNetMask)-1] = '\0';
+            OICStrcpy(info->subNetMask, sizeof(info->subNetMask), netMask);
             OICFree(netMask);
         }
-        strncpy(info->ipAddress, localAddress, sizeof(info->ipAddress) - 1);
-        info->ipAddress[sizeof(info->ipAddress) - 1] = '\0';
+        OICStrcpy(info->ipAddress, sizeof(info->ipAddress), localAddress);
         info->port = *port;
         info->socketFd = unicastServerFd;
         info->isSecured = isSecured;
         info->isServerStarted = true;
         info->isMulticastServer = false;
-        strncpy(info->ifAddr, localAddress, sizeof(info->ifAddr) - 1);
-        info->ifAddr[sizeof(info->ifAddr) - 1] = '\0';
+        OICStrcpy(info->ifAddr, sizeof(info->ifAddr), localAddress);
 
         CAResult_t res = CAAddServerInfo(g_serverInfoList, info);
         if (CA_STATUS_OK != res)
@@ -725,20 +723,17 @@ CAResult_t CAIPStartMulticastServer(const char *localAddress, const char *multic
         }
         if (netMask)
         {
-            strncpy(info->subNetMask, netMask, sizeof(info->subNetMask) - 1);
-            info->subNetMask[sizeof(info->subNetMask) -1] = '\0';
+            OICStrcpy(info->subNetMask, sizeof(info->subNetMask), netMask);
             OICFree(netMask);
         }
 
-        strncpy(info->ipAddress, multicastAddress, sizeof(info->ipAddress) - 1);
-        info->ipAddress[sizeof(info->ipAddress) -1] = '\0';
+        OICStrcpy(info->ipAddress, sizeof(info->ipAddress), multicastAddress);
         info->port = multicastPort;
         info->socketFd = mulicastServerFd;
         info->isSecured = false;
         info->isServerStarted = true;
         info->isMulticastServer = true;
-        strncpy(info->ifAddr, localAddress, sizeof(info->ifAddr)-1);
-        info->ifAddr[sizeof(info->ifAddr) -1] = '\0';
+        OICStrcpy(info->ifAddr, sizeof(info->ifAddr), localAddress);
 
         ret = CAAddServerInfo(g_serverInfoList, info);
 
@@ -932,7 +927,7 @@ CAResult_t CAGetIPServerInfoList(u_arraylist_t **serverInfoList)
             return CA_MEMORY_ALLOC_FAILED;
         }
 
-        memcpy(newNetinfo, info, sizeof(*info));
+        *newNetinfo = *info;
 
         CAResult_t result = u_arraylist_add(*serverInfoList, (void *) newNetinfo);
         if (CA_STATUS_OK != result)
index c077580..d9d8f3b 100644 (file)
@@ -136,14 +136,13 @@ static void CAIPGetInterfaceInformation(u_arraylist_t **netInterfaceList)
             return;
         }
         // set interface name
-        strncpy(netInfo->interfaceName, ifa->ifa_name, sizeof(netInfo->interfaceName) - 1);
-        netInfo->interfaceName[sizeof(netInfo->interfaceName)-1] = '\0';
+        OICStrcpy(netInfo->interfaceName, sizeof(netInfo->interfaceName), ifa->ifa_name);
 
         // set local ip address
-        strncpy(netInfo->ipAddress, interfaceAddress, strlen(interfaceAddress));
+        OICStrcpy(netInfo->ipAddress, sizeof(netInfo->ipAddress), interfaceAddress);
 
         // set subnet mask
-        strncpy(netInfo->subnetMask, interfaceSubnetMask, strlen(interfaceSubnetMask));
+        OICStrcpy(netInfo->subnetMask, sizeof(netInfo->subnetMask), interfaceSubnetMask);
 
         CAResult_t result = u_arraylist_add(*netInterfaceList, (void *)netInfo);
         if (CA_STATUS_OK != result)
@@ -232,7 +231,7 @@ static bool CACheckIsInterfaceInfoChanged(const CANetInfo_t *info)
         ca_mutex_unlock(g_networkMonitorContextMutex);
         return false;
     }
-    memcpy(newNetInfo, info, sizeof(*newNetInfo));
+    *newNetInfo = *info;
 
     OIC_LOG(DEBUG, IP_MONITOR_TAG, "New Interface found");
 
@@ -559,7 +558,7 @@ CAResult_t CAIPGetInterfaceInfo(u_arraylist_t **netInterfaceList)
             return CA_MEMORY_ALLOC_FAILED;
         }
 
-        memcpy(newNetinfo, info, sizeof(*info));
+        *newNetinfo = *info;
 
         CAResult_t result = u_arraylist_add(*netInterfaceList, (void *)newNetinfo);
         if (CA_STATUS_OK != result)
index 1a46cd8..231975c 100644 (file)
@@ -148,7 +148,7 @@ static bool CACheckIsInterfaceInfoChanged(const CANetInfo_t *info)
         ca_mutex_unlock(g_networkMonitorContextMutex);
         return false;
     }
-    memcpy(newNetInfo, info, sizeof(*newNetInfo));
+    *newNetInfo = *info;
 
     OIC_LOG(DEBUG, IP_MONITOR_TAG, "New Interface found");
 
@@ -258,13 +258,13 @@ static void CAIPGetInterfaceInformation(u_arraylist_t **netInterfaceList)
     }
 
     // set interface name
-    strncpy(netInfo->interfaceName, interfaceName, strlen(interfaceName));
+    OICStrcpy(netInfo->interfaceName, sizeof(netInfo->interfaceName), interfaceName);
 
     // set local ip address
-    strncpy(netInfo->ipAddress, ipAddress, strlen(ipAddress));
+    OICStrcpy(netInfo->ipAddress, sizeof(netInfo->ipAddress), ipAddress);
 
     // set subnet mask
-    strncpy(netInfo->subnetMask, subnetMask, strlen(subnetMask));
+    OICStrcpy(netInfo->subnetMask, sizeof(netInfo->subnetMask), subnetMask);
 
     CAResult_t result = u_arraylist_add(*netInterfaceList, (void *)netInfo);
     if (CA_STATUS_OK != result)
@@ -309,13 +309,13 @@ void CAWIFIConnectionStateChangedCb(wifi_connection_state_e state, wifi_ap_h ap,
         }
 
         // set interface name
-        strncpy(netInfo->interfaceName, interfaceName, strlen(interfaceName));
+        OICStrcpy(netInfo->interfaceName, sizeof(netInfo->interfaceName), interfaceName);
 
         // set local ip address
-        strncpy(netInfo->ipAddress, ipAddress, strlen(ipAddress));
+        OICStrcpy(netInfo->ipAddress, sizeof(netInfo->ipAddress), ipAddress);
 
         // set subnet mask
-        strncpy(netInfo->subnetMask, subnetMask, strlen(subnetMask));
+        OICStrcpy(netInfo->subnetMask, sizeof(netInfo->subnetMask), subnetMask);
 
         bool ret = CACheckIsInterfaceInfoChanged(netInfo);
         if (ret)
@@ -541,7 +541,7 @@ CAResult_t CAIPGetInterfaceInfo(u_arraylist_t **netInterfaceList)
             return CA_MEMORY_ALLOC_FAILED;
         }
 
-        memcpy(newNetinfo, info, sizeof(*info));
+        *newNetinfo = *info;
 
         CAResult_t result = u_arraylist_add(*netInterfaceList, (void *)newNetinfo);
         if (CA_STATUS_OK != result)
index b642464..4b090a5 100644 (file)
@@ -117,8 +117,7 @@ void OCLogv(LogLevel level, const char * tag, const char * format, ...) {
     if (!format || !tag) {
         return;
     }
-    char buffer[MAX_LOG_V_BUFFER_SIZE];
-    memset(buffer, 0, sizeof buffer);
+    char buffer[MAX_LOG_V_BUFFER_SIZE] = {};
     va_list args;
     va_start(args, format);
     vsnprintf(buffer, sizeof buffer - 1, format, args);
@@ -200,6 +199,8 @@ void OCLogBuffer(LogLevel level, const char * tag, const uint8_t * buffer, uint1
         return;
     }
 
+    // No idea why the static initialization won't work here, it seems the compiler is convinced
+    // that this is a variable-sized object.
     char lineBuffer[LINE_BUFFER_SIZE];
     memset(lineBuffer, 0, sizeof lineBuffer);
     int lineIndex = 0;
index 9f22173..07028e2 100644 (file)
@@ -50,8 +50,7 @@ TEST(RandomGeneration,OCGetRandom) {
 
 TEST(RandomGeneration,OCFillRandomMem) {
     uint16_t ARR_SIZE = 20;
-    uint8_t array[ARR_SIZE];
-    memset(array, 0, ARR_SIZE);
+    uint8_t array[ARR_SIZE]={};
     OCFillRandomMem(array + 1, ARR_SIZE - 2);
 
     for (int i = 1; i < ARR_SIZE - 2; i++) {
index 904b73c..d9faf0d 100644 (file)
@@ -52,8 +52,7 @@ void setup() {
     }
 
     Serial.print("Testing OCFillRandomMem ... ");
-    uint8_t array[ARR_SIZE];
-    memset(array, 0, ARR_SIZE);
+    uint8_t array[ARR_SIZE] = {};
     OCFillRandomMem(array + 1, ARR_SIZE - 2);
     uint8_t overall = 0;
     uint8_t value82 = 0;
index 837a4d8..d8654fa 100644 (file)
@@ -51,8 +51,7 @@ TEST(RandomGeneration,OCGetRandom) {
 }
 
 TEST(RandomGeneration,OCFillRandomMem) {
-    uint8_t array[ARR_SIZE];
-    memset(array, 0, ARR_SIZE);
+    uint8_t array[ARR_SIZE] = {};
     OCFillRandomMem(array + 1, ARR_SIZE - 2);
 
     for (int i = 1; i <= ARR_SIZE - 2; i++) {
index 1d3932c..dd53780 100644 (file)
@@ -261,19 +261,6 @@ OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
         OCResourceProperty resourceProperties, uint8_t enable);
 #endif
 
-/**
- * Clones a string IFF its pointer value is not NULL.
- *
- * Note: The caller to this function is responsible for calling @ref OCFree
- * for the destination parameter.
- *
- * @param dest The destination string for the string value to be cloned.
- *
- * @param src The source for the string value to be to cloned.
- */
-OCStackResult CloneStringIfNonNull(char **dest, const char *src);
-
-
 const char *convertTriggerEnumToString(OCPresenceTrigger trigger);
 
 OCPresenceTrigger convertTriggerStringToEnum(const char * triggerStr);
index 901b8db..2df74d9 100644 (file)
@@ -33,6 +33,7 @@
 #include "logger.h"
 #include "cJSON.h"
 #include "oic_malloc.h"
+#include "oic_string.h"
 
 /// Module Name
 #include <stdio.h>
@@ -248,7 +249,7 @@ static OCStackResult BuildRootResourceJSON(OCResource *resource,
         jsonLen = strlen(jsonStr);
         if (jsonLen < *remaining)
         {
-            strncpy(bufferPtr, jsonStr, jsonLen);
+            OICStrcpy(bufferPtr, *remaining, jsonStr);
             *remaining -= jsonLen;
             bufferPtr += jsonLen;
             ret = OC_STACK_OK;
index c0800c2..555db9b 100644 (file)
@@ -26,6 +26,7 @@
 #include "ocresourcehandler.h"
 #include "ocrandom.h"
 #include "oic_malloc.h"
+#include "oic_string.h"
 #include "ocserverrequest.h"
 #include "cJSON.h"
 
@@ -93,7 +94,7 @@ static OCStackResult BuildPresenceResponse(char *out, uint16_t *remaining,
 
         if (jsonLen < *remaining)
         {
-            strncpy(out, jsonStr, (jsonLen + 1));
+            OICStrcpy(out, *remaining, jsonStr);
             *remaining = *remaining - jsonLen;
             ret = OC_STACK_OK;
         }
@@ -261,8 +262,8 @@ OCStackResult SendAllObserverNotification (OCMethod method, OCResource *resPtr,
                         ehResponse.persistentBufferFlag = 0;
                         ehResponse.requestHandle = (OCRequestHandle) request;
                         ehResponse.resourceHandle = (OCResourceHandle) resPtr;
-                        strcpy((char *)ehResponse.resourceUri,
-                                (const char *)resourceObserver->resUri);
+                        OICStrcpy(ehResponse.resourceUri, sizeof(ehResponse.resourceUri),
+                                resourceObserver->resUri);
                         result = OCDoResponse(&ehResponse);
                     }
                 }
@@ -339,8 +340,8 @@ OCStackResult SendListObserverNotification (OCResource * resource,
                             FindAndDeleteServerRequest(request);
                             continue;
                         }
-                        strncpy(ehResponse.payload, notificationJSONPayload, MAX_RESPONSE_LENGTH-1);
-                        ehResponse.payload[MAX_RESPONSE_LENGTH] = '\0';
+                        OICStrcpy(ehResponse.payload, MAX_RESPONSE_LENGTH + 1,
+                                notificationJSONPayload);
                         ehResponse.payloadSize = strlen(ehResponse.payload) + 1;
                         ehResponse.persistentBufferFlag = 0;
                         ehResponse.requestHandle = (OCRequestHandle) request;
@@ -445,16 +446,14 @@ OCStackResult AddObserver (const char         *resUri,
     {
         obsNode->observeId = obsId;
 
-        obsNode->resUri = (char *)OICMalloc(strlen(resUri)+1);
+        obsNode->resUri = OICStrdup(resUri);
         VERIFY_NON_NULL (obsNode->resUri);
-        memcpy (obsNode->resUri, resUri, strlen(resUri)+1);
 
         obsNode->qos = qos;
         if(query)
         {
-            obsNode->query = (char *)OICMalloc(strlen(query)+1);
+            obsNode->query = OICStrdup(query);
             VERIFY_NON_NULL (obsNode->query);
-            memcpy (obsNode->query, query, strlen(query)+1);
         }
         // If tokenLength is zero, the return value depends on the
         // particular library implementation (it may or may not be a null pointer).
@@ -630,10 +629,7 @@ GetObserveHeaderOption (uint32_t * observationOption,
             *observationOption = options[i].optionData[0];
             for(uint8_t c = i; c < *numOptions-1; c++)
             {
-                options[i].protocolID = options[i+1].protocolID;
-                options[i].optionID = options[i+1].optionID;
-                options[i].optionLength = options[i+1].optionLength;
-                memcpy(options[i].optionData, options[i+1].optionData, options[i+1].optionLength);
+                options[i] = options[i+1];
             }
             (*numOptions)--;
             return OC_STACK_OK;
index 934155d..0e358df 100644 (file)
@@ -31,6 +31,7 @@
 #include "ocobserve.h"
 #include "occollection.h"
 #include "oic_malloc.h"
+#include "oic_string.h"
 #include "logger.h"
 #include "cJSON.h"
 
@@ -429,7 +430,7 @@ BuildVirtualResourceResponse(const OCResource *resourcePtr, uint8_t filterOn,
     jsonLen = strlen(jsonStr);
     if (jsonLen < *remaining)
     {
-        strcpy(out, jsonStr);
+        OICStrcpy(out, *remaining, jsonStr);
         *remaining = *remaining - jsonLen;
     }
     else
@@ -463,7 +464,7 @@ OCStackResult BuildVirtualResourceResponseForDevice(uint8_t filterOn, char *filt
 
         if (jsonLen < *remaining)
         {
-            strncpy(out, jsonStr, (jsonLen + 1));
+            OICStrcpy(out, *remaining, jsonStr);
             *remaining = *remaining - jsonLen;
             ret = OC_STACK_OK;
         }
@@ -494,7 +495,7 @@ OCStackResult BuildVirtualResourceResponseForPlatform(char *out, uint16_t *remai
 
         if (jsonLen < *remaining)
         {
-            strncpy(out, jsonStr, (jsonLen + 1));
+            OICStrcpy(out, *remaining, jsonStr);
             *remaining = *remaining - jsonLen;
             ret = OC_STACK_OK;
         }
@@ -1106,46 +1107,36 @@ void DeletePlatformInfo()
 
 static OCStackResult DeepCopyPlatFormInfo(OCPlatformInfo info)
 {
-    OCStackResult ret = OC_STACK_OK;
-    ret = CloneStringIfNonNull(&(savedPlatformInfo.platformID), info.platformID);
-    VERIFY_SUCCESS(ret, OC_STACK_OK);
-
-    ret = CloneStringIfNonNull(&(savedPlatformInfo.manufacturerName), info.manufacturerName);
-    VERIFY_SUCCESS(ret, OC_STACK_OK);
-
-    ret = CloneStringIfNonNull(&(savedPlatformInfo.manufacturerUrl), info.manufacturerUrl);
-    VERIFY_SUCCESS(ret, OC_STACK_OK);
-
-    ret = CloneStringIfNonNull(&(savedPlatformInfo.modelNumber), info.modelNumber);
-    VERIFY_SUCCESS(ret, OC_STACK_OK);
-
-    ret = CloneStringIfNonNull(&(savedPlatformInfo.dateOfManufacture), info.dateOfManufacture);
-    VERIFY_SUCCESS(ret, OC_STACK_OK);
-
-    ret = CloneStringIfNonNull(&(savedPlatformInfo.platformVersion), info.platformVersion);
-    VERIFY_SUCCESS(ret, OC_STACK_OK);
-
-    ret = CloneStringIfNonNull(&(savedPlatformInfo.operatingSystemVersion), info.operatingSystemVersion);
-    VERIFY_SUCCESS(ret, OC_STACK_OK);
-
-    ret = CloneStringIfNonNull(&(savedPlatformInfo.hardwareVersion), info.hardwareVersion);
-    VERIFY_SUCCESS(ret, OC_STACK_OK);
-
-    ret = CloneStringIfNonNull(&(savedPlatformInfo.firmwareVersion), info.firmwareVersion);
-    VERIFY_SUCCESS(ret, OC_STACK_OK);
-
-    ret = CloneStringIfNonNull(&(savedPlatformInfo.supportUrl), info.supportUrl);
-    VERIFY_SUCCESS(ret, OC_STACK_OK);
-
-    ret = CloneStringIfNonNull(&(savedPlatformInfo.systemTime), info.systemTime);
-    VERIFY_SUCCESS(ret, OC_STACK_OK);
+    savedPlatformInfo.platformID = OICStrdup(info.platformID);
+    savedPlatformInfo.manufacturerName = OICStrdup(info.manufacturerName);
+    savedPlatformInfo.manufacturerUrl = OICStrdup(info.manufacturerUrl);
+    savedPlatformInfo.modelNumber = OICStrdup(info.modelNumber);
+    savedPlatformInfo.dateOfManufacture = OICStrdup(info.dateOfManufacture);
+    savedPlatformInfo.platformVersion = OICStrdup(info.platformVersion);
+    savedPlatformInfo.operatingSystemVersion = OICStrdup(info.operatingSystemVersion);
+    savedPlatformInfo.hardwareVersion = OICStrdup(info.hardwareVersion);
+    savedPlatformInfo.firmwareVersion = OICStrdup(info.firmwareVersion);
+    savedPlatformInfo.supportUrl = OICStrdup(info.supportUrl);
+    savedPlatformInfo.systemTime = OICStrdup(info.systemTime);
+
+    if ((!savedPlatformInfo.platformID && info.platformID)||
+        (!savedPlatformInfo.manufacturerName && info.manufacturerName)||
+        (!savedPlatformInfo.manufacturerUrl && info.manufacturerUrl)||
+        (!savedPlatformInfo.modelNumber && info.modelNumber)||
+        (!savedPlatformInfo.dateOfManufacture && info.dateOfManufacture)||
+        (!savedPlatformInfo.platformVersion && info.platformVersion)||
+        (!savedPlatformInfo.operatingSystemVersion && info.operatingSystemVersion)||
+        (!savedPlatformInfo.hardwareVersion && info.hardwareVersion)||
+        (!savedPlatformInfo.firmwareVersion && info.firmwareVersion)||
+        (!savedPlatformInfo.supportUrl && info.supportUrl)||
+        (!savedPlatformInfo.systemTime && info.systemTime))
+    {
+        DeletePlatformInfo();
+        return OC_STACK_INVALID_PARAM;
+    }
 
     return OC_STACK_OK;
 
-    exit:
-        DeletePlatformInfo();
-        return ret;
-
 }
 
 OCStackResult SavePlatformInfo(OCPlatformInfo info)
@@ -1176,16 +1167,15 @@ void DeleteDeviceInfo()
 
 static OCStackResult DeepCopyDeviceInfo(OCDeviceInfo info)
 {
-    OCStackResult ret = OC_STACK_OK;
+    savedDeviceInfo.deviceName = OICStrdup(info.deviceName);
 
-    ret = CloneStringIfNonNull(&(savedDeviceInfo.deviceName), info.deviceName);
-    VERIFY_SUCCESS(ret, OC_STACK_OK);
+    if(!savedDeviceInfo.deviceName && info.deviceName)
+    {
+        DeleteDeviceInfo();
+        return OC_STACK_NO_MEMORY;
+    }
 
     return OC_STACK_OK;
-
-    exit:
-        DeleteDeviceInfo();
-        return ret;
 }
 
 OCStackResult SaveDeviceInfo(OCDeviceInfo info)
index 5a3bfc0..2abade8 100644 (file)
@@ -23,6 +23,7 @@
 #include "ocserverrequest.h"
 #include "ocresourcehandler.h"
 #include "oic_malloc.h"
+#include "oic_string.h"
 
 #include "cacommon.h"
 #include "cainterface.h"
@@ -271,8 +272,7 @@ OCStackResult AddServerRequest (OCServerRequest ** request, uint16_t coapID,
 
     if(query)
     {
-        strncpy((char*)serverRequest->query,
-                (const char*)query, sizeof(serverRequest->query) - 1);
+        OICStrcpy(serverRequest->query, sizeof(serverRequest->query), query);
     }
 
     if(rcvdVendorSpecificHeaderOptions)
@@ -282,10 +282,7 @@ OCStackResult AddServerRequest (OCServerRequest ** request, uint16_t coapID,
     }
     if(reqJSONPayload && reqTotalSize)
     {
-        // destination is at least 1 greater than the source, so a NULL always exists in the
-        // last character
-        strncpy((char*)serverRequest->reqJSONPayload,
-                (const char*)reqJSONPayload, reqTotalSize - 1);
+        OICStrcpy(serverRequest->reqJSONPayload, reqTotalSize, reqJSONPayload);
     }
     serverRequest->requestComplete = 0;
     if(requestToken)
@@ -304,8 +301,8 @@ OCStackResult AddServerRequest (OCServerRequest ** request, uint16_t coapID,
 
     if(resourceUrl)
     {
-        strncpy((char*)serverRequest->resourceUrl,
-                (const char*)resourceUrl, sizeof(serverRequest->resourceUrl) - 1);
+        OICStrcpy(serverRequest->resourceUrl, sizeof(serverRequest->resourceUrl),
+            resourceUrl);
     }
 
     if (addressInfo)
@@ -332,7 +329,8 @@ exit:
 /**
  * Form the OCEntityHandlerRequest struct that is passed to a resource's entity handler
  *
- * @param entityHandlerRequest - pointer to the OCEntityHandlerRequest struct that is created
+ * @param entityHandlerRequest - pointer to the OCEntityHandlerRequest struct that is created.
+ *                              Required to be zero-initialized before calling this function.
  * @param request          - request handle
  * @param method           - RESTful method
  * @param resource         - resource handle
@@ -360,17 +358,16 @@ OCStackResult FormOCEntityHandlerRequest(
 {
     if (entityHandlerRequest)
     {
-        memset(entityHandlerRequest, 0, sizeof(OCEntityHandlerRequest));
+        entityHandlerRequest->resource = (OCResourceHandle) resource;
         entityHandlerRequest->requestHandle = request;
         entityHandlerRequest->method = method;
-        entityHandlerRequest->resource = (OCResourceHandle) resource;
         entityHandlerRequest->query = queryBuf;
-        entityHandlerRequest->reqJSONPayload = bufReqPayload;
+        entityHandlerRequest->obsInfo.action = observeAction;
+        entityHandlerRequest->obsInfo.obsId = observeID;
         entityHandlerRequest->numRcvdVendorSpecificHeaderOptions = numVendorOptions;
         entityHandlerRequest->rcvdVendorSpecificHeaderOptions = vendorOptions;
+        entityHandlerRequest->reqJSONPayload = bufReqPayload;
 
-        entityHandlerRequest->obsInfo.action = observeAction;
-        entityHandlerRequest->obsInfo.obsId = observeID;
         return OC_STACK_OK;
     }
 
@@ -560,14 +557,15 @@ OCStackResult HandleSingleResponse(OCEntityHandlerResponse * ehResponse)
     char payload[MAX_RESPONSE_LENGTH + OC_JSON_PREFIX_LEN + OC_JSON_SUFFIX_LEN + 1] = {};
 
     // Put the JSON prefix and suffix around the payload
-    strcpy(payload, (const char *)OC_JSON_PREFIX);
+    OICStrcpy(payload, sizeof(payload), OC_JSON_PREFIX);
     if(ehResponse->payloadSize)
     {
-        strncat(payload, (const char *)ehResponse->payload,
-                       ehResponse->payloadSize < MAX_RESPONSE_LENGTH ?
-                       ehResponse->payloadSize : MAX_RESPONSE_LENGTH);
+        OICStrcatPartial(payload, sizeof(payload),
+            ehResponse->payload,
+            ehResponse->payloadSize < MAX_RESPONSE_LENGTH ?
+            ehResponse->payloadSize : MAX_RESPONSE_LENGTH);
     }
-    strcat(payload, (const char *)OC_JSON_SUFFIX);
+    OICStrcat(payload, sizeof(payload), OC_JSON_SUFFIX);
     responseInfo.info.payload = (CAPayload_t)payload;
 
     #ifdef WITH_PRESENCE
@@ -675,8 +673,11 @@ OCStackResult HandleAggregateResponse(OCEntityHandlerResponse * ehResponse)
         {
             OC_LOG(ERROR, TAG, PCF("There is room in response buffer"));
             // append
-            strncat((char *)serverResponse->payload,
-                    (char *)ehResponse->payload,
+            // allocated size of the payload is assumed, since a search of the code
+            // shows that it is OICCalloc'ed to this size in AddServerResponse above
+            OICStrcatPartial(serverResponse->payload,
+                    MAX_RESPONSE_LENGTH,
+                    ehResponse->payload,
                     serverResponse->remainingPayloadSize);
             OC_LOG_V(INFO, TAG, "Current aggregated response  ...%s", serverResponse->payload);
             serverResponse->remainingPayloadSize -= strlen((char *)ehResponse->payload);
@@ -694,7 +695,8 @@ OCStackResult HandleAggregateResponse(OCEntityHandlerResponse * ehResponse)
             else
             {
                 OC_LOG(INFO, TAG, PCF("More response fragments to come"));
-                strncat((char *)serverResponse->payload,
+                OICStrcatPartial(serverResponse->payload,
+                        MAX_RESPONSE_LENGTH,
                         OC_JSON_SEPARATOR_STR,
                         serverResponse->remainingPayloadSize);
                 OC_LOG_V(INFO, TAG, "Current aggregated response  ...%s", serverResponse->payload);
index 95a930a..cc0342c 100644 (file)
@@ -40,6 +40,7 @@
 #include "ocobserve.h"
 #include "ocrandom.h"
 #include "oic_malloc.h"
+#include "oic_string.h"
 #include "ocserverrequest.h"
 #include "secureresourcemanager.h"
 #include "cacommon.h"
@@ -451,33 +452,6 @@ uint32_t GetTicks(uint32_t afterMilliSeconds)
         return UINT32_MAX;
     }
 }
-/**
- * Clones a string IFF its pointer value is not NULL.
- *
- * Note: The caller to this function is responsible for calling @ref OICFree
- * for the destination parameter.
- *
- * @param dest The destination string for the string value to be cloned.
- *
- * @param src The source for the string value to be to cloned.
- */
-OCStackResult CloneStringIfNonNull(char **dest, const char *src)
-{
-    if (src)
-    {
-        *dest = (char*) OICMalloc(strlen(src) + 1);
-        if (!*dest)
-        {
-            return OC_STACK_NO_MEMORY;
-        }
-        strcpy(*dest, src);
-    }
-    else
-    {
-        *dest = NULL;
-    }
-    return OC_STACK_OK;
-}
 
 OCStackResult OCBuildIPv4Address(uint8_t a, uint8_t b, uint8_t c, uint8_t d,
         uint16_t port, OCDevAddr *ipAddr)
@@ -726,14 +700,12 @@ OCStackResult UpdateResponseAddr(OCDevAddr *address, const CARemoteEndpoint_t* e
     OCStackResult ret = OC_STACK_ERROR;
     char * tok = NULL;
     char * savePtr = NULL;
-    char * cpAddress = (char *) OICMalloc(strlen(endPoint->addressInfo.IP.ipAddress) + 1);
+    char* cpAddress = OICStrdup(endPoint->addressInfo.IP.ipAddress);
     if(!cpAddress)
     {
         ret = OC_STACK_NO_MEMORY;
         goto exit;
     }
-    memcpy(cpAddress, endPoint->addressInfo.IP.ipAddress,
-            strlen(endPoint->addressInfo.IP.ipAddress) + 1);
 
     // Grabs the first three numbers from the IPv4 address and replaces dots
     for(int i=0; i<4; i++)
@@ -858,7 +830,6 @@ void parsePresencePayload(char* payload, uint32_t* seqNum, uint32_t* maxAge,
     cJSON *maxAgeObj = NULL;
     cJSON *triggerObj = NULL;
     cJSON *resObj = NULL;
-    size_t size = 0;
     if(repObj)
     {
         ocObj = cJSON_GetObjectItem(repObj, OC_RSRVD_OC);
@@ -908,13 +879,11 @@ void parsePresencePayload(char* payload, uint32_t* seqNum, uint32_t* maxAge,
                         OC_RSRVD_RESOURCE_TYPE);
                 if(resObj)
                 {
-                    size = strlen(resObj->valuestring) + 1;
-                    *resType = (char *)OICMalloc(size);
+                    *resType = OICStrdup(resObj->valuestring);
                     if(!*resType)
                     {
                         goto exit;
                     }
-                    strncpy(*resType, resObj->valuestring, size);
                 }
                 else
                 {
@@ -966,7 +935,6 @@ static OCStackResult HandlePresenceResponse(const CARemoteEndpoint_t* endPoint,
     char *ipAddress = NULL;
     int presenceSubscribe = 0;
     int multicastPresenceSubscribe = 0;
-    size_t addressLen = 0;
 
     if (responseInfo->result != CA_SUCCESS)
     {
@@ -983,8 +951,7 @@ static OCStackResult HandlePresenceResponse(const CARemoteEndpoint_t* endPoint,
         goto exit;
     }
 
-    addressLen = strlen(endPoint->addressInfo.IP.ipAddress);
-    ipAddress = (char *) OICMalloc(addressLen + 1);
+    ipAddress = OICStrdup(endPoint->addressInfo.IP.ipAddress);
 
     if(!ipAddress)
     {
@@ -993,8 +960,6 @@ static OCStackResult HandlePresenceResponse(const CARemoteEndpoint_t* endPoint,
         goto exit;
     }
 
-    strncpy(ipAddress, endPoint->addressInfo.IP.ipAddress, addressLen);
-    ipAddress[addressLen] = '\0';
 
     snprintf(fullUri, MAX_URI_LENGTH, "coap://%s:%u%s", ipAddress, endPoint->addressInfo.IP.port,
                 OC_PRESENCE_URI);
@@ -1145,13 +1110,8 @@ static OCStackResult HandlePresenceResponse(const CARemoteEndpoint_t* endPoint,
         }
         else
         {
-            uint32_t uriLen = strlen(fullUri);
-            char* uri = (char *) OICMalloc(uriLen + 1);
-            if(uri)
-            {
-                memcpy(uri, fullUri, (uriLen + 1));
-            }
-            else
+            char* uri = OICStrdup(fullUri);
+            if(!uri)
             {
                 OC_LOG(ERROR, TAG,
                     PCF("No Memory for URI to store in the presence node"));
@@ -1516,7 +1476,8 @@ void HandleCARequests(const CARemoteEndpoint_t* endPoint, const CARequestInfo_t*
     if(strlen(newUri) < MAX_URI_LENGTH)
     {
         //copy URI
-        memcpy (&(serverRequest.resourceUrl), newUri, strlen(newUri));
+        OICStrcpy(serverRequest.resourceUrl, sizeof(serverRequest.resourceUrl),
+                    newUri);
         OICFree(newUri);
     }
     else
@@ -1531,7 +1492,7 @@ void HandleCARequests(const CARemoteEndpoint_t* endPoint, const CARequestInfo_t*
     {
         if(strlen(query) < MAX_QUERY_LENGTH)
         {
-            memcpy (&(serverRequest.query), query, strlen(query));
+            OICStrcpy(serverRequest.query, sizeof(serverRequest.query), query);
             OICFree(query);
         }
         else
@@ -1546,8 +1507,8 @@ void HandleCARequests(const CARemoteEndpoint_t* endPoint, const CARequestInfo_t*
     {
         size_t payloadLen = strlen(requestInfo->info.payload);
         serverRequest.reqTotalSize = payloadLen + 1;
-        memcpy (&(serverRequest.reqJSONPayload), requestInfo->info.payload,
-                payloadLen);
+        OICStrcpy(serverRequest.reqJSONPayload, sizeof(serverRequest.reqJSONPayload),
+                requestInfo->info.payload);
     }
     else
     {
@@ -2120,7 +2081,7 @@ OCStackResult OCDoResource(OCDoHandle *handle, OCMethod method, const char *requ
     requestUri = (char *) OICMalloc(uriLen + 1);
     if(requestUri)
     {
-        memcpy(requestUri, newUri, (uriLen + 1));
+        OICStrcpy(requestUri, uriLen + 1, newUri);
     }
     else
     {
@@ -2192,7 +2153,7 @@ OCStackResult OCDoResource(OCDoHandle *handle, OCMethod method, const char *requ
             CADestroyToken(token);
             goto exit;
         }
-        strncpy(grpEnd.resourceUri, requiredUri, (uriLen + 1));
+        OICStrcpy(grpEnd.resourceUri, uriLen +1, requiredUri);
 
         caResult = CASendRequestToAll(&grpEnd, &requestInfo);
     }
@@ -2559,7 +2520,8 @@ OCStackResult OCStartPresence(const uint32_t ttl)
         presenceState = OC_PRESENCE_INITIALIZED;
 
         CAAddress_t addressInfo;
-        strncpy(addressInfo.IP.ipAddress, OC_MULTICAST_IP, CA_IPADDR_SIZE);
+        OICStrcpy(addressInfo.IP.ipAddress, sizeof(addressInfo.IP.ipAddress),
+                OC_MULTICAST_IP);
         addressInfo.IP.port = OC_MULTICAST_PORT;
 
         CAToken_t caToken = NULL;
@@ -2665,7 +2627,6 @@ OCStackResult OCCreateResource(OCResourceHandle *handle,
 
     OCResource *pointer = NULL;
     char *str = NULL;
-    size_t size = 0;
     OCStackResult result = OC_STACK_ERROR;
 
     OC_LOG(INFO, TAG, PCF("Entering OCCreateResource"));
@@ -2728,14 +2689,12 @@ OCStackResult OCCreateResource(OCResourceHandle *handle,
     insertResource(pointer);
 
     // Set the uri
-    size = strlen(uri) + 1;
-    str = (char *) OICMalloc(size);
+    str = OICStrdup(uri);
     if (!str)
     {
         result = OC_STACK_NO_MEMORY;
         goto exit;
     }
-    strncpy(str, uri, size);
     pointer->uri = str;
 
     // Set properties.  Set OC_ACTIVE
@@ -2903,7 +2862,6 @@ OCStackResult BindResourceTypeToResource(OCResource* resource,
 {
     OCResourceType *pointer = NULL;
     char *str = NULL;
-    size_t size = 0;
     OCStackResult result = OC_STACK_ERROR;
 
     OC_LOG(INFO, TAG, PCF("Entering BindResourceTypeToResource"));
@@ -2922,14 +2880,12 @@ OCStackResult BindResourceTypeToResource(OCResource* resource,
     }
 
     // Set the resourceTypeName
-    size = strlen(resourceTypeName) + 1;
-    str = (char *) OICMalloc(size);
+    str = OICStrdup(resourceTypeName);
     if (!str)
     {
         result = OC_STACK_NO_MEMORY;
         goto exit;
     }
-    strncpy(str, resourceTypeName, size);
     pointer->resourcetypename = str;
 
     insertResourceType(resource, pointer);
@@ -2950,7 +2906,6 @@ OCStackResult BindResourceInterfaceToResource(OCResource* resource,
 {
     OCResourceInterface *pointer = NULL;
     char *str = NULL;
-    size_t size = 0;
     OCStackResult result = OC_STACK_ERROR;
 
     OC_LOG(INFO, TAG, PCF("Entering BindResourceInterfaceToResource"));
@@ -2969,14 +2924,12 @@ OCStackResult BindResourceInterfaceToResource(OCResource* resource,
     }
 
     // Set the resourceinterface name
-    size = strlen(resourceInterfaceName) + 1;
-    str = (char *) OICMalloc(size);
+    str = OICStrdup(resourceInterfaceName);
     if (!str)
     {
         result = OC_STACK_NO_MEMORY;
         goto exit;
     }
-    strncpy(str, resourceInterfaceName, size);
     pointer->name = str;
 
     // Bind the resourceinterface to the resource
@@ -3889,14 +3842,13 @@ OCStackResult getResourceType(const char * query, char** resourceType)
 
     if(strncmp(query, "rt=", 3) == 0)
     {
-        *resourceType = (char *) OICMalloc(strlen(query)-3 + 1);
+        *resourceType = OICStrdup(&query[3]);
         if(!*resourceType)
         {
             result = OC_STACK_NO_MEMORY;
         }
         else
         {
-            strcpy((char *)*resourceType, ((const char *)&query[3]));
             result = OC_STACK_OK;
         }
     }
@@ -3947,7 +3899,7 @@ OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithout
         {
             goto exit;
         }
-        strncpy(*uriWithoutQuery, uri, uriWithoutQueryLen);
+        OICStrcpy(*uriWithoutQuery, uriWithoutQueryLen +1, uri);
     }
     else
     {
@@ -3963,7 +3915,7 @@ OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithout
             *uriWithoutQuery = NULL;
             goto exit;
         }
-        strncpy(*query, pointerToDelimiter + 1, queryLen);
+        OICStrcpy(*query, queryLen + 1, pointerToDelimiter + 1);
     }
 
     return OC_STACK_OK;
index 7b2db2b..77df219 100644 (file)
@@ -19,6 +19,7 @@
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
 #include "oc_logger.h"
+#include "oic_string.h"
 
 #include <string.h>
 #include <stdlib.h>
@@ -149,7 +150,6 @@ size_t oc_log_write_level(oc_log_ctx_t *ctx, const oc_log_level loglevel, const
 int oc_log_set_module(oc_log_ctx_t *ctx, const char *module_name)
 {
  char *mn = NULL;
- size_t len = 0;
 
  if(!ctx || !module_name)
  {
@@ -157,17 +157,13 @@ int oc_log_set_module(oc_log_ctx_t *ctx, const char *module_name)
  }
 
  /* Swap pointers so that module data's not erased in the event of failure: */
- len = strlen(module_name);
-
- mn = (char *)malloc(1 + len);
+ mn = OICStrdup(module_name);
 
  if(!mn)
  {
      return 0;
  }
 
- memcpy(mn, module_name, 1 + len);
-
  if(!ctx->module_name)
  {
      free(ctx->module_name);
index 2fa231b..aa4991b 100644 (file)
@@ -827,11 +827,6 @@ namespace OC
                     it->getOptionID(),
                     it->getOptionData().length() + 1,
                     reinterpret_cast<const uint8_t*>(it->getOptionData().c_str()));
-            //options[i].protocolID = OC_COAP_ID;
-            //options[i].optionID = static_cast<uint16_t>(it->getOptionID());
-            //options[i].optionLength = (it->getOptionData()).length() + 1;
-            //memcpy(options[i].optionData, (it->getOptionData()).c_str(),
-            //        (it->getOptionData()).length() + 1);
             i++;
         }
 
index b1821f8..769de24 100644 (file)
@@ -528,11 +528,8 @@ namespace OC
         else
         {
             OCEntityHandlerResponse response;
-            std::string payLoad;
-            HeaderOptions serverHeaderOptions;
-
-            payLoad = pResponse->getPayload();
-            serverHeaderOptions = pResponse->getHeaderOptions();
+            std::string payLoad = pResponse->getPayload();
+            HeaderOptions serverHeaderOptions = pResponse->getHeaderOptions();
 
             response.requestHandle = pResponse->getRequestHandle();
             response.resourceHandle = pResponse->getResourceHandle();
@@ -545,7 +542,8 @@ namespace OC
                 throw OCException(OC::Exception::NO_MEMORY, OC_STACK_NO_MEMORY);
             }
 
-            strncpy(response.payload, payLoad.c_str(), payLoad.length()+1);
+            payLoad.copy(response.payload, payLoad.length());
+            response.payload[payLoad.length()] = '\0';
             response.payloadSize = payLoad.length() + 1;
             response.persistentBufferFlag = 0;
 
@@ -558,18 +556,19 @@ namespace OC
                     static_cast<uint16_t>(it->getOptionID());
                 response.sendVendorSpecificHeaderOptions[i].optionLength =
                     (it->getOptionData()).length() + 1;
-                memcpy(response.sendVendorSpecificHeaderOptions[i].optionData,
-                    (it->getOptionData()).c_str(),
-                    (it->getOptionData()).length() + 1);
+                std::copy(it->getOptionData().begin(),
+                         it->getOptionData().end(),
+                         response.sendVendorSpecificHeaderOptions[i].optionData);
+                response.sendVendorSpecificHeaderOptions[i].optionData[it->getOptionData().length()]
+                    = '\0';
                 i++;
             }
 
             if(OC_EH_RESOURCE_CREATED == response.ehResult)
             {
-                std::string createdUri = pResponse->getNewResourceUri();
-                strncpy(reinterpret_cast<char*>(response.resourceUri),
-                        createdUri.c_str(),
-                        createdUri.length() + 1);
+                pResponse->getNewResourceUri().copy(response.resourceUri,
+                        sizeof (response.resourceUri) - 1);
+                response.resourceUri[pResponse->getNewResourceUri().length()] = '\0';
             }
 
             if(cLock)