Merge master to cloud-interface branch 38/2238/2
authorhyuna0213.jo <hyuna0213.jo@samsung.com>
Wed, 19 Aug 2015 03:53:37 +0000 (12:53 +0900)
committerJon A. Cruz <jonc@osg.samsung.com>
Thu, 20 Aug 2015 03:27:23 +0000 (03:27 +0000)
merge master branch to use latest master code.

Change-Id: I57a2415e334c99755df87da5f97f28deb3ce5d76
Signed-off-by: hyuna0213.jo <hyuna0213.jo@samsung.com>
Reviewed-on: https://gerrit.iotivity.org/gerrit/2238
Reviewed-by: Jaehong Jo <jaehong.jo@samsung.com>
Reviewed-by: Jon A. Cruz <jonc@osg.samsung.com>
Tested-by: Jon A. Cruz <jonc@osg.samsung.com>
87 files changed:
android/BuildInstructionsForAndroidAPI.txt
android/android_api/SConscript
android/android_api/base/src/main/java/org/iotivity/base/OcPlatform.java
android/android_api/base/src/main/java/org/iotivity/ca/CaLeClientInterface.java
android/android_api/base/src/main/java/org/iotivity/ca/CaLeServerInterface.java
auto_build.sh
build_common/android/compatibility/c_compat.c
resource/c_common/platform_features.h
resource/csdk/connectivity/api/cacommon.h
resource/csdk/connectivity/api/cainterface.h
resource/csdk/connectivity/common/inc/uarraylist.h
resource/csdk/connectivity/common/src/caremotehandler.c
resource/csdk/connectivity/common/src/cathreadpool_pthreads.c
resource/csdk/connectivity/common/src/uarraylist.c
resource/csdk/connectivity/inc/caadapterinterface.h
resource/csdk/connectivity/inc/caadapternetdtls.h
resource/csdk/connectivity/inc/caipinterface.h
resource/csdk/connectivity/inc/camessagehandler.h
resource/csdk/connectivity/samples/android/casample/sampleService/src/main/jni/ResourceModel.c
resource/csdk/connectivity/src/adapter_util/caadapternetdtls.c
resource/csdk/connectivity/src/bt_edr_adapter/android/caedrutils.c
resource/csdk/connectivity/src/bt_edr_adapter/android/caedrutils.h
resource/csdk/connectivity/src/bt_edr_adapter/tizen/caedrendpoint.c
resource/csdk/connectivity/src/bt_edr_adapter/tizen/caedrnwmonitor.c
resource/csdk/connectivity/src/bt_le_adapter/android/caleclient.c
resource/csdk/connectivity/src/bt_le_adapter/android/caleclient.h
resource/csdk/connectivity/src/bt_le_adapter/android/caleserver.c
resource/csdk/connectivity/src/bt_le_adapter/android/caleserver.h
resource/csdk/connectivity/src/bt_le_adapter/caleadapter.c
resource/csdk/connectivity/src/bt_le_adapter/tizen/cableserver.c
resource/csdk/connectivity/src/cablockwisetransfer.c
resource/csdk/connectivity/src/cainterfacecontroller.c
resource/csdk/connectivity/src/camessagehandler.c
resource/csdk/connectivity/src/canetworkconfigurator.c
resource/csdk/connectivity/src/caprotocolmessage.c
resource/csdk/connectivity/src/ip_adapter/android/caipnwmonitor.c [changed mode: 0644->0755]
resource/csdk/connectivity/src/ip_adapter/arduino/caipnwmonitor_eth.cpp
resource/csdk/connectivity/src/ip_adapter/arduino/caipnwmonitor_wifi.cpp
resource/csdk/connectivity/src/ip_adapter/arduino/caipserver_eth.cpp
resource/csdk/connectivity/src/ip_adapter/arduino/caipserver_wifi.cpp
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/doc/CCF Lite GIT Repo Layout.docx [deleted file]
resource/csdk/security/src/secureresourcemanager.c
resource/csdk/stack/include/octypes.h
resource/csdk/stack/samples/arduino/SimpleClientServer/ocserver/SConscript
resource/csdk/stack/samples/linux/SimpleClientServer/occlient.cpp
resource/csdk/stack/samples/linux/SimpleClientServer/occlientbasicops.cpp
resource/csdk/stack/samples/linux/SimpleClientServer/occlientbasicops.h
resource/csdk/stack/samples/linux/SimpleClientServer/occlientcoll.cpp
resource/csdk/stack/samples/linux/SimpleClientServer/occlientslow.cpp
resource/csdk/stack/samples/linux/secure/occlientbasicops.cpp
resource/csdk/stack/src/ocpayloadconvert.c
resource/csdk/stack/src/ocpayloadparse.c
resource/csdk/stack/src/ocstack.c
resource/examples/simpleclient.cpp
resource/examples/simpleclientHQ.cpp
resource/src/OCRepresentation.cpp
resource/third_party_libs.scons
service/SConscript
service/notification-manager/NotificationManager/src/ResourceHosting.cpp
service/protocol-plugin/plugins/mqtt-light/lib/cpp/test.txt [deleted file]
service/resource-encapsulation/SConscript
service/resource-encapsulation/examples/linux/SampleResourceClient.cpp
service/resource-encapsulation/include/RCSDiscoveryManager.h
service/resource-encapsulation/include/RCSResourceAttributes.h
service/resource-encapsulation/include/RCSResourceObject.h
service/resource-encapsulation/src/common/SConscript
service/resource-encapsulation/src/common/primitiveResource/src/RCSResourceAttributes.cpp
service/resource-encapsulation/src/common/utils/include/AtomicHelper.h [new file with mode: 0644]
service/resource-encapsulation/src/resourceBroker/include/ResourcePresence.h
service/resource-encapsulation/src/resourceBroker/src/ResourcePresence.cpp
service/resource-encapsulation/src/resourceClient/RCSDiscoveryManager.cpp
service/resource-encapsulation/src/resourceContainer/SConscript
service/resource-encapsulation/src/resourceContainer/src/ResourceContainerImpl.cpp
service/resource-encapsulation/src/serverBuilder/SConscript
service/resource-encapsulation/src/serverBuilder/src/RCSResourceObject.cpp
service/resource-encapsulation/src/serverBuilder/unittests/RCSResourceObjectTest.cpp
service/resource-encapsulation/unittests/ResourceClientTest.cpp
service/soft-sensor-manager/SDK/java/org/iotivity/service/ssm/DataReader.java
service/soft-sensor-manager/SDK/java/org/iotivity/service/ssm/ModelData.java
service/soft-sensor-manager/SDK/java/org/iotivity/service/ssm/QueryEngine.java
service/soft-sensor-manager/SSMCore/src/SSMInterface/SSMCore_JNI.cpp
service/soft-sensor-manager/SSMCore/src/SSMInterface/SSMCore_JNI.h
service/third_party_libs.scons

index 1b0f239..a30df42 100644 (file)
@@ -10,11 +10,10 @@ Build Instructions for Android-API:
         def ndkBuild = new File(System.env.ANDROID_NDK_HOME, 'ndk-build.cmd')
 
 4.Build scons for android and your targeted architecture (This will also build Android API):
-    a.scons TARGET_OS=android TARGET_ARCH=<target arch> TARGET_TRANSPORT=IP RELEASE=1
-               where <target arch> can be armeabi, armeabi-v7a, x86.
+    a.scons TARGET_OS=android TARGET_ARCH=<target arch> TARGET_TRANSPORT=<target transport> RELEASE=1
+               where <target arch> can be armeabi, armeabi-v7a, x86, x86_64.
                Note: To build in debug mode, use RELEASE=0.
                Note: The minimum SDK version supported is 21.
-               Note: Only TARGET_TRANSPORT currently supported is IP
     b.If the project is setup correctly, you should see a BUILD SUCCESSFUL message on the terminal
     c.You should see the .aar files generated inside of '<iotivity>/android/android_api/base/build/outputs/aar' directory. The .aar files contain jni directory and also a .jar file
 
index 11983d7..5fba6e7 100644 (file)
@@ -43,6 +43,6 @@ if not os.path.exists(android_home + '/platforms/android-21') or not os.path.exi
     os.system(android_home + '/tools/android')
 
 jdk_env = Environment(ENV=os.environ)
-jdk_env['BUILDERS']['Gradle'] = Builder(action = env.get('ANDROID_GRADLE') + ' build -b' + os.getcwd()+'/build.gradle -PTARGET_ARCH=%s -PRELEASE=%s' %(ANDROID_TARGET_ARCH, ANDROID_RELEASE))
+jdk_env['BUILDERS']['Gradle'] = Builder(action = env.get('ANDROID_GRADLE') + ' build -b' + os.getcwd()+'/build.gradle -PTARGET_ARCH=%s -PRELEASE=%s --stacktrace' %(ANDROID_TARGET_ARCH, ANDROID_RELEASE))
 jdk_env.Gradle(target="base/objs", source="base/src/main/java/org/iotivity/base/OcResource.java")
 
index d042e9e..fc562be 100644 (file)
@@ -63,7 +63,7 @@ public final class OcPlatform {
      */
     public static final String GROUP_INTERFACE = "oic.mi.grp";
 
-    public static final String WELL_KNOWN_QUERY = "224.0.1.187:5683/oic/res";
+    public static final String WELL_KNOWN_QUERY = "/oic/res";
     public static final String MULTICAST_PREFIX = "224.0.1.187:5683";
     public static final String MULTICAST_IP = "224.0.1.187";
     public static final int MULTICAST_PORT = 5683;
index 891cb40..ef20573 100644 (file)
@@ -72,8 +72,7 @@ public class CaLeClientInterface {
     private native static void caLeRegisterGattCallback(BluetoothGattCallback callback);
 
     // BluetoothAdapter.LeScanCallback
-    private native static void caLeScanCallback(BluetoothDevice device,
-                                                int rssi, byte[] scanRecord);
+    private native static void caLeScanCallback(BluetoothDevice device);
 
     // BluetoothGattCallback
     private native static void caLeGattConnectionStateChangeCallback(
@@ -81,24 +80,13 @@ public class CaLeClientInterface {
 
     private native static void caLeGattServicesDiscoveredCallback(BluetoothGatt gatt, int status);
 
-    private native static void caLeGattCharacteristicReadCallback(
-            BluetoothGatt gatt, BluetoothGattCharacteristic characteristic,
-            byte[] data, int status);
-
     private native static void caLeGattCharacteristicWriteCallback(
-            BluetoothGatt gatt, BluetoothGattCharacteristic characteristic,
-            byte[] data, int status);
+            BluetoothGatt gatt, byte[] data, int status);
 
     private native static void caLeGattCharacteristicChangedCallback(
-            BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, byte[] data);
-
-    private native static void caLeGattDescriptorReadCallback(BluetoothGatt gatt,
-                                                             BluetoothGattDescriptor descriptor,
-                                                             int status);
+            BluetoothGatt gatt, byte[] data);
 
-    private native static void caLeGattDescriptorWriteCallback(BluetoothGatt gatt,
-                                                              BluetoothGattDescriptor descriptor,
-                                                              int status);
+    private native static void caLeGattDescriptorWriteCallback(BluetoothGatt gatt, int status);
 
     private native static void caLeGattReliableWriteCompletedCallback(BluetoothGatt gatt,
                                                                      int status);
@@ -125,7 +113,7 @@ public class CaLeClientInterface {
                     Log.d(TAG, "UUID : " + uuid.toString());
                     if(uuid.toString().contains(SERVICE_UUID.toLowerCase())) {
                         Log.d(TAG, "we found that has the Device");
-                        caLeScanCallback(device, rssi, scanRecord);
+                        caLeScanCallback(device);
                     }
                 }
             } catch(UnsatisfiedLinkError e) {
@@ -202,9 +190,6 @@ public class CaLeClientInterface {
         public void onCharacteristicRead(BluetoothGatt gatt,
                 BluetoothGattCharacteristic characteristic, int status) {
             super.onCharacteristicRead(gatt, characteristic, status);
-
-            caLeGattCharacteristicReadCallback(gatt, characteristic,
-                                               characteristic.getValue(), status);
         }
 
         @Override
@@ -212,8 +197,7 @@ public class CaLeClientInterface {
                 BluetoothGattCharacteristic characteristic, int status) {
             super.onCharacteristicWrite(gatt, characteristic, status);
 
-            caLeGattCharacteristicWriteCallback(gatt, characteristic,
-                                                characteristic.getValue(), status);
+            caLeGattCharacteristicWriteCallback(gatt, characteristic.getValue(), status);
         }
 
         @Override
@@ -221,16 +205,13 @@ public class CaLeClientInterface {
                 BluetoothGattCharacteristic characteristic) {
             super.onCharacteristicChanged(gatt, characteristic);
 
-            caLeGattCharacteristicChangedCallback(gatt, characteristic,
-                                                  characteristic.getValue());
+            caLeGattCharacteristicChangedCallback(gatt, characteristic.getValue());
         }
 
         @Override
         public void onDescriptorRead(BluetoothGatt gatt, BluetoothGattDescriptor descriptor,
                 int status) {
             super.onDescriptorRead(gatt, descriptor, status);
-
-            caLeGattDescriptorReadCallback(gatt, descriptor, status);
         }
 
         @Override
@@ -238,21 +219,17 @@ public class CaLeClientInterface {
                 int status) {
             super.onDescriptorWrite(gatt, descriptor, status);
 
-            caLeGattDescriptorWriteCallback(gatt, descriptor, status);
+            caLeGattDescriptorWriteCallback(gatt, status);
         }
 
         @Override
         public void onReliableWriteCompleted(BluetoothGatt gatt, int status) {
             super.onReliableWriteCompleted(gatt, status);
-
-            caLeGattReliableWriteCompletedCallback(gatt, status);
         }
 
         @Override
         public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {
             super.onReadRemoteRssi(gatt, rssi, status);
-
-            caLeGattReadRemoteRssiCallback(gatt, rssi, status);
         }
     };
 
@@ -293,3 +270,4 @@ public class CaLeClientInterface {
     };
 }
 
+
index 18ac49f..281beac 100644 (file)
@@ -56,23 +56,10 @@ public class CaLeServerInterface {
                                                                   BluetoothGattService service);
 
     private native static void caLeGattServerCharacteristicReadRequestCallback(
-            BluetoothDevice device,
-            int requestId, int offset, BluetoothGattCharacteristic characteristic, byte[] data);
+            BluetoothDevice device, byte[] data);
 
     private native static void caLeGattServerCharacteristicWriteRequestCallback(
-            BluetoothDevice device, int requestId,
-            BluetoothGattCharacteristic characteristic, byte[] data, boolean preparedWrite,
-            boolean responseNeeded, int offset, byte[] value);
-
-    private native static void caLeGattServerDescriptorReadRequestCallback(
-            BluetoothDevice device, int requestId, int offset, BluetoothGattDescriptor descriptor);
-
-    public native static void caLeGattServerDescriptorWriteRequestCallback(
-            BluetoothDevice device, int requestId, BluetoothGattDescriptor descriptor,
-            boolean preparedWrite, boolean responseNeeded, int offset, byte[] value);
-
-    private native static void caLeGattServerExecuteWriteCallback(BluetoothDevice device,
-                                                                 int requestId, boolean execute);
+            BluetoothDevice device, byte[] data);
 
     private native static void caLeGattServerNotificationSentCallback(BluetoothDevice device,
                                                                      int status);
@@ -107,9 +94,7 @@ public class CaLeServerInterface {
                 BluetoothGattCharacteristic characteristic) {
             super.onCharacteristicReadRequest(device, requestId, offset, characteristic);
 
-            caLeGattServerCharacteristicReadRequestCallback(device, requestId, offset,
-                                                            characteristic,
-                                                            characteristic.getValue());
+            caLeGattServerCharacteristicReadRequestCallback(device, characteristic.getValue());
         }
 
         @Override
@@ -119,9 +104,7 @@ public class CaLeServerInterface {
             super.onCharacteristicWriteRequest(device, requestId, characteristic,
                     preparedWrite, responseNeeded, offset, value);
 
-            caLeGattServerCharacteristicWriteRequestCallback(device, requestId, characteristic,
-                                                             value, preparedWrite, responseNeeded,
-                                                             offset, value);
+            caLeGattServerCharacteristicWriteRequestCallback(device, value);
         }
 
         @Override
@@ -129,8 +112,6 @@ public class CaLeServerInterface {
                 BluetoothDevice device,
                 int requestId, int offset, BluetoothGattDescriptor descriptor) {
             super.onDescriptorReadRequest(device, requestId, offset, descriptor);
-
-            caLeGattServerDescriptorReadRequestCallback(device, requestId, offset, descriptor);
         }
 
         @Override
@@ -140,17 +121,11 @@ public class CaLeServerInterface {
                 byte[] value) {
             super.onDescriptorWriteRequest(device, requestId, descriptor, preparedWrite,
                                            responseNeeded, offset, value);
-
-            caLeGattServerDescriptorWriteRequestCallback(device, requestId, descriptor,
-                                                         preparedWrite, responseNeeded, offset,
-                                                         value);
         }
 
         @Override
         public void onExecuteWrite(BluetoothDevice device, int requestId, boolean execute) {
             super.onExecuteWrite(device, requestId, execute);
-
-            caLeGattServerExecuteWriteCallback(device, requestId, execute);
         }
 
         @Override
index 568920e..750f641 100755 (executable)
@@ -69,9 +69,18 @@ function build_android()
 
        echo "*********** Build for android x86 *************"
        scons TARGET_OS=android TARGET_ARCH=x86 RELEASE=$1 TARGET_TRANSPORT=IP $2
+       scons TARGET_OS=android TARGET_ARCH=x86 RELEASE=$1 TARGET_TRANSPORT=BT $2
+       scons TARGET_OS=android TARGET_ARCH=x86 RELEASE=$1 TARGET_TRANSPORT=BLE $2
+
+       echo "*********** Build for android x86_64 *************"
+       scons TARGET_OS=android TARGET_ARCH=x86_64 RELEASE=$1 TARGET_TRANSPORT=IP $2
+       scons TARGET_OS=android TARGET_ARCH=x86_64 RELEASE=$1 TARGET_TRANSPORT=BT $2
+       scons TARGET_OS=android TARGET_ARCH=x86_64 RELEASE=$1 TARGET_TRANSPORT=BLE $2
 
        echo "*********** Build for android armeabi *************"
        scons TARGET_OS=android TARGET_ARCH=armeabi RELEASE=$1 TARGET_TRANSPORT=IP $2
+       scons TARGET_OS=android TARGET_ARCH=armeabi RELEASE=$1 TARGET_TRANSPORT=BT $2
+       scons TARGET_OS=android TARGET_ARCH=armeabi RELEASE=$1 TARGET_TRANSPORT=BLE $2
 
        # enable parallel build
        export SCONSFLAGS="-Q -j 4"
@@ -82,10 +91,12 @@ function build_arduino()
        echo "*********** Build for arduino avr *************"
        scons resource TARGET_OS=arduino UPLOAD=false BOARD=mega TARGET_ARCH=avr TARGET_TRANSPORT=IP SHIELD=ETH RELEASE=$1 $2
        scons resource TARGET_OS=arduino UPLOAD=false BOARD=mega TARGET_ARCH=avr TARGET_TRANSPORT=IP SHIELD=WIFI RELEASE=$1 $2
+       scons resource TARGET_OS=arduino UPLOAD=false BOARD=mega TARGET_ARCH=avr TARGET_TRANSPORT=BLE SHIELD=RBL_NRF8001 RELEASE=$1 $2
 
        echo "*********** Build for arduino arm *************"
        scons resource TARGET_OS=arduino UPLOAD=false BOARD=arduino_due_x TARGET_ARCH=arm TARGET_TRANSPORT=IP SHIELD=ETH RELEASE=$1 $2
        scons resource TARGET_OS=arduino UPLOAD=false BOARD=arduino_due_x TARGET_ARCH=arm TARGET_TRANSPORT=IP SHIELD=WIFI RELEASE=$1 $2
+       # BLE support for the Arduino Due is currently unavailable.
 }
 
 function build_tizen()
@@ -210,5 +221,3 @@ else
 fi
 
 echo "===================== done ====================="
-
-
index 000428a..b76c739 100644 (file)
@@ -45,16 +45,3 @@ void srandom(unsigned int __s)
 {
     srand48(__s);
 }
-
-/* from unistd.h */
-int getpagesize(void)
-{
-  extern unsigned int __page_size;
-  return __page_size;
-}
-
-int __getpageshift(void)
-{
-  extern unsigned int __page_shift;
-  return __page_shift;
-}
index 2fdaded..8f39e19 100644 (file)
     #define SUPPORTS_DEFAULT_CTOR
 #endif
 
+#if (__STDC_VERSION__ >= 201112L)
+    #include <stdassert.h>
+    #define OC_STATIC_ASSERT(condition, msg) static_assert(condition, msg)
+#else
+    #define OC_STATIC_ASSERT(condition, msg) ((void)sizeof(char[2*!!(condition) - 1]))
+#endif
+
 #endif
index b5beea1..cc261ce 100644 (file)
@@ -236,12 +236,20 @@ typedef struct
 {
     CATransportAdapter_t    adapter;    // adapter type
     CATransportFlags_t      flags;      // transport modifiers
+    uint16_t                port;       // for IP
     char                    addr[MAX_ADDR_STR_SIZE_CA]; // address for all
     uint32_t                interface;  // usually zero for default interface
-    uint16_t                port;       // for IP
-    CARemoteId_t identity;              // endpoint identity
 } CAEndpoint_t;
 
+/**
+ * Endpoint information for secure messages
+ */
+typedef struct
+{
+    CAEndpoint_t endpoint;      /**< endpoint */
+    CARemoteId_t identity;      /**< endpoint identity */
+} CASecureEndpoint_t;
+
 /**
  * @enum CAResult_t
  * Enums for CA return values
@@ -347,6 +355,7 @@ typedef struct
     CAPayload_t payload;        /**< payload of the request  */
     size_t payloadSize;         /**< size in bytes of the payload */
     CAURI_t resourceUri;        /**< Resource URI information **/
+    CARemoteId_t identity;      /**< endpoint identity */
 } CAInfo_t;
 
 /**
@@ -406,16 +415,38 @@ typedef struct
  */
 typedef struct
 {
-    int fd;
-    uint16_t port;
+    int fd;        /**< socket fd */
+    uint16_t port; /**< socket port */
 } CASocket_t;
 
+#define HISTORYSIZE (4)
+
+typedef struct
+{
+    CATransportFlags_t flags;
+    uint16_t messageId;
+} CAHistoryItem_t;
+
+typedef struct
+{
+    int nextIndex;
+    CAHistoryItem_t items[HISTORYSIZE];
+} CAHistory_t;
+
+/**
+ * Hold interface index for keeping track of comings and goings
+ */
+typedef struct
+{
+    int32_t ifIndex; /**< network interface index */
+} CAIfItem_t;
+
 typedef struct
 {
-    CATransportFlags_t clientFlags;
-    CATransportFlags_t serverFlags;
-    bool client;
-    bool server;
+    CATransportFlags_t clientFlags; /**< flag for client */
+    CATransportFlags_t serverFlags; /**< flag for server */
+    bool client; /**< client mode */
+    bool server; /**< server mode */
 
     struct sockets
     {
@@ -432,17 +463,26 @@ typedef struct
         int shutdownFds[2]; /**< shutdown pipe */
         int selectTimeout;  /**< in seconds */
         int maxfd;          /**< highest fd (for select) */
-        int numInterfaces;  /**< number of active interfaces */
         bool started;       /**< the IP adapter has started */
         bool terminate;     /**< the IP adapter needs to stop */
         bool ipv6enabled;   /**< IPv6 enabled by OCInit flags */
         bool ipv4enabled;   /**< IPv4 enabled by OCInit flags */
+        bool dualstack;     /**< IPv6 and IPv4 enabled */
+
+        struct networkmonitors
+        {
+            CAIfItem_t *ifItems; /**< current network interface index list */
+            size_t sizeIfItems;  /**< size of network interface index array */
+            size_t numIfItems;   /**< number of valid network interfaces */
+        } nm;
     } ip;
 
     struct calayer
     {
-        CATransportFlags_t previousRequestFlags; /**< address family filtering */
-        uint16_t previousRequestMessageId;       /**< address family filtering */
+        CAHistory_t requestHistory;  /**< filter IP family in requests */
+        CAHistory_t responseHistory; /**< filter IP family in responses */
+        CATransportFlags_t previousRequestFlags;/**< address family filtering */
+        uint16_t previousRequestMessageId;      /**< address family filtering */
     } ca;
 } CAGlobals_t;
 
index 27b4ff2..7449b28 100644 (file)
@@ -42,28 +42,25 @@ extern "C"
 #endif
 
 /**
- * @brief   Callback function type for request delivery.
- * @param   object      [OUT] Endpoint object from which the request is received. It contains
- *                            endpoint address based on the connectivity type.
- * @param   requestInfo [OUT] Info for resource model to understand about the request.
- * @return  NONE
+ * Callback function type for request delivery.
+ * @param[out]   object       Endpoint object from which the request is received.
+ *                            It contains endpoint address based on the connectivity type.
+ * @param[out]   requestInfo  Info for resource model to understand about the request.
  */
 typedef void (*CARequestCallback)(const CAEndpoint_t *object,
                                   const CARequestInfo_t *requestInfo);
 
 /**
- * @brief   Callback function type for response delivery.
- * @param   object          [OUT] Endpoint object from which the response is received.
- * @param   responseInfo    [OUT] Identifier which needs to be mapped with response.
- * @return  NONE
+ * Callback function type for response delivery.
+ * @param[out]   object           Endpoint object from which the response is received.
+ * @param[out]   responseInfo     Identifier which needs to be mapped with response.
  */
 typedef void (*CAResponseCallback)(const CAEndpoint_t *object,
                                    const CAResponseInfo_t *responseInfo);
 /**
- * @brief   Callback function type for error
- * @param   object          [OUT] remote device information
- * @param   errorInfo       [OUT] CA Error information
- * @return  NONE
+ * Callback function type for error.
+ * @param[out]   object           remote device information.
+ * @param[out]   errorInfo        CA Error information.
  */
 typedef void (*CAErrorCallback)(const CAEndpoint_t *object,
                                 const CAErrorInfo_t *errorInfo);
@@ -76,83 +73,80 @@ typedef void (*CAErrorCallback)(const CAEndpoint_t *object,
  */
 typedef struct
 {
-   unsigned char identity[DTLS_PSK_ID_LEN]; /** identity of self */
-   uint32_t num;                            /** number of credentials in this blob */
+   unsigned char identity[DTLS_PSK_ID_LEN]; /** identity of self. */
+   uint32_t num;                            /** number of credentials in this blob. */
    OCDtlsPskCreds *creds;                   /** list of credentials. Size of this
                                                 array is determined by 'num' variable. */
 } CADtlsPskCredsBlob_t;
 
 /**
- * @brief   Callback function type for getting DTLS credentials.
- * @param   credInfo          [OUT] DTLS credentials info. Handler has to allocate new memory for
- *                                  both credInfo and credInfo->creds which is then freed by CA
- * @return  NONE
+ * Callback function type for getting DTLS credentials.
+ * @param[out]   credInfo     DTLS credentials info. Handler has to allocate new memory for.
+ *                            both credInfo and credInfo->creds which is then freed by CA.
  */
 typedef void (*CAGetDTLSCredentialsHandler)(CADtlsPskCredsBlob_t **credInfo);
 #endif //__WITH_DTLS__
 
 /**
- * @brief   Initialize the connectivity abstraction module.
- *          It will initialize adapters, thread pool and other modules based on the platform
- *          compilation options.
+ * Initialize the connectivity abstraction module.
+ * It will initialize adapters, thread pool and other modules based on the platform
+ * compilation options.
  *
- * @return  #CA_STATUS_OK or #CA_STATUS_FAILED or #CA_MEMORY_ALLOC_FAILED
+ * @return  ::CA_STATUS_OK or ::CA_STATUS_FAILED or ::CA_MEMORY_ALLOC_FAILED
  */
 CAResult_t CAInitialize();
 
 /**
- * @brief   Terminate the connectivity abstraction module.
- *          All threads, data structures are destroyed for next initializations.
- * @return  NONE
+ * Terminate the connectivity abstraction module.
+ * All threads, data structures are destroyed for next initializations.
  */
 void CATerminate();
 
 /**
- * @brief   Starts listening servers.
- *          This API is used by resource hosting server for listening multicast requests.
- *          Based on the adapters configurations, different kinds of servers are started.
- * @return  #CA_STATUS_OK or #CA_STATUS_FAILED
+ * Starts listening servers.
+ * This API is used by resource hosting server for listening multicast requests.
+ * Based on the adapters configurations, different kinds of servers are started.
+ * @return  ::CA_STATUS_OK or ::CA_STATUS_FAILED
  */
 CAResult_t CAStartListeningServer();
 
 /**
- * @brief   Starts discovery servers.
- *          This API is used by resource required clients for listening multicast requests.
- *          Based on the adapters configurations, different kinds of servers are started.
- * @return  #CA_STATUS_OK or #CA_STATUS_FAILED
+ * Starts discovery servers.
+ * This API is used by resource required clients for listening multicast requests.
+ * Based on the adapters configurations, different kinds of servers are started.
+ * @return  ::CA_STATUS_OK or ::CA_STATUS_FAILED
  */
 CAResult_t CAStartDiscoveryServer();
 
 /**
- * @brief   Register request callbacks and response callbacks.
- *          Requests and responses are delivered these callbacks .
- * @param   ReqHandler   [IN] Request callback ( for GET,PUT ..etc)
- * @param   RespHandler  [IN] Response Handler Callback
+ * Register request callbacks and response callbacks.
+ *          Requests and responses are delivered these callbacks.
+ * @param[in]   ReqHandler    Request callback ( for GET,PUT ..etc).
+ * @param[in]   RespHandler   Response Handler Callback.
  * @see     CARequestCallback
  * @see     CAResponseCallback
  * @see     CAErrorCallback
- * @return  NONE
  */
 void CARegisterHandler(CARequestCallback ReqHandler, CAResponseCallback RespHandler,
                        CAErrorCallback ErrorHandler);
 
 #ifdef __WITH_DTLS__
 /**
- * @brief   Register callback to get DTLS PSK credentials.
- * @param   GetDTLSCredentials   [IN] GetDTLS Credetials callback
- * @return  #CA_STATUS_OK
+ * Register callback to get DTLS PSK credentials.
+ * @param[in]   GetDTLSCredentials    GetDTLS Credetials callback.
+ * @return  ::CA_STATUS_OK
  */
 CAResult_t CARegisterDTLSCredentialsHandler(CAGetDTLSCredentialsHandler GetDTLSCredentials);
 #endif //__WITH_DTLS__
 
 /**
- * @brief   Create an endpoint description
- * @param   flags               [IN]  how the adapter should be used
- * @param   adapter             [IN]  which adapter to use
- * @param   addr                [IN]  string representation of address
- * @param   port                [IN]  port (for IP_ADAPTER)
- * @param   endpoint            [OUT] Endpoint which contains the above
- * @return  #CA_STATUS_OK or #CA_STATUS_FAILED
+ * Create an endpoint description.
+ * @param[in]   flags                 how the adapter should be used.
+ * @param[in]   adapter               which adapter to use.
+ * @param[in]   addr                  string representation of address.
+ * @param[in]   port                  port (for IP_ADAPTER).
+ * @param[in]   endpoint              Endpoint which contains the above.
+ * @return  ::CA_STATUS_OK or ::CA_STATUS_FAILED
  * @remark  The created Remote endpoint can be freed using CADestroyEndpoint().
  * @see     CADestroyEndpoint
  */
@@ -163,94 +157,93 @@ CAResult_t CACreateEndpoint(CATransportFlags_t flags,
                             CAEndpoint_t **object);
 
 /**
- * @brief   Destroy the remote endpoint created
- * @param   object  [IN] Remote Endpoint object created with CACreateEndpoint
- * @return  NONE
+ * Destroy the remote endpoint created.
+ * @param[in]   object   Remote Endpoint object created with CACreateEndpoint.
  */
 void CADestroyEndpoint(CAEndpoint_t *object);
 
 /**
- * @brief   Generating the token for matching the request and response.
- * @param   token          [OUT] Token for the request
- * @param   tokenLength    [IN]  length of the token
- * @return  #CA_STATUS_OK or #CA_STATUS_FAILED or #CA_MEMORY_ALLOC_FAILED
- *          or #CA_STATUS_NOT_INITIALIZED
+ * Generating the token for matching the request and response.
+ * @param[in]   token            Token for the request.
+ * @param[in]   tokenLength      length of the token.
+ * @return  ::CA_STATUS_OK or ::CA_STATUS_FAILED or
+ *          ::CA_MEMORY_ALLOC_FAILED or ::CA_STATUS_NOT_INITIALIZED
  * @remark  Token memory is destroyed by the caller using CADestroyToken().
  * @see     CADestroyToken
  */
 CAResult_t CAGenerateToken(CAToken_t *token, uint8_t tokenLength);
 
 /**
- * @brief   Destroy the token generated by CAGenerateToken
- * @param   token   [IN] token to be freed
- * @return  NONE
+ * Destroy the token generated by CAGenerateToken.
+ * @param[in]   token    token to be freed.
  */
 void CADestroyToken(CAToken_t token);
 
 /**
- * @brief   Send control Request on a resource
- * @param   object      [IN] Endpoint where the payload need to be sent.
+ * Send control Request on a resource.
+ * @param[in]   object       Endpoint where the payload need to be sent.
  *                           This endpoint is delivered with Request or response callback.
- * @param   requestInfo [IN] Information for the request.
- * @return  #CA_STATUS_OK #CA_STATUS_FAILED #CA_MEMORY_ALLOC_FAILED
+ * @param[in]   requestInfo  Information for the request.
+ * @return  ::CA_STATUS_OK ::CA_STATUS_FAILED ::CA_MEMORY_ALLOC_FAILED
  */
 CAResult_t CASendRequest(const CAEndpoint_t *object, const CARequestInfo_t *requestInfo);
 
 /**
- * @brief   Send the response
- * @param   object          [IN] Endpoint where the payload need to be sent.
- *                               This endpoint is delivered with Request or response callback
- * @param   responseInfo    [IN] Information for the response
- * @return  #CA_STATUS_OK or  #CA_STATUS_FAILED or #CA_MEMORY_ALLOC_FAILED
+ * Send the response.
+ * @param[in]   object           Endpoint where the payload need to be sent.
+ *                               This endpoint is delivered with Request or response callback.
+ * @param[in]   responseInfo     Information for the response.
+ * @return  ::CA_STATUS_OK or  ::CA_STATUS_FAILED or ::CA_MEMORY_ALLOC_FAILED
  */
 CAResult_t CASendResponse(const CAEndpoint_t *object, const CAResponseInfo_t *responseInfo);
 
 /**
- * @brief   Send notification to the remote object
- * @param   object          [IN] Endpoint where the payload need to be sent.
+ * Send notification to the remote object.
+ * @param[in]   object           Endpoint where the payload need to be sent.
  *                               This endpoint is delivered with Request or response callback.
- * @param   responseInfo    [IN] Information for the response.
- * @return  #CA_STATUS_OK or #CA_STATUS_FAILED or #CA_MEMORY_ALLOC_FAILED
+ * @param[in]   responseInfo     Information for the response.
+ * @return  ::CA_STATUS_OK or ::CA_STATUS_FAILED or ::CA_MEMORY_ALLOC_FAILED
  */
 CAResult_t CASendNotification(const CAEndpoint_t *object,
                       const  CAResponseInfo_t *responseInfo);
 
 /**
- * @brief   Select network to use
- * @param   interestedNetwork   [IN] Connectivity Type enum
- * @return  #CA_STATUS_OK or #CA_NOT_SUPPORTED or #CA_STATUS_FAILED or #CA_NOT_SUPPORTED
+ * Select network to use.
+ * @param[in]   interestedNetwork    Connectivity Type enum.
+ * @return  ::CA_STATUS_OK or ::CA_NOT_SUPPORTED or
+ *          ::CA_STATUS_FAILED or ::CA_NOT_SUPPORTED
  */
 CAResult_t CASelectNetwork(CATransportAdapter_t interestedNetwork);
 
 /**
- * @brief   Select network to unuse
- * @param   nonInterestedNetwork    [IN] Connectivity Type enum
- * @return  #CA_STATUS_OK or #CA_NOT_SUPPORTED or #CA_STATUS_FAILED
+ * Select network to unuse.
+ * @param[in]   nonInterestedNetwork     Connectivity Type enum.
+ * @return  ::CA_STATUS_OK or ::CA_NOT_SUPPORTED or ::CA_STATUS_FAILED
  */
 CAResult_t CAUnSelectNetwork(CATransportAdapter_t nonInterestedNetwork);
 
 /**
- * @brief   Get network information
- *          It should be destroyed by the caller as it Get Information.
- * @param   info    [OUT] LocalConnectivity objects
- * @param   size    [OUT] No Of Array objects
- * @return  #CA_STATUS_OK or #CA_STATUS_FAILED or #CA_STATUS_INVALID_PARAM or
-*                #CA_MEMORY_ALLOC_FAILED
+ * Get network information.
+ * It should be destroyed by the caller as it Get Information.
+ * @param[out]   info     LocalConnectivity objects
+ * @param[out]   size     No Of Array objects
+ * @return  ::CA_STATUS_OK or ::CA_STATUS_FAILED or
+ *          ::CA_STATUS_INVALID_PARAM or ::CA_MEMORY_ALLOC_FAILED
  */
 CAResult_t CAGetNetworkInformation(CAEndpoint_t **info, uint32_t *size);
 
 /**
- * @brief    To Handle the Request or Response
- * @return   #CA_STATUS_OK
+ * To Handle the Request or Response.
+ * @return   ::CA_STATUS_OK
  */
 CAResult_t CAHandleRequestResponse();
 
 #ifdef RA_ADAPTER
 /**
- * @brief   Set Remote Access information for XMPP Client.
- * @param   caraInfo          [IN] remote access info.
+ * Set Remote Access information for XMPP Client.
+ * @param[in]   caraInfo          remote access info.
  *
- * @return  #CA_STATUS_OK
+ * @return  ::CA_STATUS_OK
  */
 CAResult_t CASetRAInfo(const CARAInfo_t *caraInfo);
 #endif
@@ -259,26 +252,26 @@ CAResult_t CASetRAInfo(const CARAInfo_t *caraInfo);
 #ifdef __WITH_DTLS__
 
 /**
- * Select the cipher suite for dtls handshake
+ * Select the cipher suite for dtls handshake.
  *
- * @param[IN] cipher  cipher suite (Note : Make sure endianness)
- *                               0xC018 : TLS_ECDH_anon_WITH_AES_128_CBC_SHA
- *                               0xC0A8 : TLS_PSK_WITH_AES_128_CCM_8
- *                               0xC0AE : TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8
+ * @param[in] cipher  cipher suite (Note : Make sure endianness).
+ *                    0xC018 : TLS_ECDH_anon_WITH_AES_128_CBC_SHA
+ *                    0xC0A8 : TLS_PSK_WITH_AES_128_CCM_8
+ *                    0xC0AE : TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8
  *
- * @retval  CA_STATUS_OK    Successful
- * @retval  CA_STATUS_INVALID_PARAM  Invalid input argumets
- * @retval  CA_STATUS_FAILED Operation failed
+ * @retval  ::CA_STATUS_OK    Successful.
+ * @retval  ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
+ * @retval  ::CA_STATUS_FAILED Operation failed.
  */
 CAResult_t CASelectCipherSuite(const uint16_t cipher);
 
 /**
- * Enable TLS_ECDH_anon_WITH_AES_128_CBC_SHA cipher suite in dtls
+ * Enable TLS_ECDH_anon_WITH_AES_128_CBC_SHA cipher suite in dtls.
  *
- * @param[IN] enable  TRUE/FALSE enables/disables anonymous cipher suite
+ * @param[in] enable  TRUE/FALSE enables/disables anonymous cipher suite.
  *
- * @retval  CA_STATUS_OK    Successful
- * @retval  CA_STATUS_FAILED Operation failed
+ * @retval  ::CA_STATUS_OK    Successful.
+ * @retval  ::CA_STATUS_FAILED Operation failed.
  *
  * @note anonymous cipher suite should only be enabled for 'JustWorks' provisioning.
  */
@@ -286,23 +279,23 @@ CAResult_t CAEnableAnonECDHCipherSuite(const bool enable);
 
 
 /**
- * Generate ownerPSK using PRF
+ * Generate ownerPSK using PRF.
  * OwnerPSK = TLS-PRF('master key' , 'oic.sec.doxm.jw',
- *                                    'ID of new device(Resource Server)',
- *                                    'ID of owner smart-phone(Provisioning Server)')
+ *                    'ID of new device(Resource Server)',
+ *                    'ID of owner smart-phone(Provisioning Server)')
  *
- * @param[IN] endpoint  information of network address
- * @param[IN] label  Ownership transfer method e.g)"oic.sec.doxm.jw"
- * @param[IN] labelLen  Byte length of label
- * @param[IN] rsrcServerDeviceID  ID of new device(Resource Server)
- * @param[IN] rsrcServerDeviceIDLen  Byte length of rsrcServerDeviceID
- * @param[IN] provServerDeviceID  label of previous owner
- * @param[IN] provServerDeviceIDLen  byte length of provServerDeviceID
- * @param[IN,OUT] ownerPSK  Output buffer for owner PSK
- * @param[IN] ownerPSKSize  Byte length of the ownerPSK to be generated
+ * @param[in] endpoint  information of network address.
+ * @param[in] label  Ownership transfer method e.g)"oic.sec.doxm.jw".
+ * @param[in] labelLen  Byte length of label.
+ * @param[in] rsrcServerDeviceID  ID of new device(Resource Server).
+ * @param[in] rsrcServerDeviceIDLen  Byte length of rsrcServerDeviceID.
+ * @param[in] provServerDeviceID  label of previous owner.
+ * @param[in] provServerDeviceIDLen  byte length of provServerDeviceID.
+ * @param[in,out] ownerPSK  Output buffer for owner PSK.
+ * @param[in] ownerPSKSize  Byte length of the ownerPSK to be generated.
  *
- * @retval  CA_STATUS_OK    Successful
- * @retval  CA_STATUS_FAILED Operation failed
+ * @retval  ::CA_STATUS_OK    Successful.
+ * @retval  ::CA_STATUS_FAILED Operation failed.
  */
 CAResult_t CAGenerateOwnerPSK(const CAEndpoint_t *endpoint,
                               const uint8_t* label, const size_t labelLen,
@@ -313,22 +306,22 @@ CAResult_t CAGenerateOwnerPSK(const CAEndpoint_t *endpoint,
                               uint8_t* ownerPSK, const size_t ownerPSKSize);
 
 /**
- * Initiate DTLS handshake with selected cipher suite
+ * Initiate DTLS handshake with selected cipher suite.
  *
- * @param[IN] endpoint  information of network address
+ * @param[in] endpoint  information of network address.
  *
- * @retval  CA_STATUS_OK    Successful
- * @retval  CA_STATUS_FAILED Operation failed
+ * @retval  ::CA_STATUS_OK    Successful.
+ * @retval  ::CA_STATUS_FAILED Operation failed.
  */
 CAResult_t CAInitiateHandshake(const CAEndpoint_t *endpoint);
 
 /**
- * Close the DTLS session
+ * Close the DTLS session.
  *
- * @param[IN] endpoint  information of network address
+ * @param[in] endpoint  information of network address.
  *
- * @retval  CA_STATUS_OK    Successful
- * @retval  CA_STATUS_FAILED Operation failed
+ * @retval  ::CA_STATUS_OK    Successful.
+ * @retval  ::CA_STATUS_FAILED Operation failed.
  */
 CAResult_t CACloseDtlsSession(const CAEndpoint_t *endpoint);
 
index a055a1b..7e8403a 100644 (file)
@@ -22,7 +22,7 @@
 #define U_ARRAYLIST_H_
 
 #include <stdint.h>
-#include "cacommon.h"
+#include <stdbool.h>
 
 #ifdef __cplusplus
 extern "C"
@@ -31,6 +31,10 @@ extern "C"
 
 /**
  * array list structure.
+ *
+ * @note
+ * Members should be treated as private and not accessed directly. Instead
+ * all access should be through the defined u_arraylist_*() functions.
  */
 typedef struct u_arraylist_t
 {
@@ -50,10 +54,8 @@ u_arraylist_t *u_arraylist_create();
  * Arraylist elements are deleted. Calling function must take care of free
  * dynamic memory allocated before freeing the arraylist.
  * @param[in] list       u_arraylist pointer
- * @return ::CAResult_t.
- * ::CA_STATUS_OK if Success, ::CA_STATUS_INVALID_PARAM if pointer to list is NULL.
  */
-CAResult_t u_arraylist_free(u_arraylist_t **list);
+void u_arraylist_free(u_arraylist_t **list);
 
 /**
  * Returns the data of the index from the array list.
@@ -67,10 +69,9 @@ void *u_arraylist_get(const u_arraylist_t *list, uint32_t index);
  * Add data in the array list.
  * @param[in] list        pointer of array list.
  * @param[in] data        pointer of data.
- * @return CAResult_t.
- * ::CA_STATUS_OK if Success, ::CA_MEMORY_ALLOC_FAILED if memory allocation fails.
+ * @return true if success, false otherwise.
  */
-CAResult_t u_arraylist_add(u_arraylist_t *list, void *data);
+bool u_arraylist_add(u_arraylist_t *list, void *data);
 
 /**
  * Remove the data of the index from the array list.
index 48e5f56..cca8bd8 100644 (file)
@@ -63,94 +63,16 @@ CARequestInfo_t *CACloneRequestInfo(const CARequestInfo_t *rep)
         return NULL;
     }
 
-    *clone = *rep;
-
-    if (rep->info.token)
-    {
-        char *temp = NULL;
-
-        // allocate token field
-        uint8_t len = rep->info.tokenLength;
-
-        if (len)
-        {
-            temp = (char *) OICCalloc(len, sizeof(char));
-            if (!temp)
-            {
-                OIC_LOG(ERROR, TAG, "CACloneRequestInfo Out of memory");
-
-                CADestroyRequestInfoInternal(clone);
-
-                return NULL;
-            }
-            memcpy(temp, rep->info.token, len);
-        }
-
-        // save the token
-        clone->info.token = temp;
-        clone->info.tokenLength = len;
-    }
-
-    if (NULL != rep->info.options && 0 < rep->info.numOptions)
-    {
-        // save the options
-        clone->info.options =
-            (CAHeaderOption_t *) OICMalloc(sizeof(CAHeaderOption_t) * rep->info.numOptions);
-        if (NULL == clone->info.options)
-        {
-            OIC_LOG(ERROR, TAG, "CACloneRequestInfo Out of memory");
-            OICFree(clone->info.token);
-            OICFree(clone);
-            return NULL;
-        }
-        memcpy(clone->info.options, rep->info.options,
-               sizeof(CAHeaderOption_t) * rep->info.numOptions);
-    }
-    else
-    {
-        clone->info.options = NULL;
-        clone->info.numOptions = 0;
-    }
-
-    if (NULL != rep->info.payload && 0 < rep->info.payloadSize)
+    CAResult_t result = CACloneInfo(&rep->info, &clone->info);
+    if(CA_STATUS_OK != result)
     {
-        // allocate payload field
-        uint8_t *temp = OICMalloc(rep->info.payloadSize);
-        if (NULL == temp)
-        {
-            OIC_LOG(ERROR, TAG, "CACloneRequestInfo Out of memory");
-
-            CADestroyRequestInfoInternal(clone);
-
-            return NULL;
-        }
-        memcpy(temp, rep->info.payload, rep->info.payloadSize);
-
-        // save the payload
-        clone->info.payload = temp;
-    }
-    else
-    {
-        clone->info.payload = NULL;
-        clone->info.payloadSize = 0;
+        OIC_LOG(ERROR, TAG, "CACloneRequestInfo error in CACloneInfo");
+        CADestroyRequestInfoInternal(clone);
+        return NULL;
     }
 
-    if (NULL != rep->info.resourceUri)
-    {
-        // allocate payload field
-        char *temp = OICStrdup(rep->info.resourceUri);
-        if (NULL == temp)
-        {
-            OIC_LOG(ERROR, TAG, "CACloneRequestInfo Out of memory");
-
-            CADestroyRequestInfoInternal(clone);
-
-            return NULL;
-        }
-
-        // save the resourceUri
-        clone->info.resourceUri = temp;
-    }
+    clone->method = rep->method;
+    clone->isMulticast = rep->isMulticast;
 
     return clone;
 }
@@ -198,96 +120,16 @@ CAResponseInfo_t *CACloneResponseInfo(const CAResponseInfo_t *rep)
         OIC_LOG(ERROR, TAG, "CACloneResponseInfo Out of memory");
         return NULL;
     }
-    *clone = *rep;
 
-    if (rep->info.token)
+    CAResult_t result = CACloneInfo(&rep->info, &clone->info);
+    if(CA_STATUS_OK != result)
     {
-        char *temp = NULL;
-
-        // allocate token field
-        uint8_t len = rep->info.tokenLength;
-
-        if (len)
-        {
-            temp = (char *) OICCalloc(len, sizeof(char));
-            if (!temp)
-            {
-                OIC_LOG(ERROR, TAG, "CACloneResponseInfo Out of memory");
-
-                CADestroyResponseInfoInternal(clone);
-
-                return NULL;
-            }
-            memcpy(temp, rep->info.token, len);
-        }
-        // save the token
-        clone->info.token = temp;
-        clone->info.tokenLength = len;
-    }
-
-    if (NULL != rep->info.options && rep->info.numOptions)
-    {
-        // save the options
-        clone->info.options =
-                (CAHeaderOption_t *) OICMalloc(sizeof(CAHeaderOption_t) * rep->info.numOptions);
-
-        if (NULL == clone->info.options)
-        {
-            OIC_LOG(ERROR, TAG, "CACloneResponseInfo Out of memory");
-
-            OICFree(clone->info.token);
-            OICFree(clone);
-            return NULL;
-        }
-        memcpy(clone->info.options, rep->info.options,
-                sizeof(CAHeaderOption_t) * rep->info.numOptions);
-    }
-    else
-    {
-        clone->info.options = NULL;
-        clone->info.numOptions = 0;
-    }
-
-    if (NULL != rep->info.payload && 0 < rep->info.payloadSize)
-    {
-        // allocate payload field
-        uint8_t *temp = (uint8_t *) OICMalloc(rep->info.payloadSize);
-        if (NULL == temp)
-        {
-            OIC_LOG(ERROR, TAG, "CACloneResponseInfo Out of memory");
-
-            CADestroyResponseInfoInternal(clone);
-
-            return NULL;
-        }
-        memcpy(temp, rep->info.payload, rep->info.payloadSize);
-
-        // save the payload
-        clone->info.payload = temp;
-    }
-    else
-    {
-        clone->info.payload = NULL;
-        clone->info.payloadSize = 0;
-    }
-
-    if (NULL != rep->info.resourceUri)
-    {
-        // allocate payload field
-        char *temp = OICStrdup(rep->info.resourceUri);
-        if (NULL == temp)
-        {
-            OIC_LOG(ERROR, TAG, "CACloneResponseInfo Out of memory");
-
-            CADestroyResponseInfoInternal(clone);
-
-            return NULL;
-        }
-
-        // save the resourceUri
-        clone->info.resourceUri = temp;
+        OIC_LOG(ERROR, TAG, "CACloneResponseInfo error in CACloneInfo");
+        CADestroyResponseInfoInternal(clone);
+        return NULL;
     }
 
+    clone->result = rep->result;
     return clone;
 }
 
@@ -386,6 +228,8 @@ CAResult_t CACloneInfo(const CAInfo_t *info, CAInfo_t *clone)
         return CA_STATUS_INVALID_PARAM;
     }
 
+    memset(clone, 0 , sizeof(CAInfo_t));
+
     //Do not free clone. we cannot declare it const, as the content is modified
     if ((info->token) && (0 < info->tokenLength))
     {
@@ -397,7 +241,7 @@ CAResult_t CACloneInfo(const CAInfo_t *info, CAInfo_t *clone)
         temp = (char *) OICMalloc(len * sizeof(char));
         if (!temp)
         {
-            OIC_LOG(ERROR, TAG, "CAClonePayloadInfo Out of memory");
+            OIC_LOG(ERROR, TAG, "CACloneInfo Out of memory");
             return CA_MEMORY_ALLOC_FAILED;
         }
 
@@ -415,20 +259,21 @@ CAResult_t CACloneInfo(const CAInfo_t *info, CAInfo_t *clone)
 
         if (!clone->options)
         {
-            OIC_LOG(ERROR, TAG, "CAClonePayloadInfo Out of memory");
+            OIC_LOG(ERROR, TAG, "CACloneInfo Out of memory");
             CADestroyInfoInternal(clone);
             return CA_MEMORY_ALLOC_FAILED;
         }
         memcpy(clone->options, info->options, sizeof(CAHeaderOption_t) * info->numOptions);
+        clone->numOptions = info->numOptions;
     }
 
-    if (info->payload && 0 < info->payloadSize)
+    if ((info->payload) && (0 < info->payloadSize))
     {
         // allocate payload field
         uint8_t *temp = OICMalloc(info->payloadSize);
         if (!temp)
         {
-            OIC_LOG(ERROR, TAG, "CAClonePayloadInfo Out of memory");
+            OIC_LOG(ERROR, TAG, "CACloneInfo Out of memory");
             CADestroyInfoInternal(clone);
             return CA_MEMORY_ALLOC_FAILED;
         }
@@ -436,11 +281,7 @@ CAResult_t CACloneInfo(const CAInfo_t *info, CAInfo_t *clone)
 
         // save the payload
         clone->payload = temp;
-    }
-    else
-    {
-        clone->payload = NULL;
-        clone->payloadSize = 0;
+        clone->payloadSize = info->payloadSize;
     }
 
     if (info->resourceUri)
@@ -449,7 +290,7 @@ CAResult_t CACloneInfo(const CAInfo_t *info, CAInfo_t *clone)
         char *temp = OICStrdup(info->resourceUri);
         if (!temp)
         {
-            OIC_LOG(ERROR, TAG, "CAClonePayloadInfo Out of memory");
+            OIC_LOG(ERROR, TAG, "CACloneInfo Out of memory");
             CADestroyInfoInternal(clone);
             return CA_MEMORY_ALLOC_FAILED;
         }
@@ -458,6 +299,9 @@ CAResult_t CACloneInfo(const CAInfo_t *info, CAInfo_t *clone)
         clone->resourceUri = temp;
     }
 
+    clone->messageId = info->messageId;
+    clone->type = info->type;
+
     return CA_STATUS_OK;
 
 }
index 744b1a5..751bafc 100644 (file)
@@ -165,13 +165,13 @@ CAResult_t ca_thread_pool_add_task(ca_thread_pool_t thread_pool, ca_thread_func
     }
 
     ca_mutex_lock(thread_pool->details->list_lock);
-    CAResult_t addResult = u_arraylist_add(thread_pool->details->threads_list, (void*)threadHandle);
+    bool addResult = u_arraylist_add(thread_pool->details->threads_list, (void*)threadHandle);
     ca_mutex_unlock(thread_pool->details->list_lock);
 
-    if(addResult != CA_STATUS_OK)
+    if(!addResult)
     {
         OIC_LOG_V(ERROR, TAG, "Arraylist Add failed, may not be properly joined: %d", addResult);
-        return addResult;
+        return CA_STATUS_FAILED;
     }
 
     OIC_LOG(DEBUG, TAG, "OUT");
@@ -200,11 +200,7 @@ void ca_thread_pool_free(ca_thread_pool_t thread_pool)
         }
     }
 
-    CAResult_t freeres = u_arraylist_free(&(thread_pool->details->threads_list));
-    if(CA_STATUS_OK != freeres)
-    {
-        OIC_LOG_V(ERROR, TAG, "Failed to free array list, error was: %d", freeres);
-    }
+    u_arraylist_free(&(thread_pool->details->threads_list));
 
     ca_mutex_unlock(thread_pool->details->list_lock);
     ca_mutex_free(thread_pool->details->list_lock);
index be897be..8cc88f4 100644 (file)
@@ -54,19 +54,17 @@ u_arraylist_t *u_arraylist_create()
     return list;
 }
 
-CAResult_t u_arraylist_free(u_arraylist_t **list)
+void u_arraylist_free(u_arraylist_t **list)
 {
     if (!list || !(*list))
     {
-        return CA_STATUS_INVALID_PARAM;
+        return;
     }
 
     OICFree((*list)->data);
     OICFree(*list);
 
     *list = NULL;
-
-    return CA_STATUS_OK;
 }
 
 void *u_arraylist_get(const u_arraylist_t *list, uint32_t index)
@@ -84,20 +82,20 @@ void *u_arraylist_get(const u_arraylist_t *list, uint32_t index)
     return NULL;
 }
 
-CAResult_t u_arraylist_add(u_arraylist_t *list, void *data)
+bool u_arraylist_add(u_arraylist_t *list, void *data)
 {
     if (!list)
     {
-        return CA_STATUS_INVALID_PARAM;
+        return false;
     }
 
     if (list->size <= list->length)
     {
-
-       uint32_t new_size = list->size + 1;
+        uint32_t new_size = list->size + 1;
         if (!(list->data = (void **) realloc(list->data, new_size * sizeof(void *))))
         {
-            return CA_MEMORY_ALLOC_FAILED;
+            OIC_LOG(ERROR, TAG, "Failed to re-allocation memory");
+            return false;
         }
 
         memset(list->data + list->size, 0, (new_size - list->size) * sizeof(void *));
@@ -107,7 +105,7 @@ CAResult_t u_arraylist_add(u_arraylist_t *list, void *data)
     list->data[list->length] = data;
     list->length++;
 
-    return CA_STATUS_OK;
+    return true;
 }
 
 void *u_arraylist_remove(u_arraylist_t *list, uint32_t index)
index f220870..a750291 100644 (file)
@@ -168,7 +168,7 @@ typedef void (*CARegisterConnectivityCallback)(CAConnectivityHandler_t handler,
  * This will be used during the receive of network requests and response.
  * @see SendUnicastData(), SendMulticastData()
  */
-typedef void (*CANetworkPacketReceivedCallback)(const CAEndpoint_t *endPoint,
+typedef void (*CANetworkPacketReceivedCallback)(const CASecureEndpoint_t *sep,
                                             const void *data, uint32_t dataLen);
 
 /**
index dc19b9f..e6940d8 100644 (file)
@@ -38,7 +38,7 @@
  */
 extern void OCGetDtlsPskCredentials(CADtlsPskCredsBlob_t **credInfo);
 
-typedef void (*CAPacketReceivedCallback)(const CAEndpoint_t *endpoint,
+typedef void (*CAPacketReceivedCallback)(const CASecureEndpoint_t *sep,
                                          const void *data, uint32_t dataLength);
 
 typedef void (*CAPacketSendCallback)(CAEndpoint_t *endpoint,
@@ -249,7 +249,7 @@ CAResult_t CAAdapterNetDtlsEncrypt(const CAEndpoint_t *endpoint,
  * @retval  ::CA_STATUS_FAILED Operation failed.
  *
  */
-CAResult_t CAAdapterNetDtlsDecrypt(const CAEndpoint_t *endpoint,
+CAResult_t CAAdapterNetDtlsDecrypt(const CASecureEndpoint_t *sep,
                                    uint8_t *data,
                                    uint32_t dataLen);
 
index 6a71f28..677b1f9 100644 (file)
@@ -50,12 +50,12 @@ typedef enum
 /**
  * Callback to be notified on reception of any data from remote OIC devices.
  *
- * @param[in]  endpoint      network endpoint description.
+ * @param[in]  sep         network endpoint description.
  * @param[in]  data          Data received from remote OIC device.
  * @param[in]  dataLength    Length of data in bytes.
  * @pre  Callback must be registered using CAIPSetPacketReceiveCallback().
  */
-typedef void (*CAIPPacketReceivedCallback)(const CAEndpoint_t *endpoint,
+typedef void (*CAIPPacketReceivedCallback)(const CASecureEndpoint_t *sep,
                                            const void *data,
                                            uint32_t dataLength);
 
@@ -173,7 +173,41 @@ typedef struct
 u_arraylist_t *CAIPGetInterfaceInformation(int desiredIndex);
 
 /**
- * Set callback for error handling.
+ * @brief   Find a new network interface.
+ *
+ * @return  Description of interface (or NULL if no change)
+ */
+CAInterface_t *CAFindInterfaceChange();
+
+/**
+ * @brief   Let the network monitor update the polling interval.
+ * @param   [in] current polling interval
+ *
+ * @return  desired polling interval
+ */
+int CAGetPollingInterval(int interval);
+
+/**
+ * @brief   Tell the IP server an interface has been added.
+ */
+void CAWakeUpForChange();
+
+/**
+ * @brief   Initializes network monitor.
+ *
+ * @return ::CA_STATUS_OK or Appropriate error code.
+ */
+CAResult_t CAIPInitializeNetworkMonitor();
+
+/**
+ * @brief   Terminates network monitor.
+ *
+ * @return ::CA_STATUS_OK or Appropriate error code.
+ */
+CAResult_t CAIPTerminateNetworkMonitor();
+
+/**
+ * @brief  Set callback for error handling.
  *
  * @param[in]  ipErrorCallback  callback to notify error to the ipadapter.
  */
index 4ec1cad..45f9f64 100644 (file)
@@ -52,9 +52,7 @@ typedef struct
     CARequestInfo_t *requestInfo;
     CAResponseInfo_t *responseInfo;
     CAErrorInfo_t *errorInfo;
-    CAHeaderOption_t *options;
     CADataType_t dataType;
-    uint8_t numOptions;
 } CAData_t;
 
 #ifdef __cplusplus
index 705427b..ce5f039 100644 (file)
@@ -1372,6 +1372,13 @@ void callback(char *subject, char *receivedData)
 {
     bool isAttached = false;
     JNIEnv* env;
+
+    if (!g_responseListenerObject)
+    {
+        LOGE("g_responseListenerObject is NULL, cannot have callback");
+        return;
+    }
+
     jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
     if (JNI_OK != res)
     {
@@ -1387,6 +1394,12 @@ void callback(char *subject, char *receivedData)
     }
 
     jclass cls = (*env)->GetObjectClass(env, g_responseListenerObject);
+    if (!cls)
+    {
+        LOGE("could not get class");
+        goto detach_thread;
+    }
+
     jmethodID mid = (*env)->GetMethodID(env, cls, "OnResponseReceived",
                                         "(Ljava/lang/String;Ljava/lang/String;)V");
     if (!mid)
@@ -1461,7 +1474,7 @@ void parsing_coap_uri(const char* uri, addressSet_t* address, CATransportFlags_t
     }
 
     // #2. copy uri for parse
-    int32_t len = strlen(uri) - startIndex;
+    size_t len = strlen(uri) - startIndex;
 
     if (len <= 0)
     {
@@ -1476,19 +1489,26 @@ void parsing_coap_uri(const char* uri, addressSet_t* address, CATransportFlags_t
         return;
     }
 
-    memcpy(cloneUri, &uri[startIndex], sizeof(char) * len);
-    cloneUri[len] = '\0';
+    OICStrcpy(cloneUri, len+1, &uri[startIndex]);
 
-    char *pAddress = cloneUri;
-    LOGI("pAddress : %s", pAddress);
+    char *pstr = NULL;
+    //filter out the resource uri
+    char *pUrl = strtok_r(cloneUri, "/", &pstr);
 
-    int res = get_address_set(pAddress, address);
-    if (res == -1)
+    if (pUrl)
     {
-        LOGE("address parse error");
+        LOGI("pAddress : %s", pUrl);
+        int res = get_address_set(pUrl, address);
+        if (res == -1)
+        {
+            LOGE("address parse error");
 
-        free(cloneUri);
-        return;
+            return;
+        }
+    }
+    else
+    {
+        LOGE("strtok_r error, could not get the address");
     }
 
     return;
index 97a72bf..af9ed9a 100644 (file)
@@ -50,7 +50,7 @@ static ca_mutex g_dtlsContextMutex = NULL;
  */
 static CAGetDTLSCredentialsHandler g_getCredentialsCallback = NULL;
 
-static CAEndpoint_t *GetPeerInfo(const CAEndpoint_t *peer)
+static CASecureEndpoint_t *GetPeerInfo(const CAEndpoint_t *peer)
 {
     uint32_t list_index = 0;
     uint32_t list_length = 0;
@@ -61,18 +61,18 @@ static CAEndpoint_t *GetPeerInfo(const CAEndpoint_t *peer)
         return NULL;
     }
 
-    CAEndpoint_t *peerInfo;
+    CASecureEndpoint_t *peerInfo = NULL;
     list_length = u_arraylist_length(g_caDtlsContext->peerInfoList);
     for (list_index = 0; list_index < list_length; list_index++)
     {
-        peerInfo = (CAEndpoint_t *)u_arraylist_get(g_caDtlsContext->peerInfoList, list_index);
+        peerInfo = (CASecureEndpoint_t *)u_arraylist_get(g_caDtlsContext->peerInfoList, list_index);
         if (NULL == peerInfo)
         {
             continue;
         }
 
-        if((0 == strncmp(peer->addr, peerInfo->addr, MAX_ADDR_STR_SIZE_CA)) &&
-                (peer->port == peerInfo->port))
+        if((0 == strncmp(peer->addr, peerInfo->endpoint.addr, MAX_ADDR_STR_SIZE_CA)) &&
+                (peer->port == peerInfo->endpoint.port))
         {
             return peerInfo;
         }
@@ -80,8 +80,8 @@ static CAEndpoint_t *GetPeerInfo(const CAEndpoint_t *peer)
     return NULL;
 }
 
-static CAResult_t CAAddIdToPeerInfoList(const char *peerAddr, uint16_t port,
-        const unsigned char *id, uint16_t id_length, CATransportFlags_t flag)
+static CAResult_t CAAddIdToPeerInfoList(const char *peerAddr, uint32_t port,
+        const unsigned char *id, uint16_t id_length)
 {
     if(NULL == peerAddr
        || NULL == id
@@ -93,31 +93,28 @@ static CAResult_t CAAddIdToPeerInfoList(const char *peerAddr, uint16_t port,
         return CA_STATUS_INVALID_PARAM;
     }
 
-    CAEndpoint_t *peer = (CAEndpoint_t *)OICCalloc(1, sizeof (CAEndpoint_t));
+    CASecureEndpoint_t *peer = (CASecureEndpoint_t *)OICCalloc(1, sizeof (CASecureEndpoint_t));
     if (NULL == peer)
     {
         OIC_LOG(ERROR, NET_DTLS_TAG, "peerInfo malloc failed!");
         return CA_MEMORY_ALLOC_FAILED;
     }
 
-    OICStrcpy(peer->addr, sizeof(peer->addr), peerAddr);
-    peer->port = port;
-    peer->flags = flag;
-    peer->flags |= CA_SECURE;
-    peer->adapter = CA_ADAPTER_IP;
+    OICStrcpy(peer->endpoint.addr, sizeof(peer->endpoint.addr), peerAddr);
+    peer->endpoint.port = port;
 
     memcpy(peer->identity.id, id, id_length);
     peer->identity.id_length = id_length;
 
-    if(NULL != GetPeerInfo(peer))
+    if (NULL != GetPeerInfo(&peer->endpoint))
     {
         OIC_LOG(ERROR, NET_DTLS_TAG, "CAAddIdToPeerInfoList peer already exist");
         OICFree(peer);
         return CA_STATUS_FAILED;
     }
 
-    CAResult_t result = u_arraylist_add(g_caDtlsContext->peerInfoList, (void *)peer);
-    if (CA_STATUS_OK != result)
+    bool result = u_arraylist_add(g_caDtlsContext->peerInfoList, (void *)peer);
+    if (!result)
     {
         OIC_LOG(ERROR, NET_DTLS_TAG, "u_arraylist_add failed!");
         OICFree(peer);
@@ -301,8 +298,8 @@ static CAResult_t CADtlsCacheMsg(stCACacheMessage_t *msg)
         return CA_STATUS_FAILED;
     }
 
-    CAResult_t result = u_arraylist_add(g_caDtlsContext->cacheList, (void *)msg);
-    if (CA_STATUS_OK != result)
+    bool result = u_arraylist_add(g_caDtlsContext->cacheList, (void *)msg);
+    if (!result)
     {
         OIC_LOG(ERROR, NET_DTLS_TAG, "u_arraylist_add failed!");
     }
@@ -385,12 +382,13 @@ static int32_t CAReadDecryptedPayload(dtls_context_t *context,
 
     stCADtlsAddrInfo_t *addrInfo = (stCADtlsAddrInfo_t *)session;
 
-    CAEndpoint_t endpoint = { 0 };
-    CAConvertAddrToName(&(addrInfo->addr.st), endpoint.addr, &endpoint.port);
-    endpoint.flags = addrInfo->addr.st.ss_family == AF_INET ? CA_IPV4 : CA_IPV6;
-    endpoint.flags |= CA_SECURE;
-    endpoint.adapter = CA_ADAPTER_IP;
-    int type = 0;
+    CASecureEndpoint_t sep =
+    { .endpoint =
+    { .adapter = CA_ADAPTER_IP, .flags =
+            ((addrInfo->addr.st.ss_family == AF_INET) ? CA_IPV4 : CA_IPV6) | CA_SECURE, .port = 0 },
+            .identity =
+            { 0 } };
+    CAConvertAddrToName(&(addrInfo->addr.st), sep.endpoint.addr, &sep.endpoint.port);
 
     if (NULL == g_caDtlsContext)
     {
@@ -398,17 +396,18 @@ static int32_t CAReadDecryptedPayload(dtls_context_t *context,
         return 0;
     }
 
+    int type = 0;
     if ((0 <= type) && (MAX_SUPPORTED_ADAPTERS > type) &&
         (NULL != g_caDtlsContext->adapterCallbacks[type].recvCallback))
     {
         // Get identity of the source of packet
-        CAEndpoint_t *peerInfo = GetPeerInfo(&endpoint);
+        CASecureEndpoint_t *peerInfo = GetPeerInfo(&sep.endpoint);
         if (peerInfo)
         {
-            endpoint.identity = peerInfo->identity;
+            sep.identity = peerInfo->identity;
         }
 
-        g_caDtlsContext->adapterCallbacks[type].recvCallback(&endpoint, buf, bufLen);
+        g_caDtlsContext->adapterCallbacks[type].recvCallback(&sep, buf, bufLen);
     }
     else
     {
@@ -483,7 +482,7 @@ static int32_t CAHandleSecureEvent(dtls_context_t *context,
         OIC_LOG(INFO, NET_DTLS_TAG, "Peer closing connection");
 
         stCADtlsAddrInfo_t *addrInfo = (stCADtlsAddrInfo_t *)session;
-        char peerAddr[MAX_ADDR_STR_SIZE_CA] = {0};
+        char peerAddr[MAX_ADDR_STR_SIZE_CA] = { 0 };
         uint16_t port = 0;
         CAConvertAddrToName(&(addrInfo->addr.st), peerAddr, &port);
         CARemovePeerFromPeerInfoList(peerAddr, port);
@@ -550,15 +549,11 @@ static int32_t CAGetPskCredentials(dtls_context_t *ctx,
                     // data structure when handshake completes. Therefore, currently this is a
                     // workaround to cache remote end-point identity when tinyDTLS asks for PSK.
                     stCADtlsAddrInfo_t *addrInfo = (stCADtlsAddrInfo_t *)session;
-                    char peerAddress[MAX_ADDR_STR_SIZE_CA] = {0};
+                    char peerAddr[MAX_ADDR_STR_SIZE_CA] = { 0 };
                     uint16_t port = 0;
-                    CAConvertAddrToName(&(addrInfo->addr.st), peerAddress, &port);
+                    CAConvertAddrToName(&(addrInfo->addr.st), peerAddr, &port);
 
-                    CATransportFlags_t flag =
-                            addrInfo->addr.st.ss_family == AF_INET ? CA_IPV4 : CA_IPV6;
-
-                    CAResult_t result = CAAddIdToPeerInfoList(peerAddress,
-                            port, desc, descLen, flag);
+                    CAResult_t result = CAAddIdToPeerInfoList(peerAddr, port, desc, descLen);
                     if(CA_STATUS_OK != result )
                     {
                         OIC_LOG(ERROR, NET_DTLS_TAG, "Fail to add peer id to gDtlsPeerInfoList");
@@ -954,15 +949,15 @@ CAResult_t CAAdapterNetDtlsEncrypt(const CAEndpoint_t *endpoint,
     return CA_STATUS_OK;
 }
 
-CAResult_t CAAdapterNetDtlsDecrypt(const CAEndpoint_t *endpoint,
+CAResult_t CAAdapterNetDtlsDecrypt(const CASecureEndpoint_t *sep,
                                    uint8_t *data, uint32_t dataLen)
 {
     OIC_LOG(DEBUG, NET_DTLS_TAG, "IN");
-    VERIFY_NON_NULL_RET(endpoint, NET_DTLS_TAG, "endpoint is NULL" , CA_STATUS_INVALID_PARAM);
+    VERIFY_NON_NULL_RET(sep, NET_DTLS_TAG, "endpoint is NULL" , CA_STATUS_INVALID_PARAM);
 
     stCADtlsAddrInfo_t addrInfo = { 0 };
 
-    CAConvertNameToAddr(endpoint->addr, endpoint->port, &(addrInfo.addr.st));
+    CAConvertNameToAddr(sep->endpoint.addr, sep->endpoint.port, &(addrInfo.addr.st));
     addrInfo.ifIndex = 0;
     addrInfo.size = CASizeOfAddrInfo(&addrInfo);
 
index cbd1fb8..5a8a231 100644 (file)
@@ -525,7 +525,7 @@ void CAEDRNativeRemoveDevice(const char *remoteAddress)
             OIC_LOG_V(DEBUG, TAG, "[EDR][Native] remove state : %s", remoteAddress);
             OICFree(state);
 
-            CAEDRReorderingDeviceList(index);
+            u_arraylist_remove(g_deviceStateList, index);
             break;
         }
     }
@@ -569,23 +569,6 @@ CAConnectedState_t CAEDRIsConnectedDevice(const char *remoteAddress)
     return STATE_DISCONNECTED;
 }
 
-void CAEDRReorderingDeviceList(uint32_t index)
-{
-    if (index >= g_deviceStateList->length)
-    {
-        return;
-    }
-
-    if (index < g_deviceStateList->length - 1)
-    {
-        memmove(&g_deviceStateList->data[index], &g_deviceStateList->data[index + 1],
-                (g_deviceStateList->length - index - 1) * sizeof(void *));
-    }
-
-    g_deviceStateList->size--;
-    g_deviceStateList->length--;
-}
-
 /**
  * Device Socket Object List
  */
@@ -808,7 +791,7 @@ void CAEDRNativeRemoveDeviceSocket(JNIEnv *env, jobject deviceSocket)
             (*env)->ReleaseStringUTFChars(env, jni_setAddress, setAddress);
             (*env)->ReleaseStringUTFChars(env, jni_remoteAddress, remoteAddress);
 
-            CAEDRReorderingDeviceSocketList(index);
+            u_arraylist_remove(g_deviceObjectList, index);
             break;
         }
         (*env)->ReleaseStringUTFChars(env, jni_setAddress, setAddress);
@@ -856,7 +839,7 @@ void CAEDRNativeRemoveDeviceSocketBaseAddr(JNIEnv *env, jstring address)
             (*env)->ReleaseStringUTFChars(env, jni_setAddress, setAddress);
             (*env)->ReleaseStringUTFChars(env, address, remoteAddress);
 
-            CAEDRReorderingDeviceSocketList(index);
+            u_arraylist_remove(g_deviceObjectList, index);
             break;
         }
         (*env)->ReleaseStringUTFChars(env, jni_setAddress, setAddress);
@@ -939,20 +922,3 @@ uint32_t CAEDRGetSocketListLength()
 
     return length;
 }
-
-void CAEDRReorderingDeviceSocketList(uint32_t index)
-{
-    if (index >= g_deviceObjectList->length)
-    {
-        return;
-    }
-
-    if (index < g_deviceObjectList->length - 1)
-    {
-        memmove(&g_deviceObjectList->data[index], &g_deviceObjectList->data[index + 1],
-                (g_deviceObjectList->length - index - 1) * sizeof(void *));
-    }
-
-    g_deviceObjectList->size--;
-    g_deviceObjectList->length--;
-}
index 00ddffc..ec12615 100644 (file)
@@ -129,12 +129,6 @@ void CAEDRNativeRemoveDevice(const char *remoteAddress);
  */
 CAConnectedState_t CAEDRIsConnectedDevice(const char *remoteAddress);
 
-/**
- * Reordering for the list.
- * @param[in]   index           index of device list that want to reordering.
- */
-void CAEDRReorderingDeviceList(uint32_t index);
-
 /**
  * This function will create the device socket list.
  */
@@ -196,11 +190,6 @@ jobject CAEDRNativeGetDeviceSocketBaseAddr(JNIEnv *env, const char* remoteAddres
  */
 uint32_t CAEDRGetSocketListLength();
 
-/**
- * Reordering for the list.
- * @param[in]   index           index of device list that want to reordering.
- */
-void CAEDRReorderingDeviceSocketList(uint32_t index);
 #ifdef __cplusplus
 } /* extern "C" */
 #endif
index 18061e7..c7156e6 100644 (file)
@@ -34,7 +34,6 @@ CAResult_t CAEDRSendData(int serverFD, const void *data, uint32_t dataLength)
     OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
 
     VERIFY_NON_NULL(data, EDR_ADAPTER_TAG, "Data is null");
-    VERIFY_NON_NULL(sentDataLen, EDR_ADAPTER_TAG, "Sent data length holder is null");
 
     if (0 > serverFD)
     {
index 20b9962..d9af8e6 100644 (file)
@@ -51,10 +51,9 @@ static CAEDRNetworkStatusCallback g_edrNetworkChangeCallback = NULL;
 static void CAEDRAdapterStateChangeCallback(int result, bt_adapter_state_e adapterState,
                                             void *userData);
 
-void *GMainLoopThread (void *param)
+void GMainLoopThread (void *param)
 {
     g_main_loop_run(g_mainloop);
-    return NULL;
 }
 
 CAResult_t CAEDRInitializeNetworkMonitor(const ca_thread_pool_t threadPool)
index 38ae49a..075c9bd 100644 (file)
@@ -2221,7 +2221,12 @@ CAResult_t CALEClientRemoveDeviceInScanDeviceList(JNIEnv *env, jstring address)
             (*env)->ReleaseStringUTFChars(env, jni_setAddress, setAddress);
             (*env)->ReleaseStringUTFChars(env, address, remoteAddress);
 
-            CALEClientReorderingList(index, g_deviceList);
+            if (NULL == u_arraylist_remove(g_deviceList, index))
+            {
+                OIC_LOG(ERROR, TAG, "List removal failed.");
+                ca_mutex_unlock(g_deviceListMutex);
+                return CA_STATUS_FAILED;
+            }
             ca_mutex_unlock(g_deviceListMutex);
             return CA_STATUS_OK;
         }
@@ -2468,8 +2473,15 @@ CAResult_t CALEClientRemoveGattObj(JNIEnv *env, jobject gatt)
             (*env)->DeleteGlobalRef(env, jarrayObj);
             (*env)->ReleaseStringUTFChars(env, jni_setAddress, setAddress);
             (*env)->ReleaseStringUTFChars(env, jni_remoteAddress, remoteAddress);
+
+            if (NULL == u_arraylist_remove(g_gattObjectList, index))
+            {
+                OIC_LOG(ERROR, TAG, "List removal failed.");
+                ca_mutex_unlock(g_gattObjectMutex);
+                return CA_STATUS_FAILED;
+            }
             ca_mutex_unlock(g_gattObjectMutex);
-            return CALEClientReorderingList(index, g_gattObjectList);
+            return CA_STATUS_OK;
         }
         (*env)->ReleaseStringUTFChars(env, jni_setAddress, setAddress);
         (*env)->ReleaseStringUTFChars(env, jni_remoteAddress, remoteAddress);
@@ -2537,8 +2549,14 @@ CAResult_t CALEClientRemoveGattObjForAddr(JNIEnv *env, jstring addr)
 
             (*env)->ReleaseStringUTFChars(env, jni_setAddress, setAddress);
             (*env)->ReleaseStringUTFChars(env, addr, remoteAddress);
+            if (NULL == u_arraylist_remove(g_gattObjectList, index))
+            {
+                OIC_LOG(ERROR, TAG, "List removal failed.");
+                ca_mutex_unlock(g_gattObjectMutex);
+                return CA_STATUS_FAILED;
+            }
             ca_mutex_unlock(g_gattObjectMutex);
-            return CALEClientReorderingList(index, g_gattObjectList);
+            return CA_STATUS_OK;
         }
         (*env)->ReleaseStringUTFChars(env, jni_setAddress, setAddress);
         (*env)->ReleaseStringUTFChars(env, addr, remoteAddress);
@@ -2716,12 +2734,12 @@ CAResult_t CALEClientRemoveDeviceState(const char* remoteAddress)
             OIC_LOG_V(DEBUG, TAG, "remove state : %s", remoteAddress);
             OICFree(state);
 
-            CAResult_t res = CALEClientReorderingList(index, g_deviceStateList);
-            if(CA_STATUS_OK != res)
+            if (NULL == u_arraylist_remove(g_deviceStateList, index))
             {
-                OIC_LOG(ERROR, TAG, "CALEClientReorderingList has failed");
-                return res;
+                OIC_LOG(ERROR, TAG, "List removal failed.");
+                return CA_STATUS_FAILED;
             }
+
             return CA_STATUS_OK;
         }
     }
@@ -2873,32 +2891,6 @@ void CALEClientCreateDeviceList()
     }
 }
 
-CAResult_t CALEClientReorderingList(uint32_t index, u_arraylist_t *list)
-{
-    if (!list)
-    {
-        OIC_LOG(ERROR, TAG, "list is null");
-        return CA_STATUS_FAILED;
-    }
-
-    if (index >= list->length)
-    {
-        OIC_LOG(ERROR, TAG, "index is not available");
-        return CA_STATUS_FAILED;
-    }
-
-    if (index < list->length - 1)
-    {
-        memmove(&list->data[index], &list->data[index + 1],
-                (list->length - index - 1) * sizeof(void *));
-    }
-
-    list->size--;
-    list->length--;
-
-    return CA_STATUS_OK;
-}
-
 /**
  * Check Sent Count for remove g_sendBuffer
  */
index 1b04609..708a1c5 100644 (file)
@@ -508,14 +508,6 @@ bool CALEClientIsSetCharacteristic(const char* remoteAddress);
  */
 void CALEClientCreateDeviceList();
 
-/**
- * Reordering for device state list.
- * @param[in]   index                 index of device list that want to reordering.
- * @param[in]   list                  the list to reorder.
- * @return  ::CA_STATUS_OK or ERROR CODES (::CAResult_t error codes in cacommon.h).
- */
-CAResult_t CALEClientReorderingList(uint32_t index, u_arraylist_t *list);
-
 /**
  * update the counter which data is sent to remote device.
  * @param[in]   env                   JNI interface pointer.
index db04fac..8f8ec34 100644 (file)
@@ -2018,12 +2018,11 @@ CAResult_t CALEServerRemoveDevice(JNIEnv *env, jstring address)
                 (*env)->ReleaseStringUTFChars(env, address, remoteAddress);
                 (*env)->DeleteGlobalRef(env, jarrayObj);
 
-                CAResult_t res = CALEServerReorderinglist(index);
-                if (CA_STATUS_OK != res)
+                if (NULL == u_arraylist_remove(g_connectedDeviceList, index))
                 {
-                    OIC_LOG(ERROR, TAG, "CALEServerReorderinglist has failed");
+                    OIC_LOG(ERROR, TAG, "List removal failed.");
                     ca_mutex_unlock(g_connectedDeviceListMutex);
-                    return res;
+                    return CA_STATUS_FAILED;
                 }
                 ca_mutex_unlock(g_connectedDeviceListMutex);
                 return CA_STATUS_OK;
@@ -2041,32 +2040,6 @@ CAResult_t CALEServerRemoveDevice(JNIEnv *env, jstring address)
     return CA_STATUS_FAILED;
 }
 
-CAResult_t CALEServerReorderinglist(uint32_t index)
-{
-    if (!g_connectedDeviceList)
-    {
-        OIC_LOG(ERROR, TAG, "g_connectedDeviceList is null");
-        return CA_STATUS_FAILED;
-    }
-
-    if (index >= g_connectedDeviceList->length)
-    {
-        OIC_LOG(ERROR, TAG, "index is not available");
-        return CA_STATUS_FAILED;
-    }
-
-    if (index < g_connectedDeviceList->length - 1)
-    {
-        memmove(&g_connectedDeviceList->data[index], &g_connectedDeviceList->data[index + 1],
-                (g_connectedDeviceList->length - index - 1) * sizeof(void *));
-    }
-
-    g_connectedDeviceList->size--;
-    g_connectedDeviceList->length--;
-
-    return CA_STATUS_OK;
-}
-
 JNIEXPORT void JNICALL
 Java_org_iotivity_ca_CaLeServerInterface_caLeRegisterGattServerCallback(JNIEnv *env, jobject obj,
                                                                         jobject callback)
index 1b7a862..48484b5 100644 (file)
@@ -291,13 +291,6 @@ CAResult_t CALEServerRemoveAllDevices(JNIEnv *env);
  */
 CAResult_t CALEServerRemoveDevice(JNIEnv *env, jstring address);
 
-/**
- * Reordering for the list (connected device list).
- * @param[in]   index                 index of device list that want to reordering.
- * @return  ::CA_STATUS_OK or ERROR CODES (::CAResult_t error codes in cacommon.h).
- */
-CAResult_t CALEServerReorderinglist(uint32_t index);
-
 /**
  * initialize mutex.
  * @return  ::CA_STATUS_OK or ERROR CODES (::CAResult_t error codes in cacommon.h).
index 9a46051..2a198db 100644 (file)
@@ -256,193 +256,6 @@ static CAQueueingThread_t *g_bleReceiverQueue = NULL;
  */
 static CAQueueingThread_t *g_bleServerSendQueueHandle = NULL;
 
-/**
- * Starting LE connectivity adapters.
- *
- * As its peer to peer it does not require to start any servers.
- *
- * @return ::CA_STATUS_OK or Appropriate error code.
- */
-static CAResult_t CAStartLE();
-
-/**
- * Start listening server for receiving multicast search requests.
- *
- * Transport Specific Behavior:
- *   LE  Starts GATT Server with prefixed UUID and Characteristics
- *   per OIC Specification.
- * @return  ::CA_STATUS_OK or Appropriate error code.
- */
-static CAResult_t CAStartLEListeningServer();
-
-/**
- * Sarting discovery of servers for receiving multicast
- * advertisements.
- *
- * Transport Specific Behavior:
- *   LE  Starts GATT Server with prefixed UUID and Characteristics
- *   per OIC Specification.
- *
- * @return ::CA_STATUS_OK or Appropriate error code
- */
-static CAResult_t CAStartLEDiscoveryServer();
-
-/**
- * Send data to the endpoint using the adapter connectivity.
- *
- * @param[in] endpoint Remote Endpoint information (like MAC address,
- *                     reference URI and connectivity type) to which
- *                     the unicast data has to be sent.
- * @param[in] data     Data which required to be sent.
- * @param[in] dataLen  Size of data to be sent.
- *
- * @note  dataLen must be > 0.
- *
- * @return The number of bytes sent on the network, or -1 on error.
- */
-static int32_t CASendLEUnicastData(const CAEndpoint_t *endpoint,
-                                   const void *data,
-                                   uint32_t dataLen);
-
-/**
- * Send multicast data to the endpoint using the LE connectivity.
- *
- * @param[in] endpoint Remote Endpoint information to which the
- *                     multicast data has to be sent.
- * @param[in] data     Data which required to be sent.
- * @param[in] dataLen  Size of data to be sent.
- *
- * @note  dataLen must be > 0.
- *
- * @return The number of bytes sent on the network, or -1 on error.
- */
-static int32_t CASendLEMulticastData(const CAEndpoint_t *endpoint,
-                                     const void *data,
-                                     uint32_t dataLen);
-
-/**
- * Get LE Connectivity network information.
- *
- * @param[out] info Local connectivity information structures.
- * @param[out] size Number of local connectivity structures.
- *
- * @return ::CA_STATUS_OK or Appropriate error code.
- */
-static CAResult_t CAGetLEInterfaceInformation(CAEndpoint_t **info,
-                                              uint32_t *size);
-
-/**
- * Read Synchronous API callback.
- *
- * @return  ::CA_STATUS_OK or Appropriate error code.
- */
-static CAResult_t CAReadLEData();
-
-/**
- * Stopping the adapters and close socket connections.
- *
- * LE Stops all GATT servers and GATT Clients.
- *
- * @return ::CA_STATUS_OK or Appropriate error code.
- */
-static CAResult_t CAStopLE();
-
-/**
- * Terminate the LE connectivity adapter.
- *
- * Configuration information will be deleted from further use.
- */
-static void CATerminateLE();
-
-/**
- * Set the NetworkPacket received callback to CA layer from adapter
- * layer.
- *
- * @param[in] callback Callback handle sent from the upper layer.
- */
-static void CASetLEReqRespAdapterCallback(CANetworkPacketReceivedCallback callback);
-
-/**
- * Push the data from CA layer to the Sender processor queue.
- *
- * @param[in] remoteEndpoint Remote endpoint information of the
- *                           server.
- * @param[in] data           Data to be transmitted from LE.
- * @param[in] dataLen        Length of the Data being transmitted.
- *
- * @return ::CA_STATUS_OK or Appropriate error code.
- * @retval ::CA_STATUS_OK  Successful.
- * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
- * @retval ::CA_STATUS_FAILED Operation failed.
- */
-static CAResult_t CALEAdapterServerSendData(const CAEndpoint_t *remoteEndpoint,
-                                            const uint8_t *data,
-                                            uint32_t dataLen);
-
-/**
- * Push the data from CA layer to the Sender processor queue.
- *
- * @param[in] remoteEndpoint Remote endpoint information of the
- *                           server.
- * @param[in] data           Data to be transmitted from LE.
- * @param[in] dataLen        Length of the Data being transmitted.
- *
- * @return ::CA_STATUS_OK or Appropriate error code.
- * @retval ::CA_STATUS_OK  Successful.
- * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
- * @retval ::CA_STATUS_FAILED Operation failed.
- */
-static CAResult_t CALEAdapterClientSendData(const CAEndpoint_t *remoteEndpoint,
-                                            const uint8_t *data,
-                                            uint32_t dataLen);
-
-/**
- * This function will receive the data from the GattServer and add the
- * data to the Server receiver queue.
- *
- * @param[in] remoteAddress Remote address of the device from where
- *                          data is received.
- * @param[in] data          Actual data recevied from the remote
- *                          device.
- * @param[in] dataLength    Length of the data received from the
- *                          remote device.
- * @param[in] sentLength    Length of the data sent from the remote
- *                          device.
- *
- * @return ::CA_STATUS_OK or Appropriate error code.
- * @retval ::CA_STATUS_OK  Successful.
- * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
- * @retval ::CA_STATUS_FAILED Operation failed.
- *
- */
-static CAResult_t CALEAdapterServerReceivedData(const char *remoteAddress,
-                                                const uint8_t *data,
-                                                uint32_t dataLength,
-                                                uint32_t *sentLength);
-
-/**
- * This function will receive the data from the GattClient and add the
- * data into the Client receiver queue.
- *
- * @param[in] remoteAddress Remote address of the device from where
- *                          data is received.
- * @param[in] data          Actual data recevied from the remote
- *                          device.
- * @param[in] dataLength    Length of the data received from the
- *                          remote device.
- * @param[in] sentLength    Length of the data sent from the remote
- *                          device.
- *
- * @return ::CA_STATUS_OK or Appropriate error code.
- * @retval ::CA_STATUS_OK  Successful.
- * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
- * @retval ::CA_STATUS_FAILED Operation failed.
- */
-static CAResult_t CALEAdapterClientReceivedData(const char *remoteAddress,
-                                                const uint8_t *data,
-                                                uint32_t dataLength,
-                                                uint32_t *sentLength);
-
 /**
  * This function will be associated with the sender queue for
  * GattServer.
@@ -1606,6 +1419,193 @@ static void CATerminateLEAdapterMutex()
     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
 }
 
+/**
+ * Starting LE connectivity adapters.
+ *
+ * As its peer to peer it does not require to start any servers.
+ *
+ * @return ::CA_STATUS_OK or Appropriate error code.
+ */
+static CAResult_t CAStartLE();
+
+/**
+ * Start listening server for receiving multicast search requests.
+ *
+ * Transport Specific Behavior:
+ *   LE  Starts GATT Server with prefixed UUID and Characteristics
+ *   per OIC Specification.
+ * @return  ::CA_STATUS_OK or Appropriate error code.
+ */
+static CAResult_t CAStartLEListeningServer();
+
+/**
+ * Sarting discovery of servers for receiving multicast
+ * advertisements.
+ *
+ * Transport Specific Behavior:
+ *   LE  Starts GATT Server with prefixed UUID and Characteristics
+ *   per OIC Specification.
+ *
+ * @return ::CA_STATUS_OK or Appropriate error code
+ */
+static CAResult_t CAStartLEDiscoveryServer();
+
+/**
+ * Send data to the endpoint using the adapter connectivity.
+ *
+ * @param[in] endpoint Remote Endpoint information (like MAC address,
+ *                     reference URI and connectivity type) to which
+ *                     the unicast data has to be sent.
+ * @param[in] data     Data which required to be sent.
+ * @param[in] dataLen  Size of data to be sent.
+ *
+ * @note  dataLen must be > 0.
+ *
+ * @return The number of bytes sent on the network, or -1 on error.
+ */
+static int32_t CASendLEUnicastData(const CAEndpoint_t *endpoint,
+                                   const void *data,
+                                   uint32_t dataLen);
+
+/**
+ * Send multicast data to the endpoint using the LE connectivity.
+ *
+ * @param[in] endpoint Remote Endpoint information to which the
+ *                     multicast data has to be sent.
+ * @param[in] data     Data which required to be sent.
+ * @param[in] dataLen  Size of data to be sent.
+ *
+ * @note  dataLen must be > 0.
+ *
+ * @return The number of bytes sent on the network, or -1 on error.
+ */
+static int32_t CASendLEMulticastData(const CAEndpoint_t *endpoint,
+                                     const void *data,
+                                     uint32_t dataLen);
+
+/**
+ * Get LE Connectivity network information.
+ *
+ * @param[out] info Local connectivity information structures.
+ * @param[out] size Number of local connectivity structures.
+ *
+ * @return ::CA_STATUS_OK or Appropriate error code.
+ */
+static CAResult_t CAGetLEInterfaceInformation(CAEndpoint_t **info,
+                                              uint32_t *size);
+
+/**
+ * Read Synchronous API callback.
+ *
+ * @return  ::CA_STATUS_OK or Appropriate error code.
+ */
+static CAResult_t CAReadLEData();
+
+/**
+ * Stopping the adapters and close socket connections.
+ *
+ * LE Stops all GATT servers and GATT Clients.
+ *
+ * @return ::CA_STATUS_OK or Appropriate error code.
+ */
+static CAResult_t CAStopLE();
+
+/**
+ * Terminate the LE connectivity adapter.
+ *
+ * Configuration information will be deleted from further use.
+ */
+static void CATerminateLE();
+
+/**
+ * This function will receive the data from the GattServer and add the
+ * data to the Server receiver queue.
+ *
+ * @param[in] remoteAddress Remote address of the device from where
+ *                          data is received.
+ * @param[in] data          Actual data recevied from the remote
+ *                          device.
+ * @param[in] dataLength    Length of the data received from the
+ *                          remote device.
+ * @param[in] sentLength    Length of the data sent from the remote
+ *                          device.
+ *
+ * @return ::CA_STATUS_OK or Appropriate error code.
+ * @retval ::CA_STATUS_OK  Successful.
+ * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
+ * @retval ::CA_STATUS_FAILED Operation failed.
+ *
+ */
+static CAResult_t CALEAdapterServerReceivedData(const char *remoteAddress,
+                                                const uint8_t *data,
+                                                uint32_t dataLength,
+                                                uint32_t *sentLength);
+
+/**
+ * This function will receive the data from the GattClient and add the
+ * data into the Client receiver queue.
+ *
+ * @param[in] remoteAddress Remote address of the device from where
+ *                          data is received.
+ * @param[in] data          Actual data recevied from the remote
+ *                          device.
+ * @param[in] dataLength    Length of the data received from the
+ *                          remote device.
+ * @param[in] sentLength    Length of the data sent from the remote
+ *                          device.
+ *
+ * @return ::CA_STATUS_OK or Appropriate error code.
+ * @retval ::CA_STATUS_OK  Successful.
+ * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
+ * @retval ::CA_STATUS_FAILED Operation failed.
+ */
+static CAResult_t CALEAdapterClientReceivedData(const char *remoteAddress,
+                                                const uint8_t *data,
+                                                uint32_t dataLength,
+                                                uint32_t *sentLength);
+
+/**
+ * Set the NetworkPacket received callback to CA layer from adapter
+ * layer.
+ *
+ * @param[in] callback Callback handle sent from the upper layer.
+ */
+static void CASetLEReqRespAdapterCallback(CANetworkPacketReceivedCallback callback);
+
+/**
+ * Push the data from CA layer to the Sender processor queue.
+ *
+ * @param[in] remoteEndpoint Remote endpoint information of the
+ *                           server.
+ * @param[in] data           Data to be transmitted from LE.
+ * @param[in] dataLen        Length of the Data being transmitted.
+ *
+ * @return ::CA_STATUS_OK or Appropriate error code.
+ * @retval ::CA_STATUS_OK  Successful.
+ * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
+ * @retval ::CA_STATUS_FAILED Operation failed.
+ */
+static CAResult_t CALEAdapterServerSendData(const CAEndpoint_t *remoteEndpoint,
+                                            const uint8_t *data,
+                                            uint32_t dataLen);
+
+/**
+ * Push the data from CA layer to the Sender processor queue.
+ *
+ * @param[in] remoteEndpoint Remote endpoint information of the
+ *                           server.
+ * @param[in] data           Data to be transmitted from LE.
+ * @param[in] dataLen        Length of the Data being transmitted.
+ *
+ * @return ::CA_STATUS_OK or Appropriate error code.
+ * @retval ::CA_STATUS_OK  Successful.
+ * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
+ * @retval ::CA_STATUS_FAILED Operation failed.
+ */
+static CAResult_t CALEAdapterClientSendData(const CAEndpoint_t *remoteEndpoint,
+                                            const uint8_t *data,
+                                            uint32_t dataLen);
+
 CAResult_t CAInitializeLE(CARegisterConnectivityCallback registerCallback,
                           CANetworkPacketReceivedCallback reqRespCallback,
                           CANetworkChangeCallback netCallback,
@@ -1670,7 +1670,7 @@ CAResult_t CAInitializeLE(CARegisterConnectivityCallback registerCallback,
 
 static CAResult_t CAStartLE()
 {
-    OIC_LOG(DEBUG, CALEADAPTER_TAG, __func__);
+    OIC_LOG(DEBUG, CALEADAPTER_TAG, "CAStartLE");
 
     return CAStartLEAdapter();
 }
index a971465..807f1d9 100644 (file)
@@ -219,8 +219,8 @@ void CAStartBleGattServerThread(void *data)
         return;
     }
 
-    char *charReadUUID = CA_GATT_RESPONSE_CHRC_UUID;
-    char charReadValue[] = {33, 44, 55, 66}; // These are initial random values
+    static const char charReadUUID[] = CA_GATT_RESPONSE_CHRC_UUID;
+    uint8_t charReadValue[] = {33, 44, 55, 66}; // These are initial random values
 
     ret = CAAddNewCharacteristicsToGattServer(g_gattSvcPath, charReadUUID, charReadValue,
             CA_BLE_INITIAL_BUF_SIZE, true); // For Read Characteristics.
@@ -232,8 +232,8 @@ void CAStartBleGattServerThread(void *data)
         return;
     }
 
-    char *charWriteUUID = CA_GATT_REQUEST_CHRC_UUID;
-    char charWriteValue[] = {33, 44, 55, 66}; // These are initial random values
+    static const char charWriteUUID[] = CA_GATT_REQUEST_CHRC_UUID;
+    uint8_t charWriteValue[] = {33, 44, 55, 66}; // These are initial random values
 
 
     ret = CAAddNewCharacteristicsToGattServer(g_gattSvcPath, charWriteUUID, charWriteValue,
@@ -592,7 +592,7 @@ void CABleGattRemoteCharacteristicWriteCb(char *charPath,
 
     OIC_LOG_V(DEBUG,
               TZ_BLE_SERVER_TAG,
-              "charPath = [%s] charValue = [%x] len [%d]",
+              "charPath = [%s] charValue = [%p] len [%d]",
               charPath,
               charValue,
               charValueLen);
@@ -647,12 +647,12 @@ CAResult_t CARegisterBleServicewithGattServer(const char *svcPath)
 }
 
 CAResult_t CAAddNewCharacteristicsToGattServer(const char *svcPath, const char *charUUID,
-        const char *charValue, int charValueLen, bool read)
+        const uint8_t *charValue, int charValueLen, bool read)
 {
 
     OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "IN");
 
-    char *charFlags[1];
+    const char *charFlags[1];
     if(read)
     {
         charFlags[0] = "notify";
@@ -665,8 +665,14 @@ CAResult_t CAAddNewCharacteristicsToGattServer(const char *svcPath, const char *
     size_t flagLen = sizeof(charFlags) / sizeof(charFlags[0]);
 
     char *charPath = NULL;
-    int ret = bt_gatt_add_characteristic(charUUID, charValue, charValueLen, charFlags, flagLen,
-                  svcPath, &charPath);
+    int ret =
+        bt_gatt_add_characteristic(charUUID,
+                                   (const char *) charValue,
+                                   charValueLen,
+                                   charFlags,
+                                   flagLen,
+                                   svcPath,
+                                   &charPath);
 
     if (0 != ret || NULL == charPath)
     {
@@ -713,7 +719,7 @@ CAResult_t CARemoveCharacteristicsFromGattServer(const char *charPath)
 }
 
 CAResult_t CAUpdateCharacteristicsToGattClient(const char *address,
-                                               const char *charValue,
+                                               const uint8_t *charValue,
                                                uint32_t charValueLen)
 {
     OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "IN");
@@ -733,7 +739,7 @@ CAResult_t CAUpdateCharacteristicsToGattClient(const char *address,
         return CA_STATUS_FAILED;
     }
 
-    char *data = (char *) OICCalloc(sizeof(char), (charValueLen + 1));
+    char *data = OICCalloc(charValueLen, 1);
     if (NULL == data)
     {
         OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "malloc failed!");
@@ -741,12 +747,16 @@ CAResult_t CAUpdateCharacteristicsToGattClient(const char *address,
         return CA_STATUS_FAILED;
     }
 
-    OICStrcpy(data, charValueLen + 1, charValue);
+    memcpy(data, charValue, charValueLen);   // Binary data
 
-    OIC_LOG_V(DEBUG, TZ_BLE_SERVER_TAG, "updating characteristics char [%s] data [%s] dataLen [%d]",
+    OIC_LOG_V(DEBUG, TZ_BLE_SERVER_TAG, "updating characteristics char [%s] data [%p] dataLen [%u]",
               (const char *)g_gattReadCharPath, data, charValueLen);
 
-    int ret =  bt_gatt_update_characteristic(g_gattReadCharPath, data, charValueLen, address);
+    int ret =
+        bt_gatt_update_characteristic(g_gattReadCharPath,
+                                      data,
+                                      charValueLen,
+                                      address);
     if (0 != ret)
     {
         OIC_LOG_V(ERROR, TZ_BLE_SERVER_TAG,
@@ -763,7 +773,7 @@ CAResult_t CAUpdateCharacteristicsToGattClient(const char *address,
     return CA_STATUS_OK;
 }
 
-CAResult_t CAUpdateCharacteristicsToAllGattClients(const char *charValue, uint32_t charValueLen)
+CAResult_t CAUpdateCharacteristicsToAllGattClients(const uint8_t *charValue, uint32_t charValueLen)
 {
     OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "IN");
 
@@ -778,7 +788,7 @@ CAResult_t CAUpdateCharacteristicsToAllGattClients(const char *charValue, uint32
         return CA_STATUS_FAILED;
     }
 
-    char *data = (char *) OICMalloc(sizeof(char) * (charValueLen + 1));
+    char *data = OICMalloc(charValueLen);
     if (NULL == data)
     {
         OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "malloc failed!");
@@ -786,12 +796,16 @@ CAResult_t CAUpdateCharacteristicsToAllGattClients(const char *charValue, uint32
         return CA_STATUS_FAILED;
     }
 
-    OICStrcpy(data, charValueLen + 1, charValue);
+    memcpy(data, charValue, charValueLen);   // Binary data
 
-    OIC_LOG_V(DEBUG, TZ_BLE_SERVER_TAG, "updating characteristics char [%s] data [%s] dataLen [%d]",
+    OIC_LOG_V(DEBUG, TZ_BLE_SERVER_TAG, "updating characteristics char [%s] data [%p] dataLen [%u]",
               (const char *)g_gattReadCharPath, data, charValueLen);
 
-    int ret =  bt_gatt_update_characteristic(g_gattReadCharPath, data, charValueLen, NULL);
+    int ret =
+        bt_gatt_update_characteristic(g_gattReadCharPath,
+                                      data,
+                                      charValueLen,
+                                      NULL);
     if (0 != ret)
     {
         OIC_LOG_V(ERROR, TZ_BLE_SERVER_TAG,
index c016654..80cd517 100644 (file)
@@ -2004,22 +2004,6 @@ CAData_t *CACloneCAData(const CAData_t *data)
         clone->remoteEndpoint = CACloneEndpoint(data->remoteEndpoint);
     }
 
-    if (NULL != data->options && 0 < data->numOptions)
-    {
-        // copy data
-        CAHeaderOption_t *headerOption = (CAHeaderOption_t *) OICMalloc(sizeof(CAHeaderOption_t)
-                                                                        * data->numOptions);
-        if (NULL == headerOption)
-        {
-            OIC_LOG(ERROR, TAG, "Out of memory");
-            CADestroyDataSet(clone);
-            return NULL;
-        }
-        memcpy(headerOption, data->options, sizeof(CAHeaderOption_t) * data->numOptions);
-
-        clone->options = headerOption;
-    }
-
     return clone;
 }
 
@@ -2475,8 +2459,8 @@ CABlockData_t *CACreateNewBlockData(const CAData_t *sendData)
 
     ca_mutex_lock(g_context.blockDataListMutex);
 
-    CAResult_t res = u_arraylist_add(g_context.dataList, (void *) data);
-    if (CA_STATUS_OK != res)
+    bool res = u_arraylist_add(g_context.dataList, (void *) data);
+    if (!res)
     {
         OIC_LOG(ERROR, TAG, "add has failed");
         CADestroyBlockID(data->blockDataId);
@@ -2558,7 +2542,6 @@ void CADestroyDataSet(CAData_t* data)
     CAFreeEndpoint(data->remoteEndpoint);
     CADestroyRequestInfoInternal(data->requestInfo);
     CADestroyResponseInfoInternal(data->responseInfo);
-    OICFree(data->options);
     OICFree(data);
 }
 
index 9df1da3..9b1f8d4 100644 (file)
@@ -123,14 +123,14 @@ CAResult_t CASetAdapterRAInfo(const CARAInfo_t *caraInfo)
 }
 #endif
 
-static void CAReceivedPacketCallback(const CAEndpoint_t *endpoint, const void *data, uint32_t dataLen)
+static void CAReceivedPacketCallback(const CASecureEndpoint_t *sep,
+                                     const void *data, uint32_t dataLen)
 {
     OIC_LOG(DEBUG, TAG, "IN");
 
-    // Call the callback.
     if (g_networkPacketReceivedCallback != NULL)
     {
-        g_networkPacketReceivedCallback(endpoint, data, dataLen);
+        g_networkPacketReceivedCallback(sep, data, dataLen);
     }
     else
     {
index 38b185d..0742377 100644 (file)
@@ -71,8 +71,9 @@ static void CAErrorHandler(const CAEndpoint_t *endpoint,
                            const void *data, uint32_t dataLen,
                            CAResult_t result);
 
-static CAData_t* CAGenerateHandlerData(const CAEndpoint_t *endpoint, const void *data,
-                                       CADataType_t dataType);
+static CAData_t* CAGenerateHandlerData(const CAEndpoint_t *endpoint,
+                                       const CARemoteId_t *identity,
+                                       const void *data, CADataType_t dataType);
 
 static void CASendErrorInfo(const CAEndpoint_t *endpoint, const CAInfo_t *info,
                             CAResult_t result);
@@ -82,7 +83,7 @@ static void CAProcessReceivedData(CAData_t *data);
 #endif
 static void CADestroyData(void *data, uint32_t size);
 static void CALogPayloadInfo(CAInfo_t *info);
-static bool CADropSecondRequest(const CAEndpoint_t *endpoint, uint16_t messageId);
+static bool CADropSecondMessage(CAHistory_t *history, const CAEndpoint_t *endpoint, uint16_t id);
 
 #ifdef WITH_BWT
 void CAAddDataToSendThread(CAData_t *data)
@@ -111,7 +112,7 @@ void CAAddDataToReceiveThread(CAData_t *data)
 static bool CAIsSelectedNetworkAvailable()
 {
     u_arraylist_t *list = CAGetSelectedNetworkList();
-    if (!list || list->length == 0)
+    if (!list || u_arraylist_length(list) == 0)
     {
         OIC_LOG(ERROR, TAG, "No selected network");
         return false;
@@ -120,7 +121,9 @@ static bool CAIsSelectedNetworkAvailable()
     return true;
 }
 
-static CAData_t* CAGenerateHandlerData(const CAEndpoint_t *endpoint, const void *data, CADataType_t dataType)
+static CAData_t* CAGenerateHandlerData(const CAEndpoint_t *endpoint,
+                                       const CARemoteId_t *identity,
+                                       const void *data, CADataType_t dataType)
 {
     OIC_LOG(DEBUG, TAG, "CAGenerateHandlerData IN");
     CAInfo_t *info = NULL;
@@ -164,6 +167,10 @@ static CAData_t* CAGenerateHandlerData(const CAEndpoint_t *endpoint, const void
         }
         cadata->responseInfo = resInfo;
         info = &resInfo->info;
+        if (identity)
+        {
+            info->identity = *identity;
+        }
         OIC_LOG(DEBUG, TAG, "Response Info :");
         CALogPayloadInfo(info);
     }
@@ -188,7 +195,7 @@ static CAData_t* CAGenerateHandlerData(const CAEndpoint_t *endpoint, const void
             return NULL;
         }
 
-        if (CADropSecondRequest(endpoint, reqInfo->info.messageId))
+        if (CADropSecondMessage(&caglobals.ca.requestHistory, endpoint, reqInfo->info.messageId))
         {
             OIC_LOG(ERROR, TAG, "Second Request with same Token, Drop it");
             CAFreeEndpoint(ep);
@@ -199,6 +206,10 @@ static CAData_t* CAGenerateHandlerData(const CAEndpoint_t *endpoint, const void
 
         cadata->requestInfo = reqInfo;
         info = &reqInfo->info;
+        if (identity)
+        {
+            info->identity = *identity;
+        }
         OIC_LOG(DEBUG, TAG, "Request Info :");
         CALogPayloadInfo(info);
    }
@@ -225,6 +236,10 @@ static CAData_t* CAGenerateHandlerData(const CAEndpoint_t *endpoint, const void
 
         cadata->errorInfo = errorInfo;
         info = &errorInfo->info;
+        if (identity)
+        {
+            info->identity = *identity;
+        }
         OIC_LOG(DEBUG, TAG, "error Info :");
         CALogPayloadInfo(info);
     }
@@ -330,7 +345,6 @@ static void CADestroyData(void *data, uint32_t size)
         CADestroyErrorInfoInternal(cadata->errorInfo);
     }
 
-    OICFree(cadata->options);
     OICFree(cadata);
     OIC_LOG(DEBUG, TAG, "CADestroyData OUT");
 }
@@ -548,47 +562,55 @@ static void CASendThreadProcess(void *threadData)
 /*
  * If a second message arrives with the same token and the other address
  * family, drop it.  Typically, IPv6 beats IPv4, so the IPv4 message is dropped.
- * This can be made more robust (for instance, another message could arrive
- * in between), but it is good enough for now.
  */
-static bool CADropSecondRequest(const CAEndpoint_t *endpoint, uint16_t messageId)
+static bool CADropSecondMessage(CAHistory_t *history, const CAEndpoint_t *ep, uint16_t id)
 {
-    if (!endpoint)
+    if (!ep)
     {
         return true;
     }
-    if (endpoint->adapter != CA_ADAPTER_IP)
+    if (ep->adapter != CA_ADAPTER_IP)
+    {
+        return false;
+    }
+    if (!caglobals.ip.dualstack)
     {
         return false;
     }
 
     bool ret = false;
-    CATransportFlags_t familyFlags = endpoint->flags & CA_IPFAMILY_MASK;
+    CATransportFlags_t familyFlags = ep->flags & CA_IPFAMILY_MASK;
 
-    if (messageId == caglobals.ca.previousRequestMessageId)
+    for (size_t i = 0; i < sizeof(history->items) / sizeof(history->items[0]); i++)
     {
-        if ((familyFlags ^ caglobals.ca.previousRequestFlags) == CA_IPFAMILY_MASK)
+        CAHistoryItem_t *item = &(history->items[i]);
+        if (id == item->messageId)
         {
-            if (familyFlags & CA_IPV6)
-            {
-                OIC_LOG(INFO, TAG, "IPv6 duplicate response ignored");
-            }
-            else
+            if ((familyFlags ^ item->flags) == CA_IPFAMILY_MASK)
             {
-                OIC_LOG(INFO, TAG, "IPv4 duplicate response ignored");
+                OIC_LOG_V(INFO, TAG, "IPv%c duplicate message ignored",
+                                            familyFlags & CA_IPV6 ? '6' : '4');
+                ret = true;
+                break;
             }
-            ret = true;
         }
     }
-    caglobals.ca.previousRequestFlags = familyFlags;
-    caglobals.ca.previousRequestMessageId = messageId;
+
+    history->items[history->nextIndex].flags = familyFlags;
+    history->items[history->nextIndex].messageId = id;
+    if (++history->nextIndex >= HISTORYSIZE)
+    {
+        history->nextIndex = 0;
+    }
+
     return ret;
 }
 
-static void CAReceivedPacketCallback(const CAEndpoint_t *remoteEndpoint, const void *data, uint32_t dataLen)
+static void CAReceivedPacketCallback(const CASecureEndpoint_t *sep,
+                                     const void *data, uint32_t dataLen)
 {
     OIC_LOG(DEBUG, TAG, "IN");
-    VERIFY_NON_NULL_VOID(remoteEndpoint, TAG, "remoteEndpoint");
+    VERIFY_NON_NULL_VOID(sep, TAG, "remoteEndpoint");
     VERIFY_NON_NULL_VOID(data, TAG, "data");
 
     uint32_t code = CA_NOT_FOUND;
@@ -604,7 +626,7 @@ static void CAReceivedPacketCallback(const CAEndpoint_t *remoteEndpoint, const v
     OIC_LOG_V(DEBUG, TAG, "code = %d", code);
     if (CA_GET == code || CA_POST == code || CA_PUT == code || CA_DELETE == code)
     {
-        cadata = CAGenerateHandlerData(remoteEndpoint, pdu, CA_REQUEST_DATA);
+        cadata = CAGenerateHandlerData(&(sep->endpoint), &(sep->identity), pdu, CA_REQUEST_DATA);
         if (!cadata)
         {
             OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, CAGenerateHandlerData failed!");
@@ -614,7 +636,7 @@ static void CAReceivedPacketCallback(const CAEndpoint_t *remoteEndpoint, const v
     }
     else
     {
-        cadata = CAGenerateHandlerData(remoteEndpoint, pdu, CA_RESPONSE_DATA);
+        cadata = CAGenerateHandlerData(&(sep->endpoint), &(sep->identity), pdu, CA_RESPONSE_DATA);
         if (!cadata)
         {
             OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, CAGenerateHandlerData failed!");
@@ -652,24 +674,24 @@ static void CAReceivedPacketCallback(const CAEndpoint_t *remoteEndpoint, const v
     CAProcessReceivedData(cadata);
 #else
 #ifdef WITH_BWT
-        if (CA_ADAPTER_GATT_BTLE != remoteEndpoint->adapter)
+    if (CA_ADAPTER_GATT_BTLE != sep->endpoint.adapter)
+    {
+        CAResult_t res = CAReceiveBlockWiseData(pdu, &(sep->endpoint), cadata, dataLen);
+        if (CA_NOT_SUPPORTED == res)
         {
-            CAResult_t res = CAReceiveBlockWiseData(pdu, remoteEndpoint, cadata, dataLen);
-            if (CA_NOT_SUPPORTED == res)
-            {
-                OIC_LOG(ERROR, TAG, "this message does not have block option");
-                CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
-            }
-            else
-            {
-                CADestroyData(cadata, sizeof(CAData_t));
-            }
+            OIC_LOG(ERROR, TAG, "this message does not have block option");
+            CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
         }
         else
-#endif
         {
-            CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
+            CADestroyData(cadata, sizeof(CAData_t));
         }
+    }
+    else
+#endif
+    {
+        CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
+    }
 #endif
 
     coap_delete_pdu(pdu);
@@ -746,7 +768,6 @@ static CAData_t* CAPrepareSendData(const CAEndpoint_t *endpoint, const void *sen
                                    CADataType_t dataType)
 {
     OIC_LOG(DEBUG, TAG, "CAPrepareSendData IN");
-    CAInfo_t *info = NULL;
 
     CAData_t *cadata = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
     if (!cadata)
@@ -768,7 +789,6 @@ static CAData_t* CAPrepareSendData(const CAEndpoint_t *endpoint, const void *sen
         }
 
         cadata->type = request->isMulticast ? SEND_TYPE_MULTICAST : SEND_TYPE_UNICAST;
-        info = &request->info;
         cadata->requestInfo =  request;
     }
     else if(CA_RESPONSE_DATA == dataType)
@@ -784,7 +804,6 @@ static CAData_t* CAPrepareSendData(const CAEndpoint_t *endpoint, const void *sen
         }
 
         cadata->type = SEND_TYPE_UNICAST;
-        info = &response->info;
         cadata->responseInfo = response;
     }
     else
@@ -794,25 +813,6 @@ static CAData_t* CAPrepareSendData(const CAEndpoint_t *endpoint, const void *sen
         return NULL;
     }
 
-    if (NULL != info->options && 0 < info->numOptions)
-    {
-        uint8_t numOptions = info->numOptions;
-        // copy data
-        CAHeaderOption_t *headerOption = (CAHeaderOption_t *) OICMalloc(sizeof(CAHeaderOption_t)
-                                                                        * numOptions);
-        if(!headerOption)
-        {
-            OIC_LOG(ERROR, TAG, "memory allocation failed");
-            CADestroyData(cadata, sizeof(CAData_t));
-            return NULL;
-        }
-
-        memcpy(headerOption, info->options, sizeof(CAHeaderOption_t) * numOptions);
-
-        cadata->options = headerOption;
-        cadata->numOptions = numOptions;
-    }
-
     CAEndpoint_t* ep = CACloneEndpoint(endpoint);
     if (!ep)
     {
@@ -1149,7 +1149,7 @@ static void CALogPayloadInfo(CAInfo_t *info)
 {
     if(info)
     {
-        if (!info->options)
+        if (info->options)
         {
             for (uint32_t i = 0; i < info->numOptions; i++)
             {
@@ -1159,13 +1159,13 @@ static void CALogPayloadInfo(CAInfo_t *info)
             }
         }
 
-        if (!info->payload)
+        if (info->payload)
         {
             OIC_LOG_V(DEBUG, TAG, "payload: %p(%u)", info->payload,
                       info->payloadSize);
         }
 
-        if (!info->token)
+        if (info->token)
         {
             OIC_LOG(DEBUG, TAG, "token:");
             OIC_LOG_BUFFER(DEBUG, TAG, (const uint8_t *) info->token,
@@ -1200,7 +1200,7 @@ void CAErrorHandler(const CAEndpoint_t *endpoint,
         return;
     }
 
-    CAData_t *cadata = CAGenerateHandlerData(endpoint, pdu, CA_ERROR_DATA);
+    CAData_t *cadata = CAGenerateHandlerData(endpoint, NULL, pdu, CA_ERROR_DATA);
     if(!cadata)
     {
         OIC_LOG(ERROR, TAG, "CAErrorHandler, CAGenerateHandlerData failed!");
index 01e9d4d..d36d378 100644 (file)
@@ -50,7 +50,7 @@ CAResult_t CAAddNetworkType(CATransportAdapter_t transportType)
             return CA_MEMORY_ALLOC_FAILED;
         }
     }
-    CAResult_t res = CA_STATUS_OK;
+    bool res = true;
     switch (transportType)
     {
         case CA_ADAPTER_IP:
@@ -111,15 +111,15 @@ CAResult_t CAAddNetworkType(CATransportAdapter_t transportType)
             break;
     }
 
-    if (CA_STATUS_OK != res)
+    if (!res)
     {
         OIC_LOG_V(ERROR, TAG, "Add arraylist failed[Err code: %d]", res);
-        return res;
+        return CA_STATUS_FAILED;
     }
     // start selected interface adapter
-    res = CAStartAdapter(transportType);
+    CAResult_t result = CAStartAdapter(transportType);
     OIC_LOG(DEBUG, TAG, "OUT");
-    return res;
+    return result;
 
 exit:
     OIC_LOG(DEBUG, TAG, "This adapter is already enabled");
index a418a03..b140264 100644 (file)
@@ -229,6 +229,14 @@ coap_pdu_t *CAParsePDU(const char *data, uint32_t length, uint32_t *outCode)
         return NULL;
     }
 
+    if (outpdu->hdr->version != COAP_DEFAULT_VERSION)
+    {
+        OIC_LOG_V(ERROR, TAG, "coap version is not available : %d",
+                  outpdu->hdr->version);
+        coap_delete_pdu(outpdu);
+        return NULL;
+    }
+
     if (outCode)
     {
         (*outCode) = (uint32_t) CA_RESPONSE_CODE(outpdu->hdr->code);
old mode 100644 (file)
new mode 100755 (executable)
index b15502c..7896334
 #include "logger.h"
 #include "oic_malloc.h"
 #include "oic_string.h"
+#include "org_iotivity_ca_CaIpInterface.h"
 
 #define TAG "IP_MONITOR"
 
-char *getHostIPAddress(const char *ifa_name) {
-    static char address[INET_ADDRSTRLEN] = {};
-    memset(&address, 0, INET_ADDRSTRLEN);
-    struct ifreq ifr;
-    int sck, status, len = sizeof(ifr.ifr_name) - 1;
-    char *ip;
+static CAInterface_t *CANewInterfaceItem(int index, const char *name, int family,
+                                         uint32_t addr, int flags);
 
-    if ((sck = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
+static CAResult_t CAAddInterfaceItem(u_arraylist_t *iflist, int index,
+                            const char *name, int family, uint32_t addr, int flags);
+
+CAResult_t CAIPJniInit();
+
+#define MAX_INTERFACE_INFO_LENGTH 1024 // allows 32 interfaces from SIOCGIFCONF
+
+CAResult_t CAIPInitializeNetworkMonitor()
+{
+    return CAIPJniInit();
+}
+
+CAResult_t CAIPTerminateNetworkMonitor()
+{
+    return CA_STATUS_OK;
+}
+
+int CAGetPollingInterval(int interval)
+{
+    return interval;
+}
+
+CAInterface_t *CAFindInterfaceChange()
+{
+    char buf[MAX_INTERFACE_INFO_LENGTH] = { 0 };
+    struct ifconf ifc  = { .ifc_len = MAX_INTERFACE_INFO_LENGTH, .ifc_buf = buf };
+
+    int s = caglobals.ip.u6.fd != -1 ? caglobals.ip.u6.fd : caglobals.ip.u4.fd;
+    if (ioctl(s, SIOCGIFCONF, &ifc) < 0)
+    {
+        OIC_LOG_V(ERROR, TAG, "SIOCGIFCONF failed: %s", strerror(errno));
         return NULL;
     }
 
-    strncpy(ifr.ifr_name, ifa_name, len);
-    ifr.ifr_name[len] = '\0';
-    if ((status = ioctl(sck, SIOCGIFADDR, &ifr)) < 0) {
-        close(sck);
+    CAInterface_t *foundNewInterface = NULL;
+
+    struct ifreq* ifr = ifc.ifc_req;
+    size_t interfaces = ifc.ifc_len / sizeof (ifc.ifc_req[0]);
+    size_t ifreqsize = ifc.ifc_len;
+
+    CAIfItem_t *previous = (CAIfItem_t *)OICMalloc(ifreqsize);
+    if (!previous)
+    {
+        OIC_LOG(ERROR, TAG, "OICMalloc failed");
         return NULL;
     }
-    close(sck);
-    ip = inet_ntoa(((struct sockaddr_in *)(&ifr.ifr_addr))->sin_addr);
-    len = sizeof(address) - 1;
-    strncpy(address, ip, len);
-    address[len] = '\0';
-    return address;
-}
 
-u_arraylist_t *CAIPGetInterfaceInformation(int desiredIndex)
-{
-    if (desiredIndex < 0)
+    memcpy(previous, caglobals.ip.nm.ifItems, ifreqsize);
+    size_t numprevious = caglobals.ip.nm.numIfItems;
+
+    if (ifreqsize > caglobals.ip.nm.sizeIfItems)
     {
-        OIC_LOG_V(ERROR, TAG, "invalid index : %d", desiredIndex);
-        return NULL;
+
+        CAIfItem_t *items = (CAIfItem_t *)OICRealloc(caglobals.ip.nm.ifItems, ifreqsize);
+        if (!items)
+        {
+            OIC_LOG(ERROR, TAG, "OICRealloc failed");
+            OICFree(previous);
+            return NULL;
+        }
+        caglobals.ip.nm.ifItems = items;
+        caglobals.ip.nm.sizeIfItems = ifreqsize;
     }
 
+    caglobals.ip.nm.numIfItems = 0;
+    for (size_t i = 0; i < interfaces; i++)
+    {
+        struct ifreq* item = &ifr[i];
+        char *name = item->ifr_name;
+        struct sockaddr_in *sa4 = (struct sockaddr_in *)&item->ifr_addr;
+        uint32_t ipv4addr = sa4->sin_addr.s_addr;
+
+        if (ioctl(s, SIOCGIFFLAGS, item) < 0)
+        {
+            OIC_LOG_V(ERROR, TAG, "SIOCGIFFLAGS failed: %s", strerror(errno));
+            continue;
+        }
+        int16_t flags = item->ifr_flags;
+        if ((flags & IFF_LOOPBACK) || !(flags & IFF_RUNNING))
+        {
+            continue;
+        }
+        if (ioctl(s, SIOCGIFINDEX, item) < 0)
+        {
+            OIC_LOG_V(ERROR, TAG, "SIOCGIFINDEX failed: %s", strerror(errno));
+            continue;
+        }
+
+        int ifIndex = item->ifr_ifindex;
+        caglobals.ip.nm.ifItems[i].ifIndex = ifIndex;  // refill interface list
+        caglobals.ip.nm.numIfItems++;
+
+        if (foundNewInterface)
+        {
+            continue;   // continue updating interface list
+        }
+
+        // see if this interface didn't previously exist
+        bool found = false;
+        for (size_t j = 0; j < numprevious; j++)
+        {
+            if (ifIndex == previous[j].ifIndex)
+            {
+                found = true;
+                break;
+            }
+        }
+        if (found)
+        {
+            OIC_LOG_V(INFO, TAG, "Interface found: %s", name);
+            continue;
+        }
+
+        foundNewInterface = CANewInterfaceItem(ifIndex, name, AF_INET, ipv4addr, flags);
+    }
+
+    OICFree(previous);
+    return foundNewInterface;
+}
+
+u_arraylist_t *CAIPGetInterfaceInformation(int desiredIndex)
+{
     u_arraylist_t *iflist = u_arraylist_create();
     if (!iflist)
     {
@@ -78,34 +171,81 @@ u_arraylist_t *CAIPGetInterfaceInformation(int desiredIndex)
         return NULL;
     }
 
-    char* ipAddr = getHostIPAddress("wlan0");
-    if (NULL == ipAddr)
+    char buf[MAX_INTERFACE_INFO_LENGTH] = { 0 };
+    struct ifconf ifc = { .ifc_len = MAX_INTERFACE_INFO_LENGTH, .ifc_buf = buf };
+
+    int s = caglobals.ip.u6.fd != -1 ? caglobals.ip.u6.fd : caglobals.ip.u4.fd;
+    if (ioctl(s, SIOCGIFCONF, &ifc) < 0)
     {
-        OIC_LOG_V(ERROR, TAG, "Failed to get ifaddrs: %s", strerror(errno));
+        OIC_LOG_V(ERROR, TAG, "SIOCGIFCONF failed: %s", strerror(errno));
         u_arraylist_destroy(iflist);
         return NULL;
     }
-    OIC_LOG_V(DEBUG, TAG, "Got ifaddrs:: %s", ipAddr);
 
-    struct in_addr inaddr;
-    inet_pton(AF_INET, ipAddr, &(inaddr));
+    struct ifreq* ifr = ifc.ifc_req;
+    size_t interfaces = ifc.ifc_len / sizeof (ifc.ifc_req[0]);
+    size_t ifreqsize = ifc.ifc_len;
 
-    CAInterface_t *ifitem = (CAInterface_t *)OICCalloc(1, sizeof(CAInterface_t));;
-    OICStrcpy(ifitem->name, INTERFACE_NAME_MAX, "wlan0");
-    ifitem->index = 0; //if_nametoindex("wlan0");
-    ifitem->family = AF_INET; //we support ipv4 only
-    ifitem->ipv4addr = inaddr.s_addr;
-    ifitem->flags = IFF_UP|IFF_RUNNING;
-
-    CAResult_t result = u_arraylist_add(iflist, ifitem);
-    if (CA_STATUS_OK != result)
+    if (ifreqsize > caglobals.ip.nm.sizeIfItems)
     {
-        OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
-        goto exit;
+        CAIfItem_t *items = (CAIfItem_t *)OICRealloc(caglobals.ip.nm.ifItems, ifreqsize);
+        if (!items)
+        {
+            OIC_LOG(ERROR, TAG, "OICRealloc failed");
+            goto exit;
+        }
+        caglobals.ip.nm.ifItems = items;
+        caglobals.ip.nm.sizeIfItems = ifreqsize;
     }
 
-    OIC_LOG_V(ERROR, TAG, "Added interface: %s (%d)", ifitem->name, ifitem->family);
+    caglobals.ip.nm.numIfItems = 0;
+    for (size_t i = 0; i < interfaces; i++)
+    {
+        CAResult_t result = CA_STATUS_OK;
+        struct ifreq* item = &ifr[i];
+        char *name = item->ifr_name;
+        struct sockaddr_in *sa4 = (struct sockaddr_in *)&item->ifr_addr;
+        uint32_t ipv4addr = sa4->sin_addr.s_addr;
+
+        if (ioctl(s, SIOCGIFFLAGS, item) < 0)
+        {
+            OIC_LOG_V(ERROR, TAG, "SIOCGIFFLAGS failed: %s", strerror(errno));
+            continue;
+        }
+        int16_t flags = item->ifr_flags;
+        if ((flags & IFF_LOOPBACK) || !(flags & IFF_RUNNING))
+        {
+            continue;
+        }
+        if (ioctl(s, SIOCGIFINDEX, item) < 0)
+        {
+            OIC_LOG_V(ERROR, TAG, "SIOCGIFINDEX failed: %s", strerror(errno));
+            continue;
+        }
+
+        int ifindex = item->ifr_ifindex;
+        caglobals.ip.nm.ifItems[i].ifIndex = ifindex;
+        caglobals.ip.nm.numIfItems++;
+
+        if (desiredIndex && (ifindex != desiredIndex))
+        {
+            continue;
+        }
 
+        // Add IPv4 interface
+        result = CAAddInterfaceItem(iflist, ifindex, name, AF_INET, ipv4addr, flags);
+        if (CA_STATUS_OK != result)
+        {
+            goto exit;
+        }
+
+        // Add IPv6 interface
+        result = CAAddInterfaceItem(iflist, ifindex, name, AF_INET6, ipv4addr, flags);
+        if (CA_STATUS_OK != result)
+        {
+            goto exit;
+        }
+    }
     return iflist;
 
 exit:
@@ -113,3 +253,131 @@ exit:
     return NULL;
 }
 
+static CAResult_t CAAddInterfaceItem(u_arraylist_t *iflist, int index,
+                            const char *name, int family, uint32_t addr, int flags)
+{
+    CAInterface_t *ifitem = CANewInterfaceItem(index, name, family, addr, flags);
+    if (!ifitem)
+    {
+        return CA_STATUS_FAILED;
+    }
+    bool result = u_arraylist_add(iflist, ifitem);
+    if (!result)
+    {
+        OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
+        OICFree(ifitem);
+        return CA_STATUS_FAILED;
+    }
+
+    return CA_STATUS_OK;
+}
+
+static CAInterface_t *CANewInterfaceItem(int index, const char *name, int family,
+                                         uint32_t addr, int flags)
+{
+    CAInterface_t *ifitem = (CAInterface_t *)OICCalloc(1, sizeof (CAInterface_t));
+    if (!ifitem)
+    {
+        OIC_LOG(ERROR, TAG, "Malloc failed");
+        return NULL;
+    }
+
+    OICStrcpy(ifitem->name, sizeof (ifitem->name), name);
+    ifitem->index = index;
+    ifitem->family = family;
+    ifitem->ipv4addr = addr;
+    ifitem->flags = flags;
+
+    return ifitem;
+}
+
+CAResult_t CAIPJniInit()
+{
+    OIC_LOG(DEBUG, TAG, "CAIPJniInit_IN");
+
+    JavaVM *jvm = CANativeJNIGetJavaVM();
+    if (!jvm)
+    {
+        OIC_LOG(ERROR, TAG, "Could not get JavaVM pointer");
+        return CA_STATUS_FAILED;
+    }
+
+    jobject context = CANativeJNIGetContext();
+    if (!context)
+    {
+        OIC_LOG(ERROR, TAG, "unable to get application context");
+        return CA_STATUS_FAILED;
+    }
+
+    JNIEnv* env;
+    if ((*jvm)->GetEnv(jvm, (void**) &env, JNI_VERSION_1_6) != JNI_OK)
+    {
+        OIC_LOG(ERROR, TAG, "Could not get JNIEnv pointer");
+        return CA_STATUS_FAILED;
+    }
+
+    jclass cls_Context = (*env)->FindClass(env, "android/content/Context");
+    if (!cls_Context)
+    {
+        OIC_LOG(ERROR, TAG, "Could not get context object class");
+        return CA_STATUS_FAILED;
+    }
+
+    jmethodID mid_getApplicationContext = (*env)->GetMethodID(env, cls_Context,
+                                                                "getApplicationContext",
+                                                                "()Landroid/content/Context;");
+    if (!mid_getApplicationContext)
+    {
+        OIC_LOG(ERROR, TAG, "Could not get getApplicationContext method");
+        return CA_STATUS_FAILED;
+    }
+
+    jobject jApplicationContext = (*env)->CallObjectMethod(env, context,
+                                                           mid_getApplicationContext);
+    if (!jApplicationContext)
+    {
+        OIC_LOG(ERROR, TAG, "Could not get application context");
+        return CA_STATUS_FAILED;
+    }
+
+    jclass cls_CaIpInterface = (*env)->FindClass(env, "org/iotivity/ca/CaIpInterface");
+    if (!cls_CaIpInterface)
+    {
+        OIC_LOG(ERROR, TAG, "Could not get CaIpInterface class");
+        return CA_STATUS_FAILED;
+    }
+
+    jmethodID mid_CaIpInterface_ctor = (*env)->GetMethodID(env, cls_CaIpInterface, "<init>",
+                                                                   "(Landroid/content/Context;)V");
+    if (!mid_CaIpInterface_ctor)
+    {
+        OIC_LOG(ERROR, TAG, "Could not get CaIpInterface constructor method");
+        return CA_STATUS_FAILED;
+    }
+
+    (*env)->NewObject(env, cls_CaIpInterface, mid_CaIpInterface_ctor, jApplicationContext);
+    OIC_LOG(DEBUG, TAG, "Create CaIpInterface instance, success");
+
+    OIC_LOG(DEBUG, TAG, "CAIPJniInit_OUT");
+    return CA_STATUS_OK;
+}
+
+JNIEXPORT void JNICALL
+Java_org_iotivity_ca_CaIpInterface_caIpStateEnabled(JNIEnv *env, jclass class)
+{
+    (void)env;
+    (void)class;
+    OIC_LOG(DEBUG, TAG, "caIpStateEnabled");
+
+    CAWakeUpForChange();
+}
+
+JNIEXPORT void JNICALL
+Java_org_iotivity_ca_CaIpInterface_caIpStateDisabled(JNIEnv *env, jclass class)
+{
+    (void)env;
+    (void)class;
+    OIC_LOG(DEBUG, TAG, "caIpStateDisabled");
+
+    CAIPGetInterfaceInformation(0);
+}
index 243f328..06fca45 100644 (file)
 // defined & used (as-is defined in the linux socket headers).
 #define AF_INET (2)
 
+CAResult_t CAIPInitializeNetworkMonitor()
+{
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAIPTerminateNetworkMonitor()
+{
+    return CA_STATUS_OK;
+}
+
 /// Retrieves the IP address assigned to Arduino Ethernet shield
 void CAArduinoGetInterfaceAddress(uint32_t *address)
 {
@@ -64,7 +74,7 @@ void CAArduinoGetInterfaceAddress(uint32_t *address)
 
 u_arraylist_t *CAIPGetInterfaceInformation(int desiredIndex)
 {
-    CAResult_t result;
+    bool result = true;
 
     u_arraylist_t *iflist = u_arraylist_create();
     if (!iflist)
@@ -88,7 +98,7 @@ u_arraylist_t *CAIPGetInterfaceInformation(int desiredIndex)
     CAArduinoGetInterfaceAddress(&ifitem->ipv4addr);
 
     result = u_arraylist_add(iflist, ifitem);
-    if (CA_STATUS_OK != result)
+    if (!result)
     {
         OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
         goto exit;
index 92acb32..f35de3c 100644 (file)
 // defined & used (as-is defined in the linux socket headers).
 #define AF_INET (2)
 
+CAResult_t CAIPInitializeNetworkMonitor()
+{
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAIPTerminateNetworkMonitor()
+{
+    return CA_STATUS_OK;
+}
+
 /// Retrieves the IP address assigned to Arduino WiFi shield
 void CAArduinoGetInterfaceAddress(uint32_t *address)
 {
@@ -68,7 +78,7 @@ void CAArduinoGetInterfaceAddress(uint32_t *address)
 
 u_arraylist_t *CAIPGetInterfaceInformation(int desiredIndex)
 {
-    CAResult_t result = CA_STATUS_OK;
+    bool result = true;
 
     u_arraylist_t *iflist = u_arraylist_create();
     if (!iflist)
@@ -92,7 +102,7 @@ u_arraylist_t *CAIPGetInterfaceInformation(int desiredIndex)
     CAArduinoGetInterfaceAddress(&ifitem->ipv4addr);
 
     result = u_arraylist_add(iflist, ifitem);
-    if (CA_STATUS_OK != result)
+    if (!result)
     {
         OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
         goto exit;
index 099e6d3..74a51f6 100644 (file)
@@ -194,12 +194,10 @@ void CAPacketReceivedCallback(const char *ipAddress, const uint16_t port,
     OIC_LOG(DEBUG, TAG, "IN");
     if (g_packetReceivedCallback)
     {
-        CAEndpoint_t ep;
-        strncpy(ep.addr, ipAddress, MAX_ADDR_STR_SIZE_CA);
-        ep.port = port;
-        ep.flags = CA_IPV4;
-        ep.adapter = CA_ADAPTER_IP;
-        g_packetReceivedCallback(&ep, data, dataLength);
+        CASecureEndpoint_t sep =
+        {.endpoint = {.adapter = CA_ADAPTER_IP, .flags = CA_IPV4, .port = port}};
+        OICStrcpy(sep.endpoint.addr, sizeof(sep.endpoint.addr), ipAddress);
+        g_packetReceivedCallback(&sep, data, dataLength);
     }
     OIC_LOG(DEBUG, TAG, "OUT");
 }
index 0086b22..d537adc 100644 (file)
@@ -181,12 +181,11 @@ void CAPacketReceivedCallback(const char *ipAddress, const uint16_t port,
     OIC_LOG(DEBUG, TAG, "IN");
     if (gPacketReceivedCallback)
     {
-        CAEndpoint_t ep;
-        strncpy(ep.addr, ipAddress, MAX_ADDR_STR_SIZE_CA);
-        ep.port = port;
-        ep.flags = CA_IPV4;
-        ep.adapter = CA_ADAPTER_IP;
-        gPacketReceivedCallback(&ep, data, dataLength);
+        CASecureEndpoint_t sep =
+        {.endpoint = {.adapter = CA_ADAPTER_IP, .flags = CA_IPV4, .port = port}};
+
+        OICStrcpy(sep.endpoint.addr, sizeof(sep.endpoint.addr), ipAddress);
+        gPacketReceivedCallback(&sep, data, dataLength);
         OIC_LOG(DEBUG, TAG, "Notified network packet");
     }
     OIC_LOG(DEBUG, TAG, "OUT");
index 1579c03..f2ba419 100644 (file)
@@ -75,7 +75,7 @@ static CANetworkChangeCallback g_networkChangeCallback = NULL;
  */
 static CAErrorHandleCallback g_errorCallback = NULL;
 
-static void CAIPPacketReceivedCB(const CAEndpoint_t *endpoint,
+static void CAIPPacketReceivedCB(const CASecureEndpoint_t *endpoint,
                                  const void *data, uint32_t dataLength);
 #ifdef __WITH_DTLS__
 static void CAIPPacketSendCB(CAEndpoint_t *endpoint,
@@ -164,19 +164,20 @@ static void CAIPPacketSendCB(CAEndpoint_t *endpoint, const void *data, uint32_t
 }
 #endif
 
-void CAIPPacketReceivedCB(const CAEndpoint_t *endpoint, const void *data,
+
+void CAIPPacketReceivedCB(const CASecureEndpoint_t *sep, const void *data,
                           uint32_t dataLength)
 {
     OIC_LOG(DEBUG, TAG, "IN");
 
-    VERIFY_NON_NULL_VOID(endpoint, TAG, "ipAddress is NULL");
+    VERIFY_NON_NULL_VOID(sep, TAG, "sep is NULL");
     VERIFY_NON_NULL_VOID(data, TAG, "data is NULL");
 
-    OIC_LOG_V(DEBUG, TAG, "Address: %s, port:%d", endpoint->addr, endpoint->port);
+    OIC_LOG_V(DEBUG, TAG, "Address: %s, port:%d", sep->endpoint.addr, sep->endpoint.port);
 
     if (g_networkPacketCallback)
     {
-        g_networkPacketCallback(endpoint, data, dataLength);
+        g_networkPacketCallback(sep, data, dataLength);
     }
     OIC_LOG(DEBUG, TAG, "OUT");
 }
@@ -239,6 +240,7 @@ static void CAInitializeIPGlobals()
     }
     caglobals.ip.ipv6enabled = flags & CA_IPV6;
     caglobals.ip.ipv4enabled = flags & CA_IPV4;
+    caglobals.ip.dualstack = caglobals.ip.ipv6enabled && caglobals.ip.ipv4enabled;
 }
 
 CAResult_t CAInitializeIP(CARegisterConnectivityCallback registerCallback,
@@ -262,6 +264,7 @@ CAResult_t CAInitializeIP(CARegisterConnectivityCallback registerCallback,
     caglobals.ip.threadpool = handle;
 
     CAIPSetPacketReceiveCallback(CAIPPacketReceivedCB);
+    CAIPInitializeNetworkMonitor();
 #ifdef __WITH_DTLS__
     CAAdapterNetDtlsInit();
 
@@ -425,6 +428,8 @@ void CATerminateIP()
 {
     OIC_LOG(DEBUG, TAG, "IN");
 
+    CAIPTerminateNetworkMonitor();
+
 #ifdef __WITH_DTLS__
     CADTLSSetAdapterCallbacks(NULL, NULL, 0);
 #endif
index 3568b65..6ead6a4 100644 (file)
 
 #include "caipinterface.h"
 
-#ifndef __APPLE__
-#include <asm/types.h>
-#else
-    #ifndef IPV6_ADD_MEMBERSHIP
-        #define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP
-    #endif
-#endif
 #include <sys/types.h>
 #include <sys/socket.h>
 #include <stdio.h>
@@ -106,6 +99,7 @@ static void CAHandleNetlink();
 static void CAApplyInterfaces();
 static void CAFindReadyMessage();
 static void CASelectReturned(fd_set *readFds, int ret);
+static void CAProcessNewInterface(CAInterface_t *ifchanged);
 static CAResult_t CAReceiveMessage(int fd, CATransportFlags_t flags);
 
 #define SET(TYPE, FDS) \
@@ -203,6 +197,11 @@ static void CASelectReturned(fd_set *readFds, int ret)
         }
         else
         {
+            CAInterface_t *ifchanged = CAFindInterfaceChange();
+            if (ifchanged)
+            {
+                CAProcessNewInterface(ifchanged);
+            }
             break;
         }
 
@@ -230,20 +229,20 @@ static CAResult_t CAReceiveMessage(int fd, CATransportFlags_t flags)
         return CA_STATUS_FAILED;
     }
 
-    CAEndpoint_t ep = { .adapter = CA_ADAPTER_IP,
-                        .flags = flags };
+    CASecureEndpoint_t sep =
+    {.endpoint = {.adapter = CA_ADAPTER_IP, .flags = flags}};
 
     if (flags & CA_IPV6)
     {
-        ep.interface = ((struct sockaddr_in6 *)&srcAddr)->sin6_scope_id;
+        sep.endpoint.interface = ((struct sockaddr_in6 *)&srcAddr)->sin6_scope_id;
         ((struct sockaddr_in6 *)&srcAddr)->sin6_scope_id = 0;
     }
-    CAConvertAddrToName(&srcAddr, ep.addr, &ep.port);
+    CAConvertAddrToName(&srcAddr, sep.endpoint.addr, &sep.endpoint.port);
 
     if (flags & CA_SECURE)
     {
 #ifdef __WITH_DTLS__
-        int ret = CAAdapterNetDtlsDecrypt(&ep, (uint8_t *)recvBuffer, recvLen);
+        int ret = CAAdapterNetDtlsDecrypt(&sep, (uint8_t *)recvBuffer, recvLen);
         OIC_LOG_V(DEBUG, TAG, "CAAdapterNetDtlsDecrypt returns [%d]", ret);
 #else
         OIC_LOG(ERROR, TAG, "Encrypted message but no DTLS");
@@ -253,7 +252,7 @@ static CAResult_t CAReceiveMessage(int fd, CATransportFlags_t flags)
     {
         if (g_packetReceivedCallback)
         {
-            g_packetReceivedCallback(&ep, recvBuffer, recvLen);
+            g_packetReceivedCallback(&sep, recvBuffer, recvLen);
         }
     }
 
@@ -473,6 +472,8 @@ CAResult_t CAIPStartServer(const ca_thread_pool_t threadPool)
     // create source of network interface change notifications
     CAInitializeNetlink();
 
+    caglobals.ip.selectTimeout = CAGetPollingInterval(caglobals.ip.selectTimeout);
+
     CAApplyInterfaces();
 
     caglobals.ip.terminate = false;
@@ -507,6 +508,14 @@ void CAIPStopServer()
     OIC_LOG(DEBUG, TAG, "OUT");
 }
 
+void CAWakeUpForChange()
+{
+    if (caglobals.ip.shutdownFds[1] != -1)
+    {
+        write(caglobals.ip.shutdownFds[1], "w", 1);
+    }
+}
+
 static void applyMulticastToInterface4(struct in_addr inaddr)
 {
     if (!caglobals.ip.ipv4enabled)
@@ -537,7 +546,7 @@ static void applyMulticast6(int fd, struct in6_addr *addr, uint32_t interface)
     struct ipv6_mreq mreq;
     mreq.ipv6mr_multiaddr = *addr;
     mreq.ipv6mr_interface = interface;
-    if (setsockopt(fd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, &mreq, sizeof (mreq)))
+    if (setsockopt(fd, IPPROTO_IPV6, IPV6_JOIN_GROUP, &mreq, sizeof (mreq)))
     {
         if (EADDRINUSE != errno)
         {
@@ -609,74 +618,81 @@ static void CAApplyInterfaces()
     u_arraylist_destroy(iflist);
 }
 
+static void CAProcessNewInterface(CAInterface_t *ifitem)
+{
+    applyMulticastToInterface6(ifitem->index);
+    struct in_addr inaddr;
+    inaddr.s_addr = ifitem->ipv4addr;
+    applyMulticastToInterface4(inaddr);
+}
+
 static void CAHandleNetlink()
 {
 #ifdef __linux__
     char buf[4096];
     struct nlmsghdr *nh;
     struct sockaddr_nl sa;
-    struct iovec iov = { buf, sizeof(buf) };
-    struct msghdr msg = { (void *)&sa, sizeof(sa), &iov, 1, NULL, 0, 0 };
+    struct iovec iov = { buf, sizeof (buf) };
+    struct msghdr msg = { (void *)&sa, sizeof (sa), &iov, 1, NULL, 0, 0 };
 
     size_t len = recvmsg(caglobals.ip.netlinkFd, &msg, 0);
 
     for (nh = (struct nlmsghdr *)buf; NLMSG_OK(nh, len); nh = NLMSG_NEXT(nh, len))
     {
-        if (nh->nlmsg_type == RTM_NEWLINK)
+        if (nh->nlmsg_type != RTM_NEWLINK)
         {
-            struct ifinfomsg *ifi = (struct ifinfomsg *)NLMSG_DATA(nh);
-            if ((ifi->ifi_flags & IFF_LOOPBACK) || !(ifi->ifi_flags & IFF_RUNNING))
-            {
-                continue;
-            }
+            continue;
+        }
+
+        struct ifinfomsg *ifi = (struct ifinfomsg *)NLMSG_DATA(nh);
+        if (!ifi || (ifi->ifi_flags & IFF_LOOPBACK) || !(ifi->ifi_flags & IFF_RUNNING))
+        {
+            continue;
+        }
 
-            int newIndex = ifi->ifi_index;
+        int newIndex = ifi->ifi_index;
 
-            u_arraylist_t *iflist = CAIPGetInterfaceInformation(newIndex);
-            if (!iflist)
+        u_arraylist_t *iflist = CAIPGetInterfaceInformation(newIndex);
+        if (!iflist)
+        {
+            OIC_LOG_V(ERROR, TAG, "get interface info failed: %s", strerror(errno));
+            return;
+        }
+
+        uint32_t listLength = u_arraylist_length(iflist);
+        for (uint32_t i = 0; i < listLength; i++)
+        {
+            CAInterface_t *ifitem = (CAInterface_t *)u_arraylist_get(iflist, i);
+            if (!ifitem)
             {
-                OIC_LOG_V(ERROR, TAG, "get interface info failed: %s", strerror(errno));
-                return;
+                continue;
             }
 
-            uint32_t listLength = u_arraylist_length(iflist);
-            for (uint32_t i = 0; i < listLength; i++)
+            if ((int)ifitem->index != newIndex)
             {
-                CAInterface_t *ifitem = (CAInterface_t *)u_arraylist_get(iflist, i);
-                if (!ifitem)
-                {
-                    continue;
-                }
-
-                if ((int)ifitem->index != newIndex)
-                {
-                    continue;
-                }
-
-                applyMulticastToInterface6(newIndex);
-                struct in_addr inaddr;
-                inaddr.s_addr = ifitem->ipv4addr;
-                applyMulticastToInterface4(inaddr);
-                break; // we found the one we were looking for
+                continue;
             }
-            u_arraylist_destroy(iflist);
+
+            CAProcessNewInterface(ifitem);
+            break; // we found the one we were looking for
         }
+        u_arraylist_destroy(iflist);
     }
 #endif // __linux__
 }
 
 void CAIPSetPacketReceiveCallback(CAIPPacketReceivedCallback callback)
 {
-OIC_LOG(DEBUG, TAG, "IN");
+    OIC_LOG(DEBUG, TAG, "IN");
 
-g_packetReceivedCallback = callback;
+    g_packetReceivedCallback = callback;
 
-OIC_LOG(DEBUG, TAG, "OUT");
+    OIC_LOG(DEBUG, TAG, "OUT");
 }
 
 void CAIPSetExceptionCallback(CAIPExceptionCallback callback)
 {
-OIC_LOG(DEBUG, TAG, "IN");
+    OIC_LOG(DEBUG, TAG, "IN");
 
     g_exceptionCallback = callback;
 
index a5fb789..fd889ee 100644 (file)
 
 #define TAG "IP_MONITOR"
 
+CAResult_t CAIPInitializeNetworkMonitor()
+{
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAIPTerminateNetworkMonitor()
+{
+    return CA_STATUS_OK;
+}
+
+int CAGetPollingInterval(int interval)
+{
+    return interval;
+}
+
+CAInterface_t *CAFindInterfaceChange()
+{
+    return NULL;
+}
+
 u_arraylist_t *CAIPGetInterfaceInformation(int desiredIndex)
 {
     if (desiredIndex < 0)
@@ -111,8 +131,8 @@ u_arraylist_t *CAIPGetInterfaceInformation(int desiredIndex)
         ifitem->ipv4addr = ((struct sockaddr_in *)(ifa->ifa_addr))->sin_addr.s_addr;
         ifitem->flags = ifa->ifa_flags;
 
-        CAResult_t result = u_arraylist_add(iflist, ifitem);
-        if (CA_STATUS_OK != result)
+        bool result = u_arraylist_add(iflist, ifitem);
+        if (!result)
         {
             OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
             goto exit;
index 90e200f..b81b357 100644 (file)
 
 #define TAG "IP_MONITOR"
 
+CAResult_t CAIPInitializeNetworkMonitor()
+{
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAIPTerminateNetworkMonitor()
+{
+    return CA_STATUS_OK;
+}
+
+int CAGetPollingInterval(int interval)
+{
+    return interval;
+}
+
+CAInterface_t *CAFindInterfaceChange()
+{
+    return NULL;
+}
+
 u_arraylist_t *CAIPGetInterfaceInformation(int desiredIndex)
 {
     u_arraylist_t *iflist = u_arraylist_create();
@@ -92,8 +112,8 @@ u_arraylist_t *CAIPGetInterfaceInformation(int desiredIndex)
         ifitem->ipv4addr = ((struct sockaddr_in *)(ifa->ifa_addr))->sin_addr.s_addr;
         ifitem->flags = ifa->ifa_flags;
 
-        CAResult_t result = u_arraylist_add(iflist, ifitem);
-        if (CA_STATUS_OK != result)
+        bool result = u_arraylist_add(iflist, ifitem);
+        if (!result)
         {
             OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
             goto exit;
diff --git a/resource/csdk/doc/CCF Lite GIT Repo Layout.docx b/resource/csdk/doc/CCF Lite GIT Repo Layout.docx
deleted file mode 100644 (file)
index 0020cc5..0000000
Binary files a/resource/csdk/doc/CCF Lite GIT Repo Layout.docx and /dev/null differ
index ddccc55..48e7bfc 100644 (file)
@@ -73,7 +73,7 @@ void SRMRequestHandler(const CAEndpoint_t *endPoint, const CARequestInfo_t *requ
 
     // Copy the subjectID
     OicUuid_t subjectId = {.id = {0}};
-    memcpy(subjectId.id, endPoint->identity.id, sizeof(subjectId.id));
+    memcpy(subjectId.id, requestInfo->info.identity.id, sizeof(subjectId.id));
 
     //Check the URI has the query and skip it before checking the permission
     char *uri = strstr(requestInfo->info.resourceUri, "?");
index 5f602ff..839fd73 100644 (file)
@@ -377,17 +377,15 @@ typedef struct
     /** transport modifiers.*/
     OCTransportFlags        flags;
 
+    /** for IP.*/
+    uint16_t                port;
+
     /** address for all adapters.*/
     char                    addr[MAX_ADDR_STR_SIZE];
 
     /** usually zero for default interface.*/
     uint32_t                interface;
 
-    /** for IP.*/
-    uint16_t                port;
-
-    /** secure node identity.*/
-    OCIdentity              identity;
 } OCDevAddr;
 
 /**
@@ -1029,6 +1027,9 @@ typedef struct
     /** backward compatibility.*/
     OCConnectivityType connType;
 
+    /** the security identity of the remote server.*/
+    OCIdentity identity;
+
     /** the is the result of our stack, OCStackResult should contain coap/other error codes.*/
     OCStackResult result;
 
index bc37c05..5b551bb 100644 (file)
 
 Import('env')
 
+transport = env.get('TARGET_TRANSPORT')
+if 'BLE' in transport:
+        # Only supported for ethernet and WiFi.
+        Return()
+
 arduino_simplecs_env = env.Clone()
 ######################################################################
 # Build flags
index 533436a..5faaccd 100644 (file)
 #include "payload_logging.h"
 
 // Tracking user input
-static int UNICAST_DISCOVERY = 0;
-static int TEST_CASE = 0;
-static int CONNECTIVITY = 0;
+static int UnicastDiscovery = 0;
+static int TestCase = 0;
+static int Connectivity = 0;
 
-static const char * UNICAST_DEVICE_DISCOVERY_QUERY = "coap://%s/oic/d";
-static const char * MULTICAST_DEVICE_DISCOVERY_QUERY = "/oic/d";
-static const char * UNICAST_PLATFORM_DISCOVERY_QUERY = "coap://%s/oic/p";
-static const char * MULTICAST_PLATFORM_DISCOVERY_QUERY = "/oic/p";
+static const char *DEVICE_DISCOVERY_QUERY = "%s/oic/d";
+static const char *PLATFORM_DISCOVERY_QUERY = "%s/oic/p";
+static const char *RESOURCE_DISCOVERY_QUERY = "%s/oic/res";
 
-static const char * UNICAST_RESOURCE_DISCOVERY_QUERY = "coap://%s/oic/res";
-static const char * MULTICAST_RESOURCE_DISCOVERY_QUERY = "/oic/res";
 //The following variable determines the interface protocol (IPv4, IPv6, etc)
-//to be used for sending unicast messages. Default set to IPv4.
-static OCConnectivityType OC_CONNTYPE = CT_ADAPTER_IP;
-static std::string coapServerIP = "255.255.255.255";
-static std::string coapServerPort = "5683";
+//to be used for sending unicast messages. Default set to IP dual stack.
+static OCConnectivityType ConnType = CT_ADAPTER_IP;
+static OCDevAddr serverAddr;
+static char discoveryAddr[100];
 static std::string coapServerResource = "/a/light";
-// Size to hold IPV4_ADDRESS:PORT
-static const int IPV4_ADDR_SIZE = 24;
-//Use ipv4addr for both InitDiscovery and InitPlatformOrDeviceDiscovery
-char ipv4addr[IPV4_ADDR_SIZE];
+
 void StripNewLineChar(char* str);
 
 // The handle for the observe registration
@@ -82,7 +76,7 @@ OCPayload* putPayload()
 {
     OCRepPayload* payload = OCRepPayloadCreate();
 
-    if(!payload)
+    if (!payload)
     {
         std::cout << "Failed to create put payload object"<<std::endl;
         std::exit(1);
@@ -134,6 +128,7 @@ static void PrintUsage()
 }
 
 OCStackResult InvokeOCDoResource(std::ostringstream &query,
+                                 OCDevAddr *remoteAddr,
                                  OCMethod method,
                                  OCQualityOfService qos,
                                  OCClientResponseHandler cb,
@@ -148,9 +143,9 @@ OCStackResult InvokeOCDoResource(std::ostringstream &query,
     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
     cbData.cd = NULL;
 
-    ret = OCDoResource(&handle, method, query.str().c_str(), 0,
+    ret = OCDoResource(&handle, method, query.str().c_str(), remoteAddr,
                        (method == OC_REST_PUT) ? putPayload() : NULL,
-                       (OC_CONNTYPE), qos, &cbData, options, numOptions);
+                       (ConnType), qos, &cbData, options, numOptions);
 
     if (ret != OC_STACK_OK)
     {
@@ -173,12 +168,12 @@ OCStackResult InvokeOCDoResource(std::ostringstream &query,
 OCStackApplicationResult putReqCB(void* ctx, OCDoHandle /*handle*/,
                                   OCClientResponse * clientResponse)
 {
-    if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
+    if (ctx == (void*)DEFAULT_CONTEXT_VALUE)
     {
         OC_LOG(INFO, TAG, "Callback Context for PUT recvd successfully");
     }
 
-    if(clientResponse)
+    if (clientResponse)
     {
         OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
         OC_LOG_PAYLOAD(INFO, TAG, clientResponse->payload);
@@ -194,12 +189,12 @@ OCStackApplicationResult putReqCB(void* ctx, OCDoHandle /*handle*/,
 OCStackApplicationResult postReqCB(void *ctx, OCDoHandle /*handle*/,
                                    OCClientResponse *clientResponse)
 {
-    if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
+    if (ctx == (void*)DEFAULT_CONTEXT_VALUE)
     {
         OC_LOG(INFO, TAG, "Callback Context for POST recvd successfully");
     }
 
-    if(clientResponse)
+    if (clientResponse)
     {
         OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
         OC_LOG_PAYLOAD(INFO, TAG, clientResponse->payload);
@@ -216,12 +211,12 @@ OCStackApplicationResult deleteReqCB(void *ctx,
                                      OCDoHandle /*handle*/,
                                      OCClientResponse *clientResponse)
 {
-    if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
+    if (ctx == (void*)DEFAULT_CONTEXT_VALUE)
     {
         OC_LOG(INFO, TAG, "Callback Context for DELETE recvd successfully");
     }
 
-    if(clientResponse)
+    if (clientResponse)
     {
         OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
         OC_LOG_PAYLOAD(INFO, TAG, clientResponse->payload);
@@ -237,13 +232,13 @@ OCStackApplicationResult deleteReqCB(void *ctx,
 OCStackApplicationResult getReqCB(void* ctx, OCDoHandle /*handle*/,
                                   OCClientResponse * clientResponse)
 {
-    if(clientResponse == NULL)
+    if (clientResponse == NULL)
     {
         OC_LOG(INFO, TAG, "getReqCB received NULL clientResponse");
         return   OC_STACK_DELETE_TRANSACTION;
     }
 
-    if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
+    if (ctx == (void*)DEFAULT_CONTEXT_VALUE)
     {
         OC_LOG(INFO, TAG, "Callback Context for GET query recvd successfully");
     }
@@ -253,14 +248,14 @@ OCStackApplicationResult getReqCB(void* ctx, OCDoHandle /*handle*/,
     OC_LOG_PAYLOAD(INFO, TAG, clientResponse->payload);
     OC_LOG(INFO, TAG, PCF("=============> Get Response"));
 
-    if(clientResponse->numRcvdVendorSpecificHeaderOptions > 0)
+    if (clientResponse->numRcvdVendorSpecificHeaderOptions > 0)
     {
         OC_LOG (INFO, TAG, "Received vendor specific options");
         uint8_t i = 0;
         OCHeaderOption * rcvdOptions = clientResponse->rcvdVendorSpecificHeaderOptions;
         for( i = 0; i < clientResponse->numRcvdVendorSpecificHeaderOptions; i++)
         {
-            if(((OCHeaderOption)rcvdOptions[i]).protocolID == OC_COAP_ID)
+            if (((OCHeaderOption)rcvdOptions[i]).protocolID == OC_COAP_ID)
             {
                 OC_LOG_V(INFO, TAG, "Received option with OC_COAP_ID and ID %u with",
                         ((OCHeaderOption)rcvdOptions[i]).optionID );
@@ -276,12 +271,12 @@ OCStackApplicationResult getReqCB(void* ctx, OCDoHandle /*handle*/,
 OCStackApplicationResult obsReqCB(void* ctx, OCDoHandle /*handle*/,
                                   OCClientResponse * clientResponse)
 {
-    if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
+    if (ctx == (void*)DEFAULT_CONTEXT_VALUE)
     {
         OC_LOG(INFO, TAG, "Callback Context for OBS query recvd successfully");
     }
 
-    if(clientResponse)
+    if (clientResponse)
     {
         OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
         OC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
@@ -292,7 +287,7 @@ OCStackApplicationResult obsReqCB(void* ctx, OCDoHandle /*handle*/,
         gNumObserveNotifies++;
         if (gNumObserveNotifies == 15) //large number to test observing in DELETE case.
         {
-            if(TEST_CASE == TEST_OBS_REQ_NON || TEST_CASE == TEST_OBS_REQ_CON)
+            if (TestCase == TEST_OBS_REQ_NON || TestCase == TEST_OBS_REQ_CON)
             {
                 if (OCCancel (gObserveDoHandle, OC_LOW_QOS, NULL, 0) != OC_STACK_OK)
                 {
@@ -300,7 +295,7 @@ OCStackApplicationResult obsReqCB(void* ctx, OCDoHandle /*handle*/,
                 }
                 return OC_STACK_DELETE_TRANSACTION;
             }
-            else if(TEST_CASE == TEST_OBS_REQ_NON_CANCEL_IMM)
+            else if (TestCase == TEST_OBS_REQ_NON_CANCEL_IMM)
             {
                 if (OCCancel (gObserveDoHandle, OC_HIGH_QOS, NULL, 0) != OC_STACK_OK)
                 {
@@ -308,16 +303,16 @@ OCStackApplicationResult obsReqCB(void* ctx, OCDoHandle /*handle*/,
                 }
             }
         }
-        if(clientResponse->sequenceNumber == OC_OBSERVE_REGISTER)
+        if (clientResponse->sequenceNumber == OC_OBSERVE_REGISTER)
         {
             OC_LOG(INFO, TAG, "This also serves as a registration confirmation");
         }
-        else if(clientResponse->sequenceNumber == OC_OBSERVE_DEREGISTER)
+        else if (clientResponse->sequenceNumber == OC_OBSERVE_DEREGISTER)
         {
             OC_LOG(INFO, TAG, "This also serves as a deregistration confirmation");
             return OC_STACK_DELETE_TRANSACTION;
         }
-        else if(clientResponse->sequenceNumber == OC_OBSERVE_NO_OPTION)
+        else if (clientResponse->sequenceNumber == OC_OBSERVE_NO_OPTION)
         {
             OC_LOG(INFO, TAG, "This also tells you that registration/deregistration failed");
             return OC_STACK_DELETE_TRANSACTION;
@@ -341,7 +336,6 @@ OCStackApplicationResult presenceCB(void* ctx, OCDoHandle /*handle*/,
     if (clientResponse)
     {
         OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
-        OC_LOG_V(INFO, TAG, "NONCE NUMBER: %u", clientResponse->sequenceNumber);
         OC_LOG_V(INFO, TAG, "Callback Context for Presence notification recvd successfully %d",
                 gNumPresenceNotifies);
         OC_LOG_PAYLOAD(INFO, TAG, clientResponse->payload);
@@ -366,7 +360,7 @@ OCStackApplicationResult presenceCB(void* ctx, OCDoHandle /*handle*/,
 
 // This is a function called back when a device is discovered
 OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle /*handle*/,
-        OCClientResponse * clientResponse)
+                                        OCClientResponse * clientResponse)
 {
     if (ctx == (void*) DEFAULT_CONTEXT_VALUE)
     {
@@ -385,10 +379,11 @@ OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle /*handle*/,
                 clientResponse->devAddr.port);
         OC_LOG_PAYLOAD(INFO, TAG, clientResponse->payload);
 
-        OC_CONNTYPE = clientResponse->connType;
+        ConnType = clientResponse->connType;
+        serverAddr = clientResponse->devAddr;
         parseClientResponse(clientResponse);
 
-        switch(TEST_CASE)
+        switch(TestCase)
         {
             case TEST_GET_REQ_NON:
                 InitGetRequest(OC_LOW_QOS, 0, 0);
@@ -453,16 +448,16 @@ OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle /*handle*/,
     return OC_STACK_KEEP_TRANSACTION;
 }
 
-OCStackApplicationResult PlatformDiscoveryReqCB (void* ctx,
-                                                 OCDoHandle /*handle*/,
-        OCClientResponse * clientResponse)
+OCStackApplicationResult PlatformDiscoveryReqCB(void* ctx,
+                                                OCDoHandle /*handle*/,
+                                                OCClientResponse * clientResponse)
 {
     if (ctx == (void*) DEFAULT_CONTEXT_VALUE)
     {
         OC_LOG(INFO, TAG, "Callback Context for Platform DISCOVER query recvd successfully");
     }
 
-    if(clientResponse)
+    if (clientResponse)
     {
         OC_LOG(INFO, TAG, PCF("Discovery Response:"));
         OC_LOG_PAYLOAD(INFO, TAG, clientResponse->payload);
@@ -472,18 +467,18 @@ OCStackApplicationResult PlatformDiscoveryReqCB (void* ctx,
         OC_LOG_V(INFO, TAG, "PlatformDiscoveryReqCB received Null clientResponse");
     }
 
-    return (UNICAST_DISCOVERY) ? OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION;
+    return (UnicastDiscovery) ? OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION;
 }
 
-OCStackApplicationResult DeviceDiscoveryReqCB (void* ctx, OCDoHandle /*handle*/,
-        OCClientResponse * clientResponse)
+OCStackApplicationResult DeviceDiscoveryReqCB(void* ctx, OCDoHandle /*handle*/,
+                                              OCClientResponse * clientResponse)
 {
     if (ctx == (void*) DEFAULT_CONTEXT_VALUE)
     {
         OC_LOG(INFO, TAG, "Callback Context for Device DISCOVER query recvd successfully");
     }
 
-    if(clientResponse)
+    if (clientResponse)
     {
         OC_LOG(INFO, TAG, PCF("Discovery Response:"));
         OC_LOG_PAYLOAD(INFO, TAG, clientResponse->payload);
@@ -493,7 +488,7 @@ OCStackApplicationResult DeviceDiscoveryReqCB (void* ctx, OCDoHandle /*handle*/,
         OC_LOG_V(INFO, TAG, "PlatformDiscoveryReqCB received Null clientResponse");
     }
 
-    return (UNICAST_DISCOVERY) ? OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION;
+    return (UnicastDiscovery) ? OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION;
 }
 
 #ifdef WITH_PRESENCE
@@ -503,37 +498,37 @@ int InitPresence()
     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
     std::ostringstream query;
     std::ostringstream querySuffix;
-    query << "coap://" << coapServerIP << ":" << coapServerPort << OC_RSRVD_PRESENCE_URI;
-    if(TEST_CASE == TEST_OBS_PRESENCE)
+    query << OC_RSRVD_PRESENCE_URI;
+    if (TestCase == TEST_OBS_PRESENCE)
     {
-        result = InvokeOCDoResource(query, OC_REST_PRESENCE, OC_LOW_QOS,
-                presenceCB, NULL, 0);
+        result = InvokeOCDoResource(query, &serverAddr, OC_REST_PRESENCE,
+                OC_LOW_QOS, presenceCB, NULL, 0);
     }
-    if(TEST_CASE == TEST_OBS_PRESENCE_WITH_FILTER || TEST_CASE == TEST_OBS_PRESENCE_WITH_FILTERS)
+    if (TestCase == TEST_OBS_PRESENCE_WITH_FILTER || TestCase == TEST_OBS_PRESENCE_WITH_FILTERS)
     {
         querySuffix.str("");
         querySuffix << query.str() << "?rt=core.led";
-        result = InvokeOCDoResource(querySuffix, OC_REST_PRESENCE, OC_LOW_QOS,
-                presenceCB, NULL, 0);
+        result = InvokeOCDoResource(querySuffix, &serverAddr, OC_REST_PRESENCE,
+                OC_LOW_QOS, presenceCB, NULL, 0);
     }
-    if(TEST_CASE == TEST_OBS_PRESENCE_WITH_FILTERS)
+    if (TestCase == TEST_OBS_PRESENCE_WITH_FILTERS)
     {
-        if(result == OC_STACK_OK)
+        if (result == OC_STACK_OK)
         {
             querySuffix.str("");
             querySuffix << query.str() << "?rt=core.fan";
-            result = InvokeOCDoResource(querySuffix, OC_REST_PRESENCE, OC_LOW_QOS,
+            result = InvokeOCDoResource(querySuffix, &serverAddr, OC_REST_PRESENCE, OC_LOW_QOS,
                     presenceCB, NULL, 0);
         }
     }
-    if(TEST_CASE == TEST_OBS_MULTICAST_PRESENCE)
+    if (TestCase == TEST_OBS_MULTICAST_PRESENCE)
     {
-        if(result == OC_STACK_OK)
+        if (result == OC_STACK_OK)
         {
             std::ostringstream multicastPresenceQuery;
             multicastPresenceQuery.str("");
             multicastPresenceQuery << "coap://" << OC_MULTICAST_PREFIX << OC_RSRVD_PRESENCE_URI;
-            result = InvokeOCDoResource(multicastPresenceQuery, OC_REST_PRESENCE, OC_LOW_QOS,
+            result = InvokeOCDoResource(multicastPresenceQuery, &serverAddr, OC_REST_PRESENCE, OC_LOW_QOS,
                     presenceCB, NULL, 0);
         }
     }
@@ -545,8 +540,8 @@ int InitGetRequestToUnavailableResource(OCQualityOfService qos)
 {
     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
     std::ostringstream query;
-    query << "coap://" << coapServerIP << ":" << coapServerPort << "/SomeUnknownResource";
-    return (InvokeOCDoResource(query, OC_REST_GET, (qos == OC_HIGH_QOS)? OC_HIGH_QOS:OC_LOW_QOS,
+    query << "/SomeUnknownResource";
+    return (InvokeOCDoResource(query, &serverAddr, OC_REST_GET, (qos == OC_HIGH_QOS)? OC_HIGH_QOS:OC_LOW_QOS,
             getReqCB, NULL, 0));
 }
 
@@ -554,17 +549,17 @@ int InitObserveRequest(OCQualityOfService qos)
 {
     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
     std::ostringstream query;
-    query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
-    return (InvokeOCDoResource(query,
-            OC_REST_OBSERVE, (qos == OC_HIGH_QOS)? OC_HIGH_QOS:OC_LOW_QOS, obsReqCB, NULL, 0));
+    query << coapServerResource;
+    return (InvokeOCDoResource(query, &serverAddr, OC_REST_OBSERVE,
+              (qos == OC_HIGH_QOS)? OC_HIGH_QOS:OC_LOW_QOS, obsReqCB, NULL, 0));
 }
 
 int InitPutRequest(OCQualityOfService qos)
 {
     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
     std::ostringstream query;
-    query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
-    return (InvokeOCDoResource(query, OC_REST_PUT, (qos == OC_HIGH_QOS)? OC_HIGH_QOS:OC_LOW_QOS,
+    query << coapServerResource;
+    return (InvokeOCDoResource(query, &serverAddr, OC_REST_PUT, (qos == OC_HIGH_QOS)? OC_HIGH_QOS:OC_LOW_QOS,
             putReqCB, NULL, 0));
 }
 
@@ -573,10 +568,10 @@ int InitPostRequest(OCQualityOfService qos)
     OCStackResult result;
     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
     std::ostringstream query;
-    query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
+    query << coapServerResource;
 
     // First POST operation (to create an Light instance)
-    result = InvokeOCDoResource(query, OC_REST_POST,
+    result = InvokeOCDoResource(query, &serverAddr, OC_REST_POST,
                                ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
                                postReqCB, NULL, 0);
     if (OC_STACK_OK != result)
@@ -586,7 +581,7 @@ int InitPostRequest(OCQualityOfService qos)
     }
 
     // Second POST operation (to create an Light instance)
-    result = InvokeOCDoResource(query, OC_REST_POST,
+    result = InvokeOCDoResource(query, &serverAddr, OC_REST_POST,
                                ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
                                postReqCB, NULL, 0);
     if (OC_STACK_OK != result)
@@ -595,7 +590,7 @@ int InitPostRequest(OCQualityOfService qos)
     }
 
     // This POST operation will update the original resourced /a/light
-    return (InvokeOCDoResource(query, OC_REST_POST,
+    return (InvokeOCDoResource(query, &serverAddr, OC_REST_POST,
                                ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
                                postReqCB, NULL, 0));
 }
@@ -604,7 +599,7 @@ void* RequestDeleteDeathResourceTask(void* myqos)
 {
     sleep (30);//long enough to give the server time to finish deleting the resource.
     std::ostringstream query;
-    query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
+    query << coapServerResource;
 
     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
 
@@ -619,7 +614,7 @@ void* RequestDeleteDeathResourceTask(void* myqos)
         qos = OC_HIGH_QOS;
     }
 
-    OCStackResult result = InvokeOCDoResource(query, OC_REST_DELETE,
+    OCStackResult result = InvokeOCDoResource(query, &serverAddr, OC_REST_DELETE,
                                qos,
                                deleteReqCB, NULL, 0);
 
@@ -635,12 +630,12 @@ int InitDeleteRequest(OCQualityOfService qos)
 {
     OCStackResult result;
     std::ostringstream query;
-    query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
+    query << coapServerResource;
 
     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
 
     // First DELETE operation
-    result = InvokeOCDoResource(query, OC_REST_DELETE,
+    result = InvokeOCDoResource(query, &serverAddr, OC_REST_DELETE,
                                qos,
                                deleteReqCB, NULL, 0);
     if (OC_STACK_OK != result)
@@ -666,7 +661,7 @@ int InitGetRequest(OCQualityOfService qos, uint8_t withVendorSpecificHeaderOptio
 
     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
     std::ostringstream query;
-    query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
+    query << coapServerResource;
 
     // ocserver is written to only process "power<X" query.
     if (getWithQuery)
@@ -691,12 +686,12 @@ int InitGetRequest(OCQualityOfService qos, uint8_t withVendorSpecificHeaderOptio
     }
     if (withVendorSpecificHeaderOptions)
     {
-        return (InvokeOCDoResource(query, OC_REST_GET,
+        return (InvokeOCDoResource(query, &serverAddr, OC_REST_GET,
                 (qos == OC_HIGH_QOS) ? OC_HIGH_QOS : OC_LOW_QOS, getReqCB, options, 2));
     }
     else
     {
-        return (InvokeOCDoResource(query, OC_REST_GET,
+        return (InvokeOCDoResource(query, &serverAddr, OC_REST_GET,
                 (qos == OC_HIGH_QOS) ? OC_HIGH_QOS : OC_LOW_QOS, getReqCB, NULL, 0));
     }
 }
@@ -709,32 +704,15 @@ int InitPlatformDiscovery(OCQualityOfService qos)
     OCCallbackData cbData;
     char szQueryUri[64] = { 0 };
 
+    snprintf(szQueryUri, sizeof (szQueryUri) - 1, PLATFORM_DISCOVERY_QUERY, discoveryAddr);
+
     cbData.cb = PlatformDiscoveryReqCB;
     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
     cbData.cd = NULL;
 
-    if(UNICAST_DISCOVERY)
-    {
-        snprintf(szQueryUri, sizeof(szQueryUri), UNICAST_PLATFORM_DISCOVERY_QUERY, ipv4addr);
-    }
-    else
-    {
-        strncpy(szQueryUri, MULTICAST_PLATFORM_DISCOVERY_QUERY, sizeof(szQueryUri) -1 );
-    }
-    szQueryUri[sizeof(szQueryUri) -1] = '\0';
-
-    if(UNICAST_DISCOVERY)
-    {
-        ret = OCDoResource(NULL, OC_REST_GET, szQueryUri, 0, 0, OC_CONNTYPE,
-                (qos == OC_HIGH_QOS) ? OC_HIGH_QOS : OC_LOW_QOS, &cbData, NULL, 0);
-    }
-    else
-    {
-
-        ret = OCDoResource(NULL, OC_REST_DISCOVER, szQueryUri, 0, 0, OC_CONNTYPE,
-                        (qos == OC_HIGH_QOS) ? OC_HIGH_QOS : OC_LOW_QOS, &cbData, NULL, 0);
-    }
-
+    ret = OCDoResource(NULL, OC_REST_DISCOVER, szQueryUri, NULL, 0, CT_DEFAULT,
+                       (qos == OC_HIGH_QOS) ? OC_HIGH_QOS : OC_LOW_QOS,
+                       &cbData, NULL, 0);
     if (ret != OC_STACK_OK)
     {
         OC_LOG(ERROR, TAG, "OCStack device error");
@@ -749,33 +727,17 @@ int InitDeviceDiscovery(OCQualityOfService qos)
 
     OCStackResult ret;
     OCCallbackData cbData;
-    char szQueryUri[64] = { 0 };
+    char szQueryUri[100] = { 0 };
+
+    snprintf(szQueryUri, sizeof (szQueryUri) - 1, DEVICE_DISCOVERY_QUERY, discoveryAddr);
 
     cbData.cb = DeviceDiscoveryReqCB;
     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
     cbData.cd = NULL;
 
-    if(UNICAST_DISCOVERY)
-    {
-        snprintf(szQueryUri, sizeof(szQueryUri), UNICAST_DEVICE_DISCOVERY_QUERY, ipv4addr);
-    }
-    else
-    {
-        strncpy(szQueryUri, MULTICAST_DEVICE_DISCOVERY_QUERY, sizeof(szQueryUri) -1 );
-    }
-    szQueryUri[sizeof(szQueryUri) -1] = '\0';
-
-    if(UNICAST_DISCOVERY)
-    {
-        ret = OCDoResource(NULL, OC_REST_GET, szQueryUri, 0, 0, OC_CONNTYPE,
-                (qos == OC_HIGH_QOS) ? OC_HIGH_QOS : OC_LOW_QOS, &cbData, NULL, 0);
-    }
-    else
-    {
-        ret = OCDoResource(NULL, OC_REST_DISCOVER, szQueryUri, 0, 0, OC_CONNTYPE,
-                        (qos == OC_HIGH_QOS) ? OC_HIGH_QOS : OC_LOW_QOS, &cbData, NULL, 0);
-    }
-
+    ret = OCDoResource(NULL, OC_REST_DISCOVER, szQueryUri, NULL, 0, CT_DEFAULT,
+                       (qos == OC_HIGH_QOS) ? OC_HIGH_QOS : OC_LOW_QOS,
+                       &cbData, NULL, 0);
     if (ret != OC_STACK_OK)
     {
         OC_LOG(ERROR, TAG, "OCStack device error");
@@ -788,31 +750,17 @@ int InitDiscovery(OCQualityOfService qos)
 {
     OCStackResult ret;
     OCCallbackData cbData;
-    /* Start a discovery query*/
-    char szQueryUri[64] = { 0 };
+    char szQueryUri[100] = { 0 };
 
-    if (UNICAST_DISCOVERY)
-    {
-        snprintf(szQueryUri, sizeof(szQueryUri), UNICAST_RESOURCE_DISCOVERY_QUERY, ipv4addr);
-    }
-    else
-    {
-        strcpy(szQueryUri, MULTICAST_RESOURCE_DISCOVERY_QUERY);
-    }
+    snprintf(szQueryUri, sizeof (szQueryUri) - 1, RESOURCE_DISCOVERY_QUERY, discoveryAddr);
 
     cbData.cb = discoveryReqCB;
     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
     cbData.cd = NULL;
-    if(UNICAST_DISCOVERY)
-    {
-        ret = OCDoResource(NULL, OC_REST_GET, szQueryUri, 0, 0, OC_CONNTYPE,
-                (qos == OC_HIGH_QOS) ? OC_HIGH_QOS : OC_LOW_QOS, &cbData, NULL, 0);
-    }
-    else
-    {
-        ret = OCDoResource(NULL, OC_REST_DISCOVER, szQueryUri, 0, 0, OC_CONNTYPE,
-                        (qos == OC_HIGH_QOS) ? OC_HIGH_QOS : OC_LOW_QOS, &cbData, NULL, 0);
-    }
+
+    ret = OCDoResource(NULL, OC_REST_DISCOVER, szQueryUri, NULL, 0, CT_DEFAULT,
+                       (qos == OC_HIGH_QOS) ? OC_HIGH_QOS : OC_LOW_QOS,
+                       &cbData, NULL, 0);
     if (ret != OC_STACK_OK)
     {
         OC_LOG(ERROR, TAG, "OCStack resource error");
@@ -829,13 +777,13 @@ int main(int argc, char* argv[])
         switch(opt)
         {
             case 'u':
-                UNICAST_DISCOVERY = atoi(optarg);
+                UnicastDiscovery = atoi(optarg);
                 break;
             case 't':
-                TEST_CASE = atoi(optarg);
+                TestCase = atoi(optarg);
                 break;
             case 'c':
-                CONNECTIVITY = atoi(optarg);
+                Connectivity = atoi(optarg);
                 break;
             default:
                 PrintUsage();
@@ -843,24 +791,23 @@ int main(int argc, char* argv[])
         }
     }
 
-    if ((UNICAST_DISCOVERY != 0 && UNICAST_DISCOVERY != 1) ||
-            (TEST_CASE < TEST_DISCOVER_REQ || TEST_CASE >= MAX_TESTS) ||
-            (CONNECTIVITY < CT_ADAPTER_DEFAULT || CONNECTIVITY >= MAX_CT))
+    if ((UnicastDiscovery != 0 && UnicastDiscovery != 1) ||
+            (TestCase < TEST_DISCOVER_REQ || TestCase >= MAX_TESTS) ||
+            (Connectivity < CT_ADAPTER_DEFAULT || Connectivity >= MAX_CT))
     {
         PrintUsage();
         return -1;
     }
 
-    /* Initialize OCStack*/
-    if (OCInit(NULL, 0, OC_CLIENT) != OC_STACK_OK)
+    if (OCInit1(OC_CLIENT, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS) != OC_STACK_OK)
     {
         OC_LOG(ERROR, TAG, "OCStack init error");
         return 0;
     }
 
-    if(CONNECTIVITY == CT_ADAPTER_DEFAULT || CONNECTIVITY == CT_IP)
+    if (Connectivity == CT_ADAPTER_DEFAULT || Connectivity == CT_IP)
     {
-        OC_CONNTYPE = CT_ADAPTER_IP;
+        ConnType = CT_ADAPTER_IP;
     }
     else
     {
@@ -868,28 +815,31 @@ int main(int argc, char* argv[])
         PrintUsage();
     }
 
-    if (UNICAST_DISCOVERY)
+    discoveryAddr[0] = '\0';
+
+    if (UnicastDiscovery)
     {
-        OC_LOG(INFO, TAG, "Enter IP address with port number of the Server hosting resource");
-        OC_LOG(INFO, TAG, "as follows - eg: 192.168.0.15:45454 (IP:Port) \n");
+        OC_LOG(INFO, TAG, "Enter IP address of server with optional port number");
+        OC_LOG(INFO, TAG, "IPv4: 192.168.0.15:45454\n");
+        OC_LOG(INFO, TAG, "IPv6: [fe80::20c:29ff:fe1b:9c5]:45454\n");
 
-        if (fgets(ipv4addr, IPV4_ADDR_SIZE, stdin))
+        if (fgets(discoveryAddr, sizeof (discoveryAddr), stdin))
         {
             //Strip newline char from ipv4addr
-            StripNewLineChar(ipv4addr);
+            StripNewLineChar(discoveryAddr);
         }
         else
         {
-            OC_LOG(ERROR, TAG, "!! Bad input for IPV4 address. !!");
+            OC_LOG(ERROR, TAG, "!! Bad input for IP address. !!");
             return OC_STACK_INVALID_PARAM;
         }
     }
 
-    if(UNICAST_DISCOVERY  == 0  && TEST_CASE == TEST_DISCOVER_DEV_REQ)
+    if (UnicastDiscovery == 0 && TestCase == TEST_DISCOVER_DEV_REQ)
     {
         InitDeviceDiscovery(OC_LOW_QOS);
     }
-    else if(UNICAST_DISCOVERY  == 0  && TEST_CASE == TEST_DISCOVER_PLATFORM_REQ)
+    else if (UnicastDiscovery == 0 && TestCase == TEST_DISCOVER_PLATFORM_REQ)
     {
         InitPlatformDiscovery(OC_LOW_QOS);
     }
@@ -922,35 +872,6 @@ int main(int argc, char* argv[])
     return 0;
 }
 
-std::string getIPAddrTBServer(OCClientResponse * clientResponse)
-{
-    if (!clientResponse)
-    {
-        return "";
-    }
-    if (!clientResponse->addr)
-    {
-        return "";
-    }
-
-    return std::string(clientResponse->devAddr.addr);
-}
-
-std::string getPortTBServer(OCClientResponse * clientResponse)
-{
-    if (!clientResponse)
-    {
-        return "";
-    }
-    if (!clientResponse->addr)
-    {
-        return "";
-    }
-    std::ostringstream ss;
-    ss << clientResponse->devAddr.port;
-    return ss.str();
-}
-
 std::string getConnectivityType (OCConnectivityType connType)
 {
     switch (connType & CT_MASK_ADAPTER)
@@ -977,13 +898,10 @@ std::string getConnectivityType (OCConnectivityType connType)
 
 std::string getQueryStrForGetPut(OCClientResponse * /*clientResponse*/)
 {
-
     return "/a/light";
 }
 
 void parseClientResponse(OCClientResponse * clientResponse)
 {
-    coapServerIP = getIPAddrTBServer(clientResponse);
-    coapServerPort = getPortTBServer(clientResponse);
     coapServerResource = getQueryStrForGetPut(clientResponse);
 }
index ce00796..e2a4a69 100644 (file)
 #define MAX_IP_ADDR_ST_SZ  16 //string size of "155.255.255.255" (15 + 1)
 #define MAX_PORT_ST_SZ  6     //string size of "65535" (5 + 1)
 
-static int IPV4_ADDR_SIZE = 24;
-static int UNICAST_DISCOVERY = 0;
-static int TEST_CASE = 0;
-static int CONNECTIVITY = 0;
-
-static const char UNICAST_DISCOVERY_QUERY[] = "coap://%s/oic/res";
+static int UnicastDiscovery = 0;
+static int TestCase = 0;
+static int Connectivity = 0;
 
 //The following variable determines the interface protocol (IP, etc)
 //to be used for sending unicast messages. Default set to IP.
-static OCConnectivityType OC_CONNTYPE = CT_ADAPTER_IP;
-static const char * MULTICAST_RESOURCE_DISCOVERY_QUERY = "/oic/res";
+static OCConnectivityType ConnType = CT_ADAPTER_IP;
+static const char *RESOURCE_DISCOVERY_QUERY = "%s/oic/res";
 
 int gQuitFlag = 0;
 
@@ -100,9 +97,12 @@ const ResourceNode * getResource()
     return resourceList;
 }
 
-OCStackResult InvokeOCDoResource(std::ostringstream &query, OCMethod method,
-                                 OCConnectivityType connType, OCQualityOfService qos,
-        OCClientResponseHandler cb, OCHeaderOption * options, uint8_t numOptions)
+OCStackResult InvokeOCDoResource(std::ostringstream &query,
+                                 OCMethod method,
+                                 const OCDevAddr *dest,
+                                 OCQualityOfService qos,
+                                 OCClientResponseHandler cb,
+                                 OCHeaderOption * options, uint8_t numOptions)
 {
     OCStackResult ret;
     OCCallbackData cbData;
@@ -111,9 +111,9 @@ OCStackResult InvokeOCDoResource(std::ostringstream &query, OCMethod method,
     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
     cbData.cd = NULL;
 
-    ret = OCDoResource(NULL, method, query.str().c_str(), 0,
+    ret = OCDoResource(NULL, method, query.str().c_str(), dest,
         (method == OC_REST_PUT || method == OC_REST_POST) ? putPayload() : NULL,
-         connType, qos, &cbData, options, numOptions);
+         CT_DEFAULT, qos, &cbData, options, numOptions);
 
     if (ret != OC_STACK_OK)
     {
@@ -125,7 +125,7 @@ OCStackResult InvokeOCDoResource(std::ostringstream &query, OCMethod method,
 }
 
 OCStackApplicationResult putReqCB(void* ctx, OCDoHandle /*handle*/,
-                                OCClientResponse * clientResponse)
+                                  OCClientResponse * clientResponse)
 {
     if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
     {
@@ -149,7 +149,7 @@ OCStackApplicationResult putReqCB(void* ctx, OCDoHandle /*handle*/,
 }
 
 OCStackApplicationResult postReqCB(void *ctx, OCDoHandle /*handle*/,
-                          OCClientResponse *clientResponse)
+                                   OCClientResponse *clientResponse)
 {
     if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
     {
@@ -174,7 +174,7 @@ OCStackApplicationResult postReqCB(void *ctx, OCDoHandle /*handle*/,
 }
 
 OCStackApplicationResult getReqCB(void* ctx, OCDoHandle /*handle*/,
-                           OCClientResponse * clientResponse)
+                                  OCClientResponse * clientResponse)
 {
     if (ctx == (void*) DEFAULT_CONTEXT_VALUE)
     {
@@ -221,7 +221,7 @@ OCStackApplicationResult getReqCB(void* ctx, OCDoHandle /*handle*/,
  * This is a function called back when a device is discovered
  */
 OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle /*handle*/,
-        OCClientResponse * clientResponse)
+                                        OCClientResponse * clientResponse)
 {
     if (ctx == (void*)DEFAULT_CONTEXT_VALUE)
     {
@@ -247,7 +247,7 @@ OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle /*handle*/,
     {
         OC_LOG(ERROR, TAG, "<====DISCOVERY Callback fail to receive clientResponse====>\n");
     }
-    return (UNICAST_DISCOVERY) ?
+    return (UnicastDiscovery) ?
            OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION ;
 }
 
@@ -262,10 +262,10 @@ int InitPutRequest(OCQualityOfService qos)
         OC_LOG_V(ERROR, TAG, "Resource null, can't do PUT request\n");
         return -1;
     }
-    query << "coap://" << resource->ip << ":" << resource->port << resource->uri ;
+    query << resource->uri;
     OC_LOG_V(INFO, TAG,"Executing InitPutRequest, Query: %s", query.str().c_str());
 
-    return (InvokeOCDoResource(query, OC_REST_PUT, resource->connType,
+    return (InvokeOCDoResource(query, OC_REST_PUT, &resource->endpoint,
            ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
             putReqCB, NULL, 0));
 }
@@ -275,7 +275,7 @@ int InitPostRequest(OCQualityOfService qos)
     OCStackResult result;
     std::ostringstream query;
     //Get most recently inserted resource
-    const ResourceNode * resource  = getResource();
+    const ResourceNode *resource  = getResource();
 
     if(!resource)
     {
@@ -283,11 +283,11 @@ int InitPostRequest(OCQualityOfService qos)
         return -1;
     }
 
-    query << "coap://" << resource->ip << ":" << resource->port << resource->uri ;
+    query << resource->uri;
     OC_LOG_V(INFO, TAG,"Executing InitPostRequest, Query: %s", query.str().c_str());
 
     // First POST operation (to create an LED instance)
-    result = InvokeOCDoResource(query, OC_REST_POST, resource->connType,
+    result = InvokeOCDoResource(query, OC_REST_POST, &resource->endpoint,
             ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
             postReqCB, NULL, 0);
     if (OC_STACK_OK != result)
@@ -297,7 +297,7 @@ int InitPostRequest(OCQualityOfService qos)
     }
 
     // Second POST operation (to create an LED instance)
-    result = InvokeOCDoResource(query, OC_REST_POST, resource->connType,
+    result = InvokeOCDoResource(query, OC_REST_POST, &resource->endpoint,
             ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
             postReqCB, NULL, 0);
     if (OC_STACK_OK != result)
@@ -306,7 +306,7 @@ int InitPostRequest(OCQualityOfService qos)
     }
 
     // This POST operation will update the original resourced /a/led
-    return (InvokeOCDoResource(query, OC_REST_POST,resource->connType,
+    return (InvokeOCDoResource(query, OC_REST_POST, &resource->endpoint,
                 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
                 postReqCB, NULL, 0));
 }
@@ -322,10 +322,10 @@ int InitGetRequest(OCQualityOfService qos)
         OC_LOG_V(ERROR, TAG, "Resource null, can't do GET request\n");
         return -1;
     }
-    query << "coap://" << resource->ip << ":" << resource->port << resource->uri ;
+    query << resource->uri;
     OC_LOG_V(INFO, TAG,"Executing InitGetRequest, Query: %s", query.str().c_str());
 
-    return (InvokeOCDoResource(query, OC_REST_GET, resource->connType,
+    return (InvokeOCDoResource(query, OC_REST_GET, &resource->endpoint,
             (qos == OC_HIGH_QOS)?OC_HIGH_QOS:OC_LOW_QOS, getReqCB, NULL, 0));
 }
 
@@ -333,44 +333,34 @@ int InitDiscovery()
 {
     OCStackResult ret;
     OCCallbackData cbData;
-    /* Start a discovery query*/
-    char szQueryUri[64] = {};
-    if (UNICAST_DISCOVERY)
+    char queryUri[200];
+    char ipaddr[100] = { '\0' };
+
+    if (UnicastDiscovery)
     {
-        char ipv4addr[IPV4_ADDR_SIZE];
-        OC_LOG(INFO, TAG, "Enter IP address with port of the Server hosting resource"\
-                    "(Ex: 192.168.0.15:1234) ");
+        OC_LOG(INFO, TAG, "Enter IP address (with optional port) of the Server hosting resource\n");
+        OC_LOG(INFO, TAG, "IPv4: 192.168.0.15:45454\n");
+        OC_LOG(INFO, TAG, "IPv6: [fe80::20c:29ff:fe1b:9c5]:45454\n");
 
-        if (fgets(ipv4addr, IPV4_ADDR_SIZE, stdin))
+        if (fgets(ipaddr, sizeof (ipaddr), stdin))
         {
-            //Strip newline char from ipv4addr
-            StripNewLineChar(ipv4addr);
-            snprintf(szQueryUri, sizeof(szQueryUri), UNICAST_DISCOVERY_QUERY, ipv4addr);
+            StripNewLineChar(ipaddr); //Strip newline char from ipaddr
         }
         else
         {
-            OC_LOG(ERROR, TAG, "!! Bad input for IPV4 address. !!");
+            OC_LOG(ERROR, TAG, "!! Bad input for IP address. !!");
             return OC_STACK_INVALID_PARAM;
         }
     }
-    else
-    {
-        OICStrcpy(szQueryUri, sizeof(szQueryUri), MULTICAST_RESOURCE_DISCOVERY_QUERY);
-    }
+
+    snprintf(queryUri, sizeof (queryUri), RESOURCE_DISCOVERY_QUERY, ipaddr);
+
     cbData.cb = discoveryReqCB;
     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
     cbData.cd = NULL;
-    if (UNICAST_DISCOVERY)
-    {
-        ret = OCDoResource(NULL, OC_REST_GET, szQueryUri, 0, 0, OC_CONNTYPE,
-                OC_LOW_QOS, &cbData, NULL, 0);
-    }
-    else
-    {
-        ret = OCDoResource(NULL, OC_REST_DISCOVER, szQueryUri, 0, 0, CT_DEFAULT,
-                OC_LOW_QOS, &cbData, NULL, 0);
-    }
 
+    ret = OCDoResource(NULL, OC_REST_DISCOVER, queryUri, 0, 0, CT_DEFAULT,
+                       OC_LOW_QOS, &cbData, NULL, 0);
     if (ret != OC_STACK_OK)
     {
         OC_LOG(ERROR, TAG, "OCStack resource error");
@@ -378,48 +368,9 @@ int InitDiscovery()
     return ret;
 }
 
-const char *getIPAddr(const OCClientResponse *clientResponse)
-{
-    if (!clientResponse)
-    {
-        return "";
-    }
-
-    const OCDevAddr *devAddr = &clientResponse->devAddr;
-    char *ipaddr = (char *) OICCalloc(1, strlen(devAddr->addr) +1);
-    if (ipaddr)
-    {
-        snprintf(ipaddr, MAX_IP_ADDR_ST_SZ, "%s", devAddr->addr);
-    }
-    else
-    {
-        OC_LOG(ERROR, TAG, "Memory not allocated to ipaddr");
-    }
-    return ipaddr;
-}
-
-const char *getPort(const OCClientResponse *clientResponse)
-{
-    if(!clientResponse)
-    {
-        return "";
-    }
-
-    char *port = NULL;
-    if((port = (char *)OICCalloc(1, MAX_PORT_ST_SZ)))
-    {
-        snprintf(port, MAX_PORT_ST_SZ, "%d", clientResponse->devAddr.port);
-    }
-    else
-    {
-        OC_LOG(ERROR, TAG, "Memory not allocated to port");
-    }
-    return port;
-}
-
 void queryResource()
 {
-    switch(TEST_CASE)
+    switch(TestCase)
     {
         case TEST_DISCOVER_REQ:
             break;
@@ -507,9 +458,7 @@ int insertResource(const char * sid, char const * uri,
     {
         iter->sid = sid_cpy;
         iter->uri = uri_cpy;
-        iter->ip = getIPAddr(clientResponse);
-        iter->port = getPort(clientResponse);
-        iter->connType = clientResponse->connType;
+        iter->endpoint = clientResponse->devAddr;
         iter->next = NULL;
     }
     else
@@ -543,9 +492,9 @@ void printResourceList()
         OC_LOG(INFO, TAG, "*****************************************************");
         OC_LOG_V(INFO, TAG, "sid = %s",iter->sid);
         OC_LOG_V(INFO, TAG, "uri = %s", iter->uri);
-        OC_LOG_V(INFO, TAG, "ip = %s", iter->ip);
-        OC_LOG_V(INFO, TAG, "port = %s", iter->port);
-        switch (iter->connType & CT_MASK_ADAPTER)
+        OC_LOG_V(INFO, TAG, "ip = %s", iter->endpoint.addr);
+        OC_LOG_V(INFO, TAG, "port = %d", iter->endpoint.port);
+        switch (iter->endpoint.adapter)
         {
             case OC_ADAPTER_IP:
                 OC_LOG(INFO, TAG, "connType = Default (IPv4)");
@@ -576,8 +525,6 @@ void freeResourceList()
         resourceList = resourceList->next;
         OICFree((void *)temp->sid);
         OICFree((void *)temp->uri);
-        OICFree((void *)temp->ip);
-        OICFree((void *)temp->port);
         OICFree(temp);
     }
     resourceList = NULL;
@@ -592,14 +539,13 @@ int main(int argc, char* argv[])
         switch(opt)
         {
             case 'u':
-                UNICAST_DISCOVERY = atoi(optarg);
+                UnicastDiscovery = atoi(optarg);
                 break;
             case 't':
-                TEST_CASE = atoi(optarg);
+                TestCase = atoi(optarg);
                 break;
             case 'c':
-
-                CONNECTIVITY = atoi(optarg);
+                Connectivity = atoi(optarg);
                 break;
             default:
                 PrintUsage();
@@ -607,24 +553,24 @@ int main(int argc, char* argv[])
         }
     }
 
-    if ((UNICAST_DISCOVERY != 0 && UNICAST_DISCOVERY != 1) ||
-        (TEST_CASE < TEST_DISCOVER_REQ || TEST_CASE >= MAX_TESTS) ||
-        (CONNECTIVITY < CT_ADAPTER_DEFAULT || CONNECTIVITY >= MAX_CT))
+    if ((UnicastDiscovery != 0 && UnicastDiscovery != 1) ||
+        (TestCase < TEST_DISCOVER_REQ || TestCase >= MAX_TESTS) ||
+        (Connectivity < CT_ADAPTER_DEFAULT || Connectivity >= MAX_CT))
     {
         PrintUsage();
         return -1;
     }
 
     /* Initialize OCStack*/
-    if (OCInit(NULL, 0, OC_CLIENT) != OC_STACK_OK)
+    if (OCInit1(OC_CLIENT, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS) != OC_STACK_OK)
     {
         OC_LOG(ERROR, TAG, "OCStack init error");
         return 0;
     }
 
-    if(CONNECTIVITY == CT_ADAPTER_DEFAULT || CONNECTIVITY ==  CT_IP)
+    if(Connectivity == CT_ADAPTER_DEFAULT || Connectivity ==  CT_IP)
     {
-        OC_CONNTYPE =  CT_ADAPTER_IP;//CT_DEFAULT;
+        ConnType =  CT_ADAPTER_IP;//CT_DEFAULT;
     }
     else
     {
index 012a11a..15c0dfd 100644 (file)
@@ -28,9 +28,6 @@
 //-----------------------------------------------------------------------------
 #define TAG "occlientbasicops"
 #define DEFAULT_CONTEXT_VALUE 0x99
-#ifndef MAX_LENGTH_IPv4_ADDR
-#define MAX_LENGTH_IPv4_ADDR 16
-#endif
 
 //-----------------------------------------------------------------------------
 // Typedefs
@@ -63,9 +60,7 @@ struct ResourceNode
 {
     const char * sid;
     const char * uri;
-    const char * ip;
-    const char * port;
-    OCConnectivityType connType;
+    OCDevAddr endpoint;
     ResourceNode * next;
 };
 
@@ -76,12 +71,6 @@ struct ResourceNode
 /* call getResult in common.cpp to get the result in string format. */
 const char *getResult(OCStackResult result);
 
-/* Get the IP address of the server */
-const char * getIPAddr(const OCClientResponse * clientResponse);
-
-/* Get the port number the server is listening on */
-const char * getPort(const OCClientResponse * clientResponse);
-
 /* Performs GET/PUT/POST query on most recently discovered resource*/
 void queryResource();
 
@@ -132,7 +121,7 @@ void parseClientResponse(OCClientResponse * clientResponse);
  * to the lower layers
  */
 OCStackResult InvokeOCDoResource(std::ostringstream &query,
-        OCMethod method, OCQualityOfService qos,
+        OCMethod method, OCDevAddr *dest, OCQualityOfService qos,
         OCClientResponseHandler cb, OCHeaderOption * options, uint8_t numOptions);
 
 /*
index 23392f9..c023c26 100644 (file)
@@ -30,8 +30,6 @@
 #include "payload_logging.h"
 #include "logger.h"
 const char *getResult(OCStackResult result);
-std::string getIPAddrTBServer(OCClientResponse * clientResponse);
-std::string getPortTBServer(OCClientResponse * clientResponse);
 std::string getQueryStrForGetPut();
 
 #define TAG PCF("occlient")
@@ -63,10 +61,10 @@ typedef enum {
     CT_ADAPTER_DEFAULT = 0,
     CT_IP,
     MAX_CT
-} CLIENT_CONNECTIVITY_TYPE;
+} CLIENT_ConnectivityType_TYPE;
 
-unsigned static int TEST = TEST_INVALID;
-unsigned static int CONNECTIVITY = 0;
+unsigned static int TestType = TEST_INVALID;
+unsigned static int ConnectivityType = 0;
 
 typedef struct
 {
@@ -90,8 +88,8 @@ testToTextMap queryInterface[] = {
 
 //The following variable determines the interface protocol (IP, etc)
 //to be used for sending unicast messages. Default set to IP.
-static OCConnectivityType OC_CONNTYPE = CT_ADAPTER_IP;
-static const char * MULTICAST_RESOURCE_DISCOVERY_QUERY = "/oic/res";
+static OCConnectivityType ConnType = CT_ADAPTER_IP;
+static const char * RESOURCE_DISCOVERY_QUERY = "/oic/res";
 
 // The handle for the observe registration
 OCDoHandle gObserveDoHandle;
@@ -202,17 +200,16 @@ OCStackApplicationResult getReqCB(void* ctx, OCDoHandle /*handle*/,
             }
         }
     }
-    if(TEST == TEST_PUT_DEFAULT || TEST == TEST_PUT_BATCH || TEST == TEST_PUT_LINK_LIST)
+    if(TestType == TEST_PUT_DEFAULT || TestType == TEST_PUT_BATCH || TestType == TEST_PUT_LINK_LIST)
     {
         InitPutRequest(clientResponse);
     }
     return OC_STACK_KEEP_TRANSACTION;
 }
 
-
 // This is a function called back when a device is discovered
 OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle /*handle*/,
-        OCClientResponse * clientResponse)
+                                        OCClientResponse * clientResponse)
 {
     OC_LOG(INFO, TAG,
             "Entering discoveryReqCB (Application Layer CB)");
@@ -230,10 +227,10 @@ OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle /*handle*/,
             clientResponse->devAddr.port);
     OC_LOG_PAYLOAD(INFO, TAG, clientResponse->payload);
 
-    OC_CONNTYPE = clientResponse->connType;
+    ConnType = clientResponse->connType;
 
-    if(TEST == TEST_UNKNOWN_RESOURCE_GET_DEFAULT || TEST == TEST_UNKNOWN_RESOURCE_GET_BATCH ||\
-            TEST == TEST_UNKNOWN_RESOURCE_GET_LINK_LIST)
+    if(TestType == TEST_UNKNOWN_RESOURCE_GET_DEFAULT || TestType == TEST_UNKNOWN_RESOURCE_GET_BATCH ||\
+            TestType == TEST_UNKNOWN_RESOURCE_GET_LINK_LIST)
     {
         InitGetRequestToUnavailableResource(clientResponse);
     }
@@ -250,14 +247,14 @@ int InitGetRequestToUnavailableResource(OCClientResponse * clientResponse)
     OCStackResult ret;
     OCCallbackData cbData;
     std::ostringstream getQuery;
-    getQuery << "coap://" << clientResponse->devAddr.addr << ":" <<
-            clientResponse->devAddr.port << "/SomeUnknownResource";
+    getQuery << "/SomeUnknownResource";
     cbData.cb = getReqCB;
     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
     cbData.cd = NULL;
 
-    ret = OCDoResource(NULL, OC_REST_GET, getQuery.str().c_str(), 0, 0, OC_CONNTYPE, OC_LOW_QOS,
-            &cbData, NULL, 0);
+    ret = OCDoResource(NULL, OC_REST_GET, getQuery.str().c_str(),
+                       &clientResponse->devAddr, 0, ConnType, OC_LOW_QOS,
+                       &cbData, NULL, 0);
     if (ret != OC_STACK_OK)
     {
         OC_LOG(ERROR, TAG, "OCStack resource error");
@@ -272,9 +269,7 @@ int InitObserveRequest(OCClientResponse * clientResponse)
     OCCallbackData cbData;
     OCDoHandle handle;
     std::ostringstream obsReg;
-    obsReg << "coap://" << clientResponse->devAddr.addr << ":" <<
-            clientResponse->devAddr.addr <<
-            getQueryStrForGetPut();
+    obsReg << getQueryStrForGetPut();
     cbData.cb = getReqCB;
     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
     cbData.cd = NULL;
@@ -283,8 +278,9 @@ int InitObserveRequest(OCClientResponse * clientResponse)
     OC_LOG_PAYLOAD(INFO, TAG, payload);
     OCPayloadDestroy(payload);
 
-    ret = OCDoResource(&handle, OC_REST_OBSERVE, obsReg.str().c_str(), 0, 0, OC_CONNTYPE,
-            OC_LOW_QOS, &cbData, NULL, 0);
+    ret = OCDoResource(&handle, OC_REST_OBSERVE, obsReg.str().c_str(),
+                       &clientResponse->devAddr, 0, ConnType,
+                       OC_LOW_QOS, &cbData, NULL, 0);
     if (ret != OC_STACK_OK)
     {
         OC_LOG(ERROR, TAG, "OCStack resource error");
@@ -305,7 +301,7 @@ int InitPutRequest(OCClientResponse * clientResponse)
     std::ostringstream getQuery;
     getQuery << "coap://" << clientResponse->devAddr.addr << ":" <<
             clientResponse->devAddr.port <<
-            "/a/room" << queryInterface[TEST].text;
+            "/a/room" << queryInterface[TestType].text;
     cbData.cb = putReqCB;
     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
     cbData.cd = NULL;
@@ -314,8 +310,9 @@ int InitPutRequest(OCClientResponse * clientResponse)
     OC_LOG_PAYLOAD(INFO, TAG, payload);
     OCPayloadDestroy(payload);
 
-    ret = OCDoResource(NULL, OC_REST_PUT, getQuery.str().c_str(), 0, putPayload(),
-                        OC_CONNTYPE, OC_LOW_QOS, &cbData, NULL, 0);
+    ret = OCDoResource(NULL, OC_REST_PUT, getQuery.str().c_str(),
+                       &clientResponse->devAddr, putPayload(), ConnType,
+                       OC_LOW_QOS, &cbData, NULL, 0);
     if (ret != OC_STACK_OK)
     {
         OC_LOG(ERROR, TAG, "OCStack resource error");
@@ -331,18 +328,16 @@ int InitGetRequest(OCClientResponse * clientResponse)
 
     //* Make a GET query*/
     std::ostringstream getQuery;
-    getQuery << "coap://" << clientResponse->devAddr.addr << ":" <<
-            clientResponse->devAddr.port <<
-            "/a/room" << queryInterface[TEST].text;
+    getQuery << "/a/room" << queryInterface[TestType].text;
 
     std::cout << "Get Query: " << getQuery.str() << std::endl;
 
     cbData.cb = getReqCB;
     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
     cbData.cd = NULL;
-    ret = OCDoResource(NULL, OC_REST_GET,
-            getQuery.str().c_str(), 0, 0, OC_CONNTYPE, OC_LOW_QOS,
-            &cbData, NULL, 0);
+    ret = OCDoResource(NULL, OC_REST_GET, getQuery.str().c_str(),
+                       &clientResponse->devAddr, 0, ConnType, OC_LOW_QOS,
+                       &cbData, NULL, 0);
     if (ret != OC_STACK_OK)
     {
         OC_LOG(ERROR, TAG, "OCStack resource error");
@@ -357,12 +352,12 @@ int InitDiscovery()
     /* Start a discovery query*/
     char szQueryUri[64] = { 0 };
 
-    strcpy(szQueryUri, MULTICAST_RESOURCE_DISCOVERY_QUERY);
+    strcpy(szQueryUri, RESOURCE_DISCOVERY_QUERY);
 
     cbData.cb = discoveryReqCB;
     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
     cbData.cd = NULL;
-    ret = OCDoResource(NULL, OC_REST_DISCOVER, szQueryUri, 0, 0, OC_CONNTYPE,
+    ret = OCDoResource(NULL, OC_REST_DISCOVER, szQueryUri, NULL, 0, ConnType,
                         OC_LOW_QOS,
             &cbData, NULL, 0);
     if (ret != OC_STACK_OK)
@@ -381,18 +376,18 @@ int main(int argc, char* argv[])
         switch (opt)
         {
             case 't':
-                TEST = atoi(optarg);
+                TestType = atoi(optarg);
                 break;
             case 'c':
-                CONNECTIVITY = atoi(optarg);
+                ConnectivityType = atoi(optarg);
                 break;
             default:
                 PrintUsage();
                 return -1;
         }
     }
-    if ((TEST <= TEST_INVALID || TEST >= MAX_TESTS) ||
-        CONNECTIVITY >= MAX_CT)
+    if ((TestType <= TEST_INVALID || TestType >= MAX_TESTS) ||
+        ConnectivityType >= MAX_CT)
     {
         PrintUsage();
         return -1;
@@ -405,14 +400,14 @@ int main(int argc, char* argv[])
         return 0;
     }
 
-    if(CONNECTIVITY == CT_ADAPTER_DEFAULT || CONNECTIVITY == CT_IP)
+    if(ConnectivityType == CT_ADAPTER_DEFAULT || ConnectivityType == CT_IP)
     {
-        OC_CONNTYPE = CT_ADAPTER_IP;
+        ConnType = CT_ADAPTER_IP;
     }
     else
     {
         OC_LOG(INFO, TAG, "Default Connectivity type selected...");
-        OC_CONNTYPE = CT_ADAPTER_IP;
+        ConnType = CT_ADAPTER_IP;
     }
 
     InitDiscovery();
index abf0e52..8b98b52 100644 (file)
 #include "payload_logging.h"
 
 // Tracking user input
-static int UNICAST_DISCOVERY = 0;
-static int TEST_CASE = 0;
-static int CONNECTIVITY = 0;
+static int UnicastDiscovery = 0;
+static int TestCase = 0;
+static int ConnectivityType = 0;
 
-static const char * UNICAST_DISCOVERY_QUERY = "coap://%s/oic/res";
-static std::string coapServerIP = "255.255.255.255";
-static uint16_t coapServerPort = 5683;
 static std::string coapServerResource = "/a/led";
 
 //The following variable determines the interface protocol (IP, etc)
 //to be used for sending unicast messages. Default set to IP.
-static OCConnectivityType OC_CONNTYPE = CT_ADAPTER_IP;
-static const char * MULTICAST_RESOURCE_DISCOVERY_QUERY = "/oic/res";
-static int IPV4_ADDR_SIZE = 24;
+static OCConnectivityType AdapterType = CT_ADAPTER_IP;
+static OCDevAddr endpoint;
+static const char *RESOURCE_DISCOVERY_QUERY = "%s/oic/res";
 void StripNewLineChar(char* str);
 
 int gQuitFlag = 0;
@@ -62,7 +59,7 @@ void handleSigInt(int signum)
 
 static void PrintUsage()
 {
-    OC_LOG(INFO, TAG, "Usage : occlient -c <0|1|2> -u <0|1> -t <1|2|3>");
+    OC_LOG(INFO, TAG, "Usage : occlient -c <0|1> -u <0|1> -t <1|2|3>");
     OC_LOG(INFO, TAG, "-c 0 : Default auto-selection");
     OC_LOG(INFO, TAG, "-c 1 : IP Connectivity Type");
     OC_LOG(INFO, TAG, "-u <0|1> : Perform multicast/unicast discovery of resources");
@@ -90,7 +87,7 @@ OCPayload* putPayload()
 }
 
 OCStackResult InvokeOCDoResource(std::ostringstream &query,
-        OCMethod method, OCQualityOfService qos,
+        OCMethod method, OCDevAddr *dest, OCQualityOfService qos,
         OCClientResponseHandler cb, OCHeaderOption * options, uint8_t numOptions)
 {
     OCStackResult ret;
@@ -100,9 +97,9 @@ OCStackResult InvokeOCDoResource(std::ostringstream &query,
     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
     cbData.cd = NULL;
 
-    ret = OCDoResource(NULL, method, query.str().c_str(), 0,
+    ret = OCDoResource(NULL, method, query.str().c_str(), dest,
             (method == OC_REST_PUT) ? putPayload() : NULL,
-            OC_CONNTYPE, qos, &cbData, options, numOptions);
+            AdapterType, qos, &cbData, options, numOptions);
 
     if (ret != OC_STACK_OK)
     {
@@ -167,9 +164,9 @@ OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
             clientResponse->devAddr.addr, clientResponse->devAddr.port);
         OC_LOG_PAYLOAD (INFO, TAG, clientResponse->payload);
 
-        parseClientResponse(clientResponse);
+        endpoint = clientResponse->devAddr;
 
-        switch(TEST_CASE)
+        switch(TestCase)
         {
             case TEST_NON_CON_OP:
                 InitGetRequest(OC_LOW_QOS);
@@ -189,7 +186,7 @@ OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
         }
     }
 
-    return (UNICAST_DISCOVERY) ? OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION ;
+    return UnicastDiscovery ? OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION ;
 
 }
 
@@ -197,62 +194,56 @@ int InitGetRequest(OCQualityOfService qos)
 {
     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
     std::ostringstream query;
-    query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
+    query << coapServerResource;
     OC_LOG_V (INFO, TAG, "Performing GET with query : %s", query.str().c_str());
-    return (InvokeOCDoResource(query, OC_REST_GET, (qos == OC_HIGH_QOS)?
-            OC_HIGH_QOS:OC_LOW_QOS, getReqCB, NULL, 0));
+    return (InvokeOCDoResource(query, OC_REST_GET, &endpoint,
+                               (qos == OC_HIGH_QOS)? OC_HIGH_QOS : OC_LOW_QOS,
+                               getReqCB, NULL, 0));
 }
 
 int InitPutRequest(OCQualityOfService qos)
 {
     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
     std::ostringstream query;
-    query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
+    query << coapServerResource;
     OC_LOG_V (INFO, TAG, "Performing PUT with query : %s", query.str().c_str());
-    return (InvokeOCDoResource(query, OC_REST_PUT, (qos == OC_HIGH_QOS)?
-            OC_HIGH_QOS:OC_LOW_QOS, getReqCB, NULL, 0));
+    return (InvokeOCDoResource(query, OC_REST_PUT, &endpoint,
+                               (qos == OC_HIGH_QOS)?  OC_HIGH_QOS:OC_LOW_QOS,
+                               getReqCB, NULL, 0));
 }
 
 int InitDiscovery()
 {
     OCStackResult ret;
     OCCallbackData cbData;
-    /* Start a discovery query*/
-    char szQueryUri[64] = { 0 };
-    if (UNICAST_DISCOVERY)
+    char queryUri[200];
+    char ipaddr[100] = { '\0' };
+
+    if (UnicastDiscovery)
     {
-        char ipv4addr[IPV4_ADDR_SIZE];
-        OC_LOG(INFO, TAG, "Enter IPv4:port of the Server hosting resource"\
-                "(Ex: 192.168.0.15:1234)");
-        if (fgets(ipv4addr, IPV4_ADDR_SIZE, stdin))
+        OC_LOG(INFO, TAG, "Enter IP address (with optional port) of the Server hosting resource\n");
+        OC_LOG(INFO, TAG, "IPv4: 192.168.0.15:45454\n");
+        OC_LOG(INFO, TAG, "IPv6: [fe80::20c:29ff:fe1b:9c5]:45454\n");
+
+        if (fgets(ipaddr, sizeof (ipaddr), stdin))
         {
-            //Strip newline char from ipv4addr
-            StripNewLineChar(ipv4addr);
-            snprintf(szQueryUri, sizeof(szQueryUri), UNICAST_DISCOVERY_QUERY, ipv4addr);
+            StripNewLineChar(ipaddr); //Strip newline char from ipaddr
         }
         else
         {
-            OC_LOG(ERROR, TAG, "!! Bad input for IPV4 address. !!");
+            OC_LOG(ERROR, TAG, "!! Bad input for IP address. !!");
             return OC_STACK_INVALID_PARAM;
         }
     }
-    else
-    {
-        OICStrcpy(szQueryUri, sizeof(szQueryUri), MULTICAST_RESOURCE_DISCOVERY_QUERY);
-    }
+
+    snprintf(queryUri, sizeof (queryUri), RESOURCE_DISCOVERY_QUERY, ipaddr);
+
     cbData.cb = discoveryReqCB;
     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
     cbData.cd = NULL;
-    if(UNICAST_DISCOVERY)
-    {
-        ret = OCDoResource(NULL, OC_REST_GET, szQueryUri, 0, 0, OC_CONNTYPE,
-                OC_LOW_QOS, &cbData, NULL, 0);
-    }
-    else
-    {
-        ret = OCDoResource(NULL, OC_REST_DISCOVER, szQueryUri, 0, 0, CT_DEFAULT,
-                OC_LOW_QOS, &cbData, NULL, 0);
-    }
+
+    ret = OCDoResource(NULL, OC_REST_DISCOVER, queryUri, 0, 0, CT_DEFAULT,
+                       OC_LOW_QOS, &cbData, NULL, 0);
     if (ret != OC_STACK_OK)
     {
         OC_LOG(ERROR, TAG, "OCStack resource error");
@@ -269,13 +260,13 @@ int main(int argc, char* argv[])
         switch(opt)
         {
             case 'u':
-                UNICAST_DISCOVERY = atoi(optarg);
+                UnicastDiscovery = atoi(optarg);
                 break;
             case 't':
-                TEST_CASE = atoi(optarg);
+                TestCase = atoi(optarg);
                 break;
             case 'c':
-                CONNECTIVITY = atoi(optarg);
+                ConnectivityType = atoi(optarg);
                 break;
             default:
                 PrintUsage();
@@ -283,9 +274,9 @@ int main(int argc, char* argv[])
         }
     }
 
-    if ((UNICAST_DISCOVERY != 0 && UNICAST_DISCOVERY != 1) ||
-            (TEST_CASE < TEST_DISCOVER_REQ || TEST_CASE >= MAX_TESTS) ||
-            (CONNECTIVITY < CT_ADAPTER_DEFAULT || CONNECTIVITY >= MAX_CT))
+    if ((UnicastDiscovery != 0 && UnicastDiscovery != 1) ||
+            (TestCase < TEST_DISCOVER_REQ || TestCase >= MAX_TESTS) ||
+            (ConnectivityType < CT_ADAPTER_DEFAULT || ConnectivityType >= MAX_CT))
     {
         PrintUsage();
         return -1;
@@ -298,14 +289,14 @@ int main(int argc, char* argv[])
         return 0;
     }
 
-    if(CONNECTIVITY == CT_ADAPTER_DEFAULT || CONNECTIVITY == CT_IP)
+    if(ConnectivityType == CT_ADAPTER_DEFAULT || ConnectivityType == CT_IP)
     {
-        OC_CONNTYPE = CT_ADAPTER_IP;
+        AdapterType = CT_ADAPTER_IP;
     }
     else
     {
         OC_LOG(INFO, TAG, "Default Connectivity type selected...");
-        OC_CONNTYPE = CT_ADAPTER_IP;
+        AdapterType = CT_ADAPTER_IP;
     }
 
     InitDiscovery();
@@ -338,10 +329,3 @@ std::string getQueryStrForGetPut(OCClientResponse * clientResponse)
     return "/a/led";
 }
 
-void parseClientResponse(OCClientResponse * clientResponse)
-{
-    coapServerIP = clientResponse->devAddr.addr;
-    coapServerPort = clientResponse->devAddr.port;
-    coapServerResource = getQueryStrForGetPut(clientResponse);
-}
-
index b375da1..41a9b66 100644 (file)
 #include "common.h"
 
 #define TAG "occlientbasicops"
-static int UNICAST_DISCOVERY = 0;
-static int TEST_CASE = 0;
-static int CONN_TYPE = 0;
+static int UnicastDiscovery = 0;
+static int TestCase = 0;
+static int ConnType = 0;
 
-static int IPV4_ADDR_SIZE = 24;
-static char UNICAST_DISCOVERY_QUERY[] = "coap://%s/oic/res";
-static char MULTICAST_DISCOVERY_QUERY[] = "/oic/res";
+static char DISCOVERY_QUERY[] = "%s/oic/res";
 OCConnectivityType discoveryReqConnType = CT_ADAPTER_IP;
+static OCDevAddr endpoint;
 
-static std::string coapServerIP;
-static std::string coapServerPort;
 static std::string coapServerResource;
 static int coapSecureResource;
 static OCConnectivityType ocConnType;
 
-
 //Secure Virtual Resource database for Iotivity Client application
 //It contains Client's Identity and the PSK credentials
 //of other devices which the client trusts
@@ -92,12 +88,15 @@ static void PrintUsage()
             " Initiate Nonconfirmable Get/Put/Post Requests");
     OC_LOG(INFO, TAG, "-t 3 : Discover Resources and Initiate Confirmable Get/Put/Post Requests");
     OC_LOG(INFO, TAG, "-c 0 : Default auto-selection");
-    OC_LOG(INFO, TAG, "-c 1 : IPv4 Connectivity Type");
+    OC_LOG(INFO, TAG, "-c 1 : IP Connectivity Type");
 }
 
 OCStackResult InvokeOCDoResource(std::ostringstream &query,
-        OCMethod method, OCQualityOfService qos,
-        OCClientResponseHandler cb, OCHeaderOption * options, uint8_t numOptions)
+                                 OCMethod method,
+                                 const OCDevAddr *dest,
+                                 OCQualityOfService qos,
+                                 OCClientResponseHandler cb,
+                                 OCHeaderOption * options, uint8_t numOptions)
 {
     OCStackResult ret;
     OCCallbackData cbData;
@@ -106,7 +105,7 @@ OCStackResult InvokeOCDoResource(std::ostringstream &query,
     cbData.context = NULL;
     cbData.cd = NULL;
 
-    ret = OCDoResource(NULL, method, query.str().c_str(), 0,
+    ret = OCDoResource(NULL, method, query.str().c_str(), dest,
             (method == OC_REST_PUT || method == OC_REST_POST) ? putPayload() : NULL,
             ocConnType, qos, &cbData, options, numOptions);
 
@@ -118,7 +117,7 @@ OCStackResult InvokeOCDoResource(std::ostringstream &query,
     return ret;
 }
 
-OCStackApplicationResult putReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse)
+OCStackApplicationResult putReqCB(void*, OCDoHandle, OCClientResponse * clientResponse)
 {
     OC_LOG(INFO, TAG, "Callback Context for PUT recvd successfully");
 
@@ -131,7 +130,7 @@ OCStackApplicationResult putReqCB(void* ctx, OCDoHandle handle, OCClientResponse
     return OC_STACK_DELETE_TRANSACTION;
 }
 
-OCStackApplicationResult postReqCB(void *ctx, OCDoHandle handle, OCClientResponse *clientResponse)
+OCStackApplicationResult postReqCB(void *, OCDoHandle, OCClientResponse *clientResponse)
 {
     OC_LOG(INFO, TAG, "Callback Context for POST recvd successfully");
 
@@ -144,7 +143,7 @@ OCStackApplicationResult postReqCB(void *ctx, OCDoHandle handle, OCClientRespons
     return OC_STACK_DELETE_TRANSACTION;
 }
 
-OCStackApplicationResult getReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse)
+OCStackApplicationResult getReqCB(void*, OCDoHandle, OCClientResponse * clientResponse)
 {
     OC_LOG(INFO, TAG, "Callback Context for GET query recvd successfully");
 
@@ -159,7 +158,7 @@ OCStackApplicationResult getReqCB(void* ctx, OCDoHandle handle, OCClientResponse
 }
 
 // This is a function called back when a device is discovered
-OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
+OCStackApplicationResult discoveryReqCB(void*, OCDoHandle,
         OCClientResponse * clientResponse)
 {
     OC_LOG(INFO, TAG, "Callback Context for DISCOVER query recvd successfully");
@@ -177,10 +176,11 @@ OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
             OC_LOG_PAYLOAD(INFO, TAG, clientResponse->payload);
 
             ocConnType = clientResponse->connType;
+            endpoint = clientResponse->devAddr;
 
             if (parseClientResponse(clientResponse) != -1)
             {
-                switch(TEST_CASE)
+                switch(TestCase)
                 {
                     case TEST_NON_CON_OP:
                         InitGetRequest(OC_LOW_QOS);
@@ -197,7 +197,7 @@ OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
         }
     }
 
-    return (UNICAST_DISCOVERY) ? OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION ;
+    return (UnicastDiscovery) ? OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION ;
 
 }
 
@@ -205,9 +205,9 @@ int InitPutRequest(OCQualityOfService qos)
 {
     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
     std::ostringstream query;
-    query << (coapSecureResource ? "coaps://" : "coap://") << coapServerIP
-        << ":" << coapServerPort  << coapServerResource;
-    return (InvokeOCDoResource(query, OC_REST_PUT,
+    query << coapServerResource;
+    endpoint.flags = (OCTransportFlags)(endpoint.flags|OC_SECURE);
+    return (InvokeOCDoResource(query, OC_REST_PUT, &endpoint,
             ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS), putReqCB, NULL, 0));
 }
 
@@ -216,11 +216,11 @@ int InitPostRequest(OCQualityOfService qos)
     OCStackResult result;
     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
     std::ostringstream query;
-    query << (coapSecureResource ? "coaps://" : "coap://") << coapServerIP
-        << ":" << coapServerPort << coapServerResource;
+    query << coapServerResource;
+    endpoint.flags = (OCTransportFlags)(endpoint.flags|OC_SECURE);
 
     // First POST operation (to create an LED instance)
-    result = InvokeOCDoResource(query, OC_REST_POST,
+    result = InvokeOCDoResource(query, OC_REST_POST, &endpoint,
             ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
             postReqCB, NULL, 0);
     if (OC_STACK_OK != result)
@@ -230,7 +230,7 @@ int InitPostRequest(OCQualityOfService qos)
     }
 
     // Second POST operation (to create an LED instance)
-    result = InvokeOCDoResource(query, OC_REST_POST,
+    result = InvokeOCDoResource(query, OC_REST_POST, &endpoint,
             ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
             postReqCB, NULL, 0);
     if (OC_STACK_OK != result)
@@ -239,7 +239,7 @@ int InitPostRequest(OCQualityOfService qos)
     }
 
     // This POST operation will update the original resourced /a/led
-    return (InvokeOCDoResource(query, OC_REST_POST,
+    return (InvokeOCDoResource(query, OC_REST_POST, &endpoint,
                 ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
                 postReqCB, NULL, 0));
 }
@@ -248,45 +248,38 @@ int InitGetRequest(OCQualityOfService qos)
 {
     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
     std::ostringstream query;
-    query << (coapSecureResource ? "coaps://" : "coap://") << coapServerIP
-        << ":" << coapServerPort << coapServerResource;
+    query << coapServerResource;
+    endpoint.flags = (OCTransportFlags)(endpoint.flags|OC_SECURE);
 
-    return (InvokeOCDoResource(query, OC_REST_GET, (qos == OC_HIGH_QOS)?
-            OC_HIGH_QOS:OC_LOW_QOS, getReqCB, NULL, 0));
+    return (InvokeOCDoResource(query, OC_REST_GET, &endpoint,
+                ((qos == OC_HIGH_QOS)?  OC_HIGH_QOS:OC_LOW_QOS),
+                getReqCB, NULL, 0));
 }
 
 int InitDiscovery()
 {
     OCStackResult ret;
-    OCMethod method;
     OCCallbackData cbData;
-    char szQueryUri[MAX_URI_LENGTH] = { 0 };
+    char queryUri[200];
+    char ipaddr[100] = { '\0' };
 
-    if (UNICAST_DISCOVERY)
+    if (UnicastDiscovery)
     {
-        char ipv4addr[IPV4_ADDR_SIZE];
-        OC_LOG(INFO, TAG, "Enter IPv4 address:port of the Server hosting secure resource"\
-                "(Ex: 11.12.13.14:1234)\n");
-        if (fgets(ipv4addr, IPV4_ADDR_SIZE, stdin))
+        OC_LOG(INFO, TAG, "Enter IP address (with optional port) of the Server hosting resource\n");
+        OC_LOG(INFO, TAG, "IPv4: 192.168.0.15:45454\n");
+        OC_LOG(INFO, TAG, "IPv6: [fe80::20c:29ff:fe1b:9c5]:45454\n");
+
+        if (fgets(ipaddr, sizeof (ipaddr), stdin))
         {
-            //Strip newline char from ipv4addr
-            StripNewLineChar(ipv4addr);
-            snprintf(szQueryUri, sizeof(szQueryUri), UNICAST_DISCOVERY_QUERY, ipv4addr);
+            StripNewLineChar(ipaddr); //Strip newline char from ipaddr
         }
         else
         {
-            OC_LOG(ERROR, TAG, "!! Bad input for IPV4 address. !!");
+            OC_LOG(ERROR, TAG, "!! Bad input for IP address. !!");
             return OC_STACK_INVALID_PARAM;
         }
-        method = OC_REST_GET;
-    }
-    else
-    {
-        //Send discovery request on Wifi and Ethernet interface
-        discoveryReqConnType = CT_DEFAULT;
-        OICStrcpy(szQueryUri, sizeof(szQueryUri), MULTICAST_DISCOVERY_QUERY);
-        method = OC_REST_DISCOVER;
     }
+    snprintf(queryUri, sizeof (queryUri), DISCOVERY_QUERY, ipaddr);
 
     cbData.cb = discoveryReqCB;
     cbData.context = NULL;
@@ -294,12 +287,11 @@ int InitDiscovery()
 
     /* Start a discovery query*/
     OC_LOG_V(INFO, TAG, "Initiating %s Resource Discovery : %s\n",
-        (UNICAST_DISCOVERY) ? "Unicast" : "Multicast",
-        szQueryUri);
+        (UnicastDiscovery) ? "Unicast" : "Multicast",
+        queryUri);
 
-    ret = OCDoResource(NULL, method, szQueryUri, 0, 0,
-            discoveryReqConnType, OC_LOW_QOS,
-            &cbData, NULL, 0);
+    ret = OCDoResource(NULL, OC_REST_DISCOVER, queryUri, 0, 0, CT_DEFAULT,
+                       OC_LOW_QOS, &cbData, NULL, 0);
     if (ret != OC_STACK_OK)
     {
         OC_LOG(ERROR, TAG, "OCStack resource error");
@@ -323,13 +315,13 @@ int main(int argc, char* argv[])
         switch(opt)
         {
             case 'u':
-                UNICAST_DISCOVERY = atoi(optarg);
+                UnicastDiscovery = atoi(optarg);
                 break;
             case 't':
-                TEST_CASE = atoi(optarg);
+                TestCase = atoi(optarg);
                 break;
             case 'c':
-                CONN_TYPE = atoi(optarg);
+                ConnType = atoi(optarg);
                 break;
             default:
                 PrintUsage();
@@ -337,16 +329,16 @@ int main(int argc, char* argv[])
         }
     }
 
-    if ((UNICAST_DISCOVERY != 0 && UNICAST_DISCOVERY != 1) ||
-            (TEST_CASE < TEST_DISCOVER_REQ || TEST_CASE >= MAX_TESTS)||
-            (CONN_TYPE < CT_ADAPTER_DEFAULT || CONN_TYPE >= MAX_CT))
+    if ((UnicastDiscovery != 0 && UnicastDiscovery != 1) ||
+            (TestCase < TEST_DISCOVER_REQ || TestCase >= MAX_TESTS)||
+            (ConnType < CT_ADAPTER_DEFAULT || ConnType >= MAX_CT))
     {
         PrintUsage();
         return -1;
     }
 
 
-    if(CONN_TYPE == CT_ADAPTER_DEFAULT || CONN_TYPE ==  CT_IP)
+    if(ConnType == CT_ADAPTER_DEFAULT || ConnType ==  CT_IP)
     {
         discoveryReqConnType = CT_DEFAULT;
     }
@@ -358,12 +350,7 @@ int main(int argc, char* argv[])
 
 
     // Initialize Persistent Storage for SVR database
-    OCPersistentStorage ps = {};
-    ps.open = client_fopen;
-    ps.read = fread;
-    ps.write = fwrite;
-    ps.close = fclose;
-    ps.unlink = unlink;
+    OCPersistentStorage ps = { client_fopen, fread, fwrite, fclose, unlink };
     OCRegisterPersistentStorageHandler(&ps);
 
     /* Initialize OCStack*/
@@ -401,41 +388,27 @@ int main(int argc, char* argv[])
     return 0;
 }
 
-std::string getPortTBServer(OCClientResponse * clientResponse)
-{
-    if(!clientResponse) return "";
-    std::ostringstream ss;
-    ss << clientResponse->devAddr.port;
-    return ss.str();
-}
-
 int parseClientResponse(OCClientResponse * clientResponse)
 {
     OCResourcePayload* res = ((OCDiscoveryPayload*)clientResponse->payload)->resources;
 
     // Initialize all global variables
     coapServerResource.clear();
-    coapServerPort.clear();
-    coapServerIP.clear();
     coapSecureResource = 0;
 
-    while(res)
+    while (res)
     {
         coapServerResource.assign(res->uri);
         OC_LOG_V(INFO, TAG, "Uri -- %s", coapServerResource.c_str());
 
-        if(res->secure)
+        if (res->secure)
         {
+            endpoint.port = res->port;
             coapSecureResource = 1;
         }
 
         OC_LOG_V(INFO, TAG, "Secure -- %s", coapSecureResource == 1 ? "YES" : "NO");
 
-        std::ostringstream ss;
-        ss << res->port;
-        coapServerPort = ss.str();
-        std::cout<<"PORT: "<<coapServerPort;
-
         // If we discovered a secure resource, exit from here
         if (coapSecureResource)
         {
@@ -445,14 +418,6 @@ int parseClientResponse(OCClientResponse * clientResponse)
         res = res->next;
     }
 
-    coapServerIP = clientResponse->devAddr.addr;
-
-    if(coapServerPort.length() == 0 || coapServerPort == "0")
-    {
-        coapServerPort = getPortTBServer(clientResponse);
-        OC_LOG_V(INFO, TAG, "Hosting Server Port -- %s", coapServerPort.c_str());
-    }
-
     return 0;
 }
 
index d72c136..a95c618 100644 (file)
@@ -19,6 +19,7 @@
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
 #include "ocpayloadcbor.h"
+#include "platform_features.h"
 #include <stdlib.h>
 #include "oic_malloc.h"
 #include "logger.h"
 #include "cbor.h"
 
 #define TAG PCF("OCPayloadConvert")
+// Arbitrarily chosen size that seems to contain the majority of packages
+#define INIT_SIZE (255)
 
-static OCStackResult OCConvertDiscoveryPayload(OCDiscoveryPayload* payload, uint8_t** outPayload,
+// Functions all return either a CborError, or a negative version of the OC_STACK return values
+static int64_t OCConvertPayloadHelper(OCPayload* payload, uint8_t* outPayload, size_t* size);
+static int64_t OCConvertDiscoveryPayload(OCDiscoveryPayload* payload, uint8_t* outPayload,
         size_t* size);
-static OCStackResult OCConvertDevicePayload(OCDevicePayload* payload, uint8_t** outPayload,
+static int64_t OCConvertDevicePayload(OCDevicePayload* payload, uint8_t* outPayload,
         size_t* size);
-static OCStackResult OCConvertPlatformPayload(OCPlatformPayload* payload, uint8_t** outPayload,
+static int64_t OCConvertPlatformPayload(OCPlatformPayload* payload, uint8_t* outPayload,
         size_t* size);
-static OCStackResult OCConvertRepPayload(OCRepPayload* payload, uint8_t** outPayload, size_t* size);
-static OCStackResult OCConvertPresencePayload(OCPresencePayload* payload, uint8_t** outPayload,
+static int64_t OCConvertRepPayload(OCRepPayload* payload, uint8_t* outPayload, size_t* size);
+static int64_t OCConvertPresencePayload(OCPresencePayload* payload, uint8_t* outPayload,
         size_t* size);
-static OCStackResult OCConvertSecurityPayload(OCSecurityPayload* payload, uint8_t** outPayload,
+static int64_t OCConvertSecurityPayload(OCSecurityPayload* payload, uint8_t* outPayload,
         size_t* size);
+static int64_t OCConvertSingleRepPayload(CborEncoder* parent, const OCRepPayload* payload);
+static int64_t OCConvertArray(CborEncoder* parent, const OCRepPayloadValueArray* valArray);
 
-bool AddTextStringToMap(CborEncoder* map, const char* key, size_t keylen,
+static int64_t AddTextStringToMap(CborEncoder* map, const char* key, size_t keylen,
         const char* value);
 
-bool ConditionalAddTextStringToMap(CborEncoder* map, const char* key, size_t keylen,
+static int64_t ConditionalAddTextStringToMap(CborEncoder* map, const char* key, size_t keylen,
         const char* value);
 
+#define STRINGIFY(s) XSTRINGIFY(s)
+#define XSTRINGIFY(s) #s
 
 OCStackResult OCConvertPayload(OCPayload* payload, uint8_t** outPayload, size_t* size)
 {
+    // TinyCbor Version 47a78569c0 or better on master is required for the re-allocation
+    // strategy to work.  If you receive the following assertion error, please do a git-pull
+    // from the extlibs/tinycbor/tinycbor directory
+    #define CborNeedsUpdating  (CborErrorOutOfMemory < CborErrorDataTooLarge)
+    OC_STATIC_ASSERT(!CborNeedsUpdating, "tinycbor needs to be updated to at least 47a78569c0");
+    #undef CborNeedsUpdating
+    if (!payload)
+    {
+        OC_LOG(ERROR, TAG, PCF("Payload parameter NULL"));
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    if (!outPayload || !size)
+    {
+        OC_LOG(ERROR, TAG, PCF("Out parameter/s parameter NULL"));
+        return OC_STACK_INVALID_PARAM;
+    }
+
     OC_LOG_V(INFO, TAG, "Converting payload of type %d", payload->type);
+
+    size_t curSize = INIT_SIZE;
+    uint8_t* out = (uint8_t*)OICCalloc(1, curSize);
+    int64_t err = OCConvertPayloadHelper(payload, out, &curSize);
+
+    if (err == CborErrorOutOfMemory)
+    {
+        // reallocate "out" and try again!
+        uint8_t* out2 = (uint8_t*)OICRealloc(out, curSize);
+
+        if (!out2)
+        {
+            OICFree(out);
+            return OC_STACK_NO_MEMORY;
+        }
+
+        out = out2;
+        err = OCConvertPayloadHelper(payload, out, &curSize);
+    }
+
+    if (err == 0)
+    {
+        if (curSize < INIT_SIZE)
+        {
+            uint8_t* out2 = (uint8_t*)OICRealloc(out, curSize);
+
+            if (!out2)
+            {
+                OICFree(out);
+                return OC_STACK_NO_MEMORY;
+            }
+        }
+
+        *size = curSize;
+        *outPayload = out;
+        return OC_STACK_OK;
+    }
+    else if (err < 0)
+    {
+        return (OCStackResult)-err;
+    }
+    else
+    {
+        return OC_STACK_ERROR;
+    }
+}
+
+static int64_t OCConvertPayloadHelper(OCPayload* payload, uint8_t* outPayload, size_t* size)
+{
     switch(payload->type)
     {
         case PAYLOAD_TYPE_DISCOVERY:
@@ -71,82 +147,66 @@ OCStackResult OCConvertPayload(OCPayload* payload, uint8_t** outPayload, size_t*
     }
 }
 
-static OCStackResult OCConvertSecurityPayload(OCSecurityPayload* payload, uint8_t** outPayload,
-        size_t* size)
+static int64_t checkError(int64_t err, CborEncoder* encoder, uint8_t* outPayload, size_t* size)
 {
-    *outPayload = (uint8_t*)OICCalloc(1, MAX_REQUEST_LENGTH);
-    *size = MAX_REQUEST_LENGTH;
-
-    if(!*outPayload)
+    if (err == CborErrorOutOfMemory)
     {
-        return OC_STACK_NO_MEMORY;
+        *size += encoder->ptr - encoder->end;
+        return err;
     }
-
+    else if (err != 0)
+    {
+        OC_LOG_V(ERROR, TAG, "Convert Payload failed", err);
+        return err;
+    }
+    else
+    {
+        *size = encoder->ptr - outPayload;
+        return 0;
+    }
+}
+static int64_t OCConvertSecurityPayload(OCSecurityPayload* payload, uint8_t* outPayload,
+        size_t* size)
+{
     CborEncoder encoder;
-    bool err = false;
+    int64_t err = 0;
 
-    cbor_encoder_init(&encoder, *outPayload, *size, 0);
+    cbor_encoder_init(&encoder, outPayload, *size, 0);
 
     CborEncoder rootArray;
-    err = err || cbor_encoder_create_array(&encoder, &rootArray, 2);
-    err = err || cbor_encode_uint(&rootArray, PAYLOAD_TYPE_SECURITY);
+    err = err | cbor_encoder_create_array(&encoder, &rootArray, 2);
+    err = err | cbor_encode_uint(&rootArray, PAYLOAD_TYPE_SECURITY);
 
     CborEncoder map;
 
-    err = err || cbor_encoder_create_map(&rootArray, &map, CborIndefiniteLength);
+    err = err | cbor_encoder_create_map(&rootArray, &map, CborIndefiniteLength);
 
     if(payload->securityData)
     {
-        err = err || AddTextStringToMap(&map, OC_RSRVD_REPRESENTATION,
+        err = err | AddTextStringToMap(&map, OC_RSRVD_REPRESENTATION,
                 sizeof(OC_RSRVD_REPRESENTATION) - 1,
                 payload->securityData);
     }
 
-    err = err || cbor_encoder_close_container(&rootArray, &map);
-
-    err = err || cbor_encoder_close_container(&encoder, &rootArray);
-
-    if(err)
-    {
-        OC_LOG_V(ERROR, TAG, "Convert Security Payload failed", err);
-        OICFree(*outPayload);
-        return OC_STACK_ERROR;
-    }
-
-    *size = encoder.ptr - *outPayload;
-    uint8_t* tempPayload = (uint8_t*)OICRealloc(*outPayload, *size);
+    err = err | cbor_encoder_close_container(&rootArray, &map);
 
-    if(!tempPayload)
-    {
-        OC_LOG_V(ERROR, TAG, PCF("Payload realloc failed!"));
-        OICFree(*outPayload);
-        return OC_STACK_ERROR;
-    }
+    err = err | cbor_encoder_close_container(&encoder, &rootArray);
+    return checkError(err, &encoder, outPayload, size);
 
-    *outPayload = tempPayload;
-    return OC_STACK_OK;
 }
 
-static OCStackResult OCConvertDiscoveryPayload(OCDiscoveryPayload* payload, uint8_t** outPayload,
+static int64_t OCConvertDiscoveryPayload(OCDiscoveryPayload* payload, uint8_t* outPayload,
         size_t* size)
 {
-    *outPayload = (uint8_t*)OICCalloc(1, MAX_REQUEST_LENGTH);
-    *size = MAX_REQUEST_LENGTH;
-
-    if(!*outPayload)
-    {
-        return OC_STACK_NO_MEMORY;
-    }
-
     CborEncoder encoder = {0};
-    bool err = false;
+    int64_t err = 0;
     size_t resourceCount =  OCDiscoveryPayloadGetResourceCount(payload);
 
-    cbor_encoder_init(&encoder, *outPayload, *size, 0);
+    cbor_encoder_init(&encoder, outPayload, *size, 0);
 
     CborEncoder rootArray;
-    err = err || cbor_encoder_create_array(&encoder, &rootArray, 1 + resourceCount);
-    err = err || cbor_encode_uint(&rootArray, PAYLOAD_TYPE_DISCOVERY);
+    err = err | cbor_encoder_create_array(&encoder, &rootArray, 1 + resourceCount);
+    err = err | cbor_encode_uint(&rootArray, PAYLOAD_TYPE_DISCOVERY);
 
     for(size_t i = 0; i < resourceCount; ++i)
     {
@@ -155,333 +215,262 @@ static OCStackResult OCConvertDiscoveryPayload(OCDiscoveryPayload* payload, uint
 
         if(!resource)
         {
-            OICFree(*outPayload);
             return OC_STACK_INVALID_PARAM;
         }
 
-        err = err || cbor_encoder_create_map(&rootArray, &map, 3);
+        err = err | cbor_encoder_create_map(&rootArray, &map, 3);
         // Uri
-        err = err || AddTextStringToMap(&map, OC_RSRVD_HREF,
+        err = err | AddTextStringToMap(&map, OC_RSRVD_HREF,
                 sizeof(OC_RSRVD_HREF) - 1,
                 resource->uri);
 
         // Server ID
-        err = err || cbor_encode_text_string(&map, OC_RSRVD_SERVER_INSTANCE_ID,
+        err = err | cbor_encode_text_string(&map, OC_RSRVD_SERVER_INSTANCE_ID,
                 sizeof(OC_RSRVD_SERVER_INSTANCE_ID) - 1);
-        err = err || cbor_encode_byte_string(&map, resource->sid, UUID_SIZE);
+        err = err | cbor_encode_byte_string(&map, resource->sid, UUID_SIZE);
         // Prop Tag
         {
             CborEncoder propMap;
-            err = err || cbor_encode_text_string(&map, OC_RSRVD_PROPERTY,
+            err = err | cbor_encode_text_string(&map, OC_RSRVD_PROPERTY,
                     sizeof(OC_RSRVD_PROPERTY) -1 );
-            err = err || cbor_encoder_create_map(&map, &propMap, 3);
+            err = err | cbor_encoder_create_map(&map, &propMap, 3);
 
             // Resource Type
             {
                 CborEncoder rtArray;
-                err = err || cbor_encode_text_string(&propMap, OC_RSRVD_RESOURCE_TYPE,
+                err = err | cbor_encode_text_string(&propMap, OC_RSRVD_RESOURCE_TYPE,
                     sizeof(OC_RSRVD_RESOURCE_TYPE) - 1);
-                err = err || cbor_encoder_create_array(&propMap, &rtArray, CborIndefiniteLength);
+                err = err | cbor_encoder_create_array(&propMap, &rtArray, CborIndefiniteLength);
 
                 OCStringLL* rtPtr = resource->types;
                 while(rtPtr)
                 {
-                    err = err || cbor_encode_text_string(&rtArray, rtPtr->value,
+                    err = err | cbor_encode_text_string(&rtArray, rtPtr->value,
                             strlen(rtPtr->value));
                     rtPtr = rtPtr->next;
                 }
 
-                err = err || cbor_encoder_close_container(&propMap, &rtArray);
+                err = err | cbor_encoder_close_container(&propMap, &rtArray);
             }
 
             // Interface Types
             {
                 CborEncoder ifArray;
-                err = err || cbor_encode_text_string(&propMap, OC_RSRVD_INTERFACE,
+                err = err | cbor_encode_text_string(&propMap, OC_RSRVD_INTERFACE,
                         sizeof(OC_RSRVD_INTERFACE) - 1);
-                err = err || cbor_encoder_create_array(&propMap, &ifArray, CborIndefiniteLength);
+                err = err | cbor_encoder_create_array(&propMap, &ifArray, CborIndefiniteLength);
                 OCStringLL* ifPtr = resource->interfaces;
 
                 while(ifPtr)
                 {
-                    err = err || cbor_encode_text_string(&ifArray, ifPtr->value,
+                    err = err | cbor_encode_text_string(&ifArray, ifPtr->value,
                         strlen(ifPtr->value));
                     ifPtr= ifPtr->next;
                 }
 
-                err = err || cbor_encoder_close_container(&propMap, &ifArray);
+                err = err | cbor_encoder_close_container(&propMap, &ifArray);
             }
             // Policy
             {
                 CborEncoder policyMap;
-                err = err || cbor_encode_text_string(&propMap, OC_RSRVD_POLICY,
+                err = err | cbor_encode_text_string(&propMap, OC_RSRVD_POLICY,
                         sizeof(OC_RSRVD_POLICY) - 1);
-                err = err || cbor_encoder_create_map(&propMap, &policyMap, CborIndefiniteLength);
+                err = err | cbor_encoder_create_map(&propMap, &policyMap, CborIndefiniteLength);
 
                 // Bitmap
-                err = err || cbor_encode_text_string(&policyMap, OC_RSRVD_BITMAP,
+                err = err | cbor_encode_text_string(&policyMap, OC_RSRVD_BITMAP,
                         sizeof(OC_RSRVD_BITMAP) - 1);
-                err = err || cbor_encode_uint(&policyMap, resource->bitmap);
+                err = err | cbor_encode_uint(&policyMap, resource->bitmap);
 
                 if(resource->secure)
                 {
-                    err = err || cbor_encode_text_string(&policyMap, OC_RSRVD_SECURE,
+                    err = err | cbor_encode_text_string(&policyMap, OC_RSRVD_SECURE,
                             sizeof(OC_RSRVD_SECURE) - 1);
-                    err = err || cbor_encode_boolean(&policyMap, OC_RESOURCE_SECURE);
+                    err = err | cbor_encode_boolean(&policyMap, OC_RESOURCE_SECURE);
 
                     if(resource->port != 0)
                     {
-                        err = err || cbor_encode_text_string(&policyMap, OC_RSRVD_HOSTING_PORT,
+                        err = err | cbor_encode_text_string(&policyMap, OC_RSRVD_HOSTING_PORT,
                                 sizeof(OC_RSRVD_HOSTING_PORT) - 1);
-                        err = err || cbor_encode_uint(&policyMap, resource->port);
+                        err = err | cbor_encode_uint(&policyMap, resource->port);
                     }
                 }
 
-                err = err || cbor_encoder_close_container(&propMap, &policyMap);
+                err = err | cbor_encoder_close_container(&propMap, &policyMap);
             }
             // Close
-            err = err || cbor_encoder_close_container(&map, &propMap);
+            err = err | cbor_encoder_close_container(&map, &propMap);
         }
         // Close Item
-        err = err || cbor_encoder_close_container(&rootArray, &map);
+        err = err | cbor_encoder_close_container(&rootArray, &map);
     }
     // Close main array
-    err = err || cbor_encoder_close_container(&encoder, &rootArray);
+    err = err | cbor_encoder_close_container(&encoder, &rootArray);
 
-    if(err)
-    {
-        OC_LOG_V(ERROR, TAG, "Convert Discovery Payload failed with : %d", err);
-        return OC_STACK_ERROR;
-    }
-
-    *size = encoder.ptr - *outPayload;
-    uint8_t* tempPayload = (uint8_t*)OICRealloc(*outPayload, *size);
-
-    if(!tempPayload)
-    {
-        OC_LOG_V(ERROR, TAG, PCF("Payload realloc failed!"));
-        OICFree(*outPayload);
-        return OC_STACK_ERROR;
-    }
-
-    *outPayload = tempPayload;
-    return OC_STACK_OK;
+    return checkError(err, &encoder, outPayload, size);
 }
 
-static OCStackResult OCConvertDevicePayload(OCDevicePayload* payload, uint8_t** outPayload,
+static int64_t OCConvertDevicePayload(OCDevicePayload* payload, uint8_t* outPayload,
         size_t* size)
 {
-    *outPayload = (uint8_t*)OICCalloc(1, MAX_REQUEST_LENGTH);
-    *size = MAX_REQUEST_LENGTH;
-
-    if(!*outPayload)
-    {
-        return OC_STACK_NO_MEMORY;
-    }
-
     CborEncoder encoder = {0};
-    bool err = false;
+    int64_t err = 0;
 
-    cbor_encoder_init(&encoder, *outPayload, *size, 0);
+    cbor_encoder_init(&encoder, outPayload, *size, 0);
     CborEncoder rootArray;
-    err = err || cbor_encoder_create_array(&encoder, &rootArray, 2);
-    err = err || cbor_encode_uint(&rootArray, PAYLOAD_TYPE_DEVICE);
+    err = err | cbor_encoder_create_array(&encoder, &rootArray, 2);
+    err = err | cbor_encode_uint(&rootArray, PAYLOAD_TYPE_DEVICE);
 
     {
         CborEncoder map;
-        err = err || cbor_encoder_create_map(&rootArray, &map, 2);
+        err = err | cbor_encoder_create_map(&rootArray, &map, 2);
 
         // uri
-        err = err || AddTextStringToMap(&map, OC_RSRVD_HREF, sizeof(OC_RSRVD_HREF) - 1,
+        err = err | AddTextStringToMap(&map, OC_RSRVD_HREF, sizeof(OC_RSRVD_HREF) - 1,
                 payload->uri);
 
         // Rep Map
         {
             CborEncoder repMap;
-            err = err || cbor_encode_text_string(&map, OC_RSRVD_REPRESENTATION,
+            err = err | cbor_encode_text_string(&map, OC_RSRVD_REPRESENTATION,
                     sizeof(OC_RSRVD_REPRESENTATION) - 1);
-            err = err || cbor_encoder_create_map(&map, &repMap, 4);
+            err = err | cbor_encoder_create_map(&map, &repMap, 4);
 
             // Device ID
-            err = err || cbor_encode_text_string(&repMap, OC_RSRVD_DEVICE_ID,
+            err = err | cbor_encode_text_string(&repMap, OC_RSRVD_DEVICE_ID,
                     sizeof(OC_RSRVD_DEVICE_ID) - 1);
-            err = err || cbor_encode_byte_string(&repMap, payload->sid, UUID_SIZE);
+            err = err | cbor_encode_byte_string(&repMap, payload->sid, UUID_SIZE);
 
             // Device Name
-            err = err || AddTextStringToMap(&repMap, OC_RSRVD_DEVICE_NAME,
+            err = err | AddTextStringToMap(&repMap, OC_RSRVD_DEVICE_NAME,
                     sizeof(OC_RSRVD_DEVICE_NAME) - 1,
                     payload->deviceName);
 
             // Device Spec Version
-            err = err || AddTextStringToMap(&repMap, OC_RSRVD_SPEC_VERSION,
+            err = err | AddTextStringToMap(&repMap, OC_RSRVD_SPEC_VERSION,
                     sizeof(OC_RSRVD_SPEC_VERSION) - 1,
                     payload->specVersion);
 
             // Device data Model Version
-            err = err || AddTextStringToMap(&repMap, OC_RSRVD_DATA_MODEL_VERSION,
+            err = err | AddTextStringToMap(&repMap, OC_RSRVD_DATA_MODEL_VERSION,
                     sizeof(OC_RSRVD_DATA_MODEL_VERSION) - 1,
                     payload->dataModelVersion);
 
-            err = err || cbor_encoder_close_container(&map, &repMap);
+            err = err | cbor_encoder_close_container(&map, &repMap);
         }
 
         // Close Map
-        err = err || cbor_encoder_close_container(&rootArray, &map);
+        err = err | cbor_encoder_close_container(&rootArray, &map);
     }
 
     // Close main array
-    err = err || cbor_encoder_close_container(&encoder, &rootArray);
-
-    if(err)
-    {
-        OC_LOG_V(ERROR, TAG, "Convert Device Payload failed with : %d", err);
-        return OC_STACK_ERROR;
-    }
-
-    *size = encoder.ptr - *outPayload;
-    uint8_t* tempPayload = (uint8_t*)OICRealloc(*outPayload, *size);
-
-    if(!tempPayload)
-    {
-        OC_LOG_V(ERROR, TAG, PCF("Payload realloc failed!"));
-        OICFree(*outPayload);
-        return OC_STACK_ERROR;
-    }
+    err = err | cbor_encoder_close_container(&encoder, &rootArray);
 
-    *outPayload = tempPayload;
-    return OC_STACK_OK;
+    return checkError(err, &encoder, outPayload, size);
 }
 
-static OCStackResult OCConvertPlatformPayload(OCPlatformPayload* payload, uint8_t** outPayload,
+static int64_t OCConvertPlatformPayload(OCPlatformPayload* payload, uint8_t* outPayload,
         size_t* size)
 {
-    *outPayload = (uint8_t*)OICCalloc(1, MAX_REQUEST_LENGTH);
-    *size = MAX_REQUEST_LENGTH;
-
-    if(!*outPayload)
-    {
-        return OC_STACK_NO_MEMORY;
-    }
-
     CborEncoder encoder = {0};
-    bool err = false;
+    int64_t err = 0;
 
-    cbor_encoder_init(&encoder, *outPayload, *size, 0);
+    cbor_encoder_init(&encoder, outPayload, *size, 0);
     CborEncoder rootArray;
-    err = err || cbor_encoder_create_array(&encoder, &rootArray, 2);
-    err = err || cbor_encode_uint(&rootArray, PAYLOAD_TYPE_PLATFORM);
+    err = err | cbor_encoder_create_array(&encoder, &rootArray, 2);
+    err = err | cbor_encode_uint(&rootArray, PAYLOAD_TYPE_PLATFORM);
     {
         CborEncoder map;
-        err = err || cbor_encoder_create_map(&rootArray, &map, CborIndefiniteLength);
+        err = err | cbor_encoder_create_map(&rootArray, &map, CborIndefiniteLength);
 
         // uri
-        err = err || AddTextStringToMap(&map, OC_RSRVD_HREF, sizeof(OC_RSRVD_HREF) - 1,
+        err = err | AddTextStringToMap(&map, OC_RSRVD_HREF, sizeof(OC_RSRVD_HREF) - 1,
                 payload->uri);
 
         // Rep Map
         {
             CborEncoder repMap;
-            err = err || cbor_encode_text_string(&map, OC_RSRVD_REPRESENTATION,
+            err = err | cbor_encode_text_string(&map, OC_RSRVD_REPRESENTATION,
                     sizeof(OC_RSRVD_REPRESENTATION) - 1);
-            err = err || cbor_encoder_create_map(&map, &repMap, CborIndefiniteLength);
+            err = err | cbor_encoder_create_map(&map, &repMap, CborIndefiniteLength);
 
             // Platform ID
-            err = err || AddTextStringToMap(&repMap, OC_RSRVD_PLATFORM_ID,
+            err = err | AddTextStringToMap(&repMap, OC_RSRVD_PLATFORM_ID,
                     sizeof(OC_RSRVD_PLATFORM_ID) - 1,
                     payload->info.platformID);
 
             // MFG Name
-            err = err || AddTextStringToMap(&repMap, OC_RSRVD_MFG_NAME,
+            err = err | AddTextStringToMap(&repMap, OC_RSRVD_MFG_NAME,
                     sizeof(OC_RSRVD_MFG_NAME) - 1,
                     payload->info.manufacturerName);
 
             // MFG Url
-            err = err || ConditionalAddTextStringToMap(&repMap, OC_RSRVD_MFG_URL,
+            err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_MFG_URL,
                     sizeof(OC_RSRVD_MFG_URL) - 1,
                     payload->info.manufacturerUrl);
 
             // Model Num
-            err = err || ConditionalAddTextStringToMap(&repMap, OC_RSRVD_MODEL_NUM,
+            err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_MODEL_NUM,
                     sizeof(OC_RSRVD_MODEL_NUM) - 1,
                     payload->info.modelNumber);
 
             // Date of Mfg
-            err = err || ConditionalAddTextStringToMap(&repMap, OC_RSRVD_MFG_DATE,
+            err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_MFG_DATE,
                     sizeof(OC_RSRVD_MFG_DATE) - 1,
                     payload->info.dateOfManufacture);
 
             // Platform Version
-            err = err || ConditionalAddTextStringToMap(&repMap, OC_RSRVD_PLATFORM_VERSION,
+            err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_PLATFORM_VERSION,
                     sizeof(OC_RSRVD_PLATFORM_VERSION) - 1,
                     payload->info.platformVersion);
 
             // OS Version
-            err = err || ConditionalAddTextStringToMap(&repMap, OC_RSRVD_OS_VERSION,
+            err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_OS_VERSION,
                     sizeof(OC_RSRVD_OS_VERSION) - 1,
                     payload->info.operatingSystemVersion);
 
             // Hardware Version
-            err = err || ConditionalAddTextStringToMap(&repMap, OC_RSRVD_HARDWARE_VERSION,
+            err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_HARDWARE_VERSION,
                     sizeof(OC_RSRVD_HARDWARE_VERSION) - 1,
                     payload->info.hardwareVersion);
 
             // Firmware Version
-            err = err || ConditionalAddTextStringToMap(&repMap, OC_RSRVD_FIRMWARE_VERSION,
+            err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_FIRMWARE_VERSION,
                     sizeof(OC_RSRVD_FIRMWARE_VERSION) - 1,
                     payload->info.firmwareVersion);
 
             // Support URL
-            err = err || ConditionalAddTextStringToMap(&repMap, OC_RSRVD_SUPPORT_URL,
+            err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_SUPPORT_URL,
                     sizeof(OC_RSRVD_SUPPORT_URL) - 1,
                     payload->info.supportUrl);
 
             // System Time
-            err = err || ConditionalAddTextStringToMap(&repMap, OC_RSRVD_SYSTEM_TIME,
+            err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_SYSTEM_TIME,
                     sizeof(OC_RSRVD_SYSTEM_TIME) - 1,
                     payload->info.systemTime);
-            err = err || cbor_encoder_close_container(&map, &repMap);
+            err = err | cbor_encoder_close_container(&map, &repMap);
         }
 
         // Close Map
-        err = err || cbor_encoder_close_container(&rootArray, &map);
+        err = err | cbor_encoder_close_container(&rootArray, &map);
     }
 
     // Close main array
-    err = err || cbor_encoder_close_container(&encoder, &rootArray);
-
-    if(err)
-    {
-        OC_LOG_V(ERROR, TAG, "Convert Platform Payload failed with : %d", err);
-        return OC_STACK_ERROR;
-    }
-
-    *size = encoder.ptr - *outPayload;
-    uint8_t* tempPayload = (uint8_t*)OICRealloc(*outPayload, *size);
-
-    if(!tempPayload)
-    {
-        OC_LOG_V(ERROR, TAG, PCF("Payload realloc failed!"));
-        OICFree(*outPayload);
-        return OC_STACK_ERROR;
-    }
-
-    *outPayload = tempPayload;
+    err = err | cbor_encoder_close_container(&encoder, &rootArray);
 
-    return OC_STACK_OK;
+    return checkError(err, &encoder, outPayload, size);
 }
 
-static bool OCConvertSingleRepPayload(CborEncoder* parent, const OCRepPayload* payload);
-
-static bool OCConvertArray(CborEncoder* parent, const OCRepPayloadValueArray* valArray)
+static int64_t OCConvertArray(CborEncoder* parent, const OCRepPayloadValueArray* valArray)
 {
     CborEncoder array;
-    bool err = false;
+    int64_t err = 0;
 
-    err = err || cbor_encoder_create_array(parent, &array, CborIndefiniteLength);
-    err = err || cbor_encode_uint(&array, valArray->type);
+    err = err | cbor_encoder_create_array(parent, &array, CborIndefiniteLength);
+    err = err | cbor_encode_uint(&array, valArray->type);
     for(int i = 0; i < MAX_REP_ARRAY_DEPTH; ++i)
     {
-        err = err || cbor_encode_uint(&array, valArray->dimensions[i]);
+        err = err | cbor_encode_uint(&array, valArray->dimensions[i]);
     }
 
     size_t dimTotal = calcDimTotal(valArray->dimensions);
@@ -495,16 +484,16 @@ static bool OCConvertArray(CborEncoder* parent, const OCRepPayloadValueArray* va
                 err = CborUnknownError;
                 break;
             case OCREP_PROP_INT:
-                err = err || cbor_encode_int(&array, valArray->iArray[i]);
+                err = err | cbor_encode_int(&array, valArray->iArray[i]);
                 break;
             case OCREP_PROP_DOUBLE:
-                err = err || cbor_encode_double(&array, valArray->dArray[i]);
+                err = err | cbor_encode_double(&array, valArray->dArray[i]);
                 break;
             case OCREP_PROP_BOOL:
-                err = err || cbor_encode_boolean(&array, valArray->bArray[i]);
+                err = err | cbor_encode_boolean(&array, valArray->bArray[i]);
                 break;
             case OCREP_PROP_STRING:
-                err = err || cbor_encode_text_string(&array, valArray->strArray[i],
+                err = err | cbor_encode_text_string(&array, valArray->strArray[i],
                         strlen(valArray->strArray[i]));
                 break;
             case OCREP_PROP_OBJECT:
@@ -517,18 +506,18 @@ static bool OCConvertArray(CborEncoder* parent, const OCRepPayloadValueArray* va
         }
     }
 
-    err = err || cbor_encoder_close_container(parent, &array);
+    err = err | cbor_encoder_close_container(parent, &array);
     return err;
 }
 
-static bool OCConvertSingleRepPayload(CborEncoder* parent, const OCRepPayload* payload)
+static int64_t OCConvertSingleRepPayload(CborEncoder* parent, const OCRepPayload* payload)
 {
-    bool err = false;
+    int64_t err = 0;
     CborEncoder map;
-    err = err || cbor_encoder_create_map(parent, &map, CborIndefiniteLength);
+    err = err | cbor_encoder_create_map(parent, &map, CborIndefiniteLength);
 
     // Uri
-    err = err || ConditionalAddTextStringToMap(&map, OC_RSRVD_HREF,
+    err = err | ConditionalAddTextStringToMap(&map, OC_RSRVD_HREF,
             sizeof(OC_RSRVD_HREF) - 1,
             payload->uri);
 
@@ -537,83 +526,83 @@ static bool OCConvertSingleRepPayload(CborEncoder* parent, const OCRepPayload* p
     if(payload->types || payload->interfaces)
     {
         OC_LOG_V(INFO, TAG, "Payload has types or interfaces");
-        err = err || cbor_encode_text_string(&map,
+        err = err | cbor_encode_text_string(&map,
                 OC_RSRVD_PROPERTY,
                 sizeof(OC_RSRVD_PROPERTY) - 1);
         CborEncoder propMap;
-        err = err || cbor_encoder_create_map(&map, &propMap, 2);
+        err = err | cbor_encoder_create_map(&map, &propMap, 2);
 
         CborEncoder curArray;
         if(payload->types)
         {
-            err = err || cbor_encode_text_string(&propMap,
+            err = err | cbor_encode_text_string(&propMap,
                     OC_RSRVD_RESOURCE_TYPE,
                     sizeof(OC_RSRVD_RESOURCE_TYPE) - 1);
-            err = err || cbor_encoder_create_array(&propMap, &curArray, CborIndefiniteLength);
+            err = err | cbor_encoder_create_array(&propMap, &curArray, CborIndefiniteLength);
             OCStringLL* val = payload->types;
             while(val)
             {
-                err = err || cbor_encode_text_string(&curArray, val->value, strlen(val->value));
+                err = err | cbor_encode_text_string(&curArray, val->value, strlen(val->value));
                 val = val->next;
             }
-            err = err || cbor_encoder_close_container(&propMap, &curArray);
+            err = err | cbor_encoder_close_container(&propMap, &curArray);
         }
         if(payload->interfaces)
         {
-            err = err || cbor_encode_text_string(&propMap,
+            err = err | cbor_encode_text_string(&propMap,
                     OC_RSRVD_INTERFACE,
                     sizeof(OC_RSRVD_INTERFACE) - 1);
-            err = err || cbor_encoder_create_array(&propMap, &curArray, CborIndefiniteLength);
+            err = err | cbor_encoder_create_array(&propMap, &curArray, CborIndefiniteLength);
             OCStringLL* val = payload->interfaces;
             while(val)
             {
-                err = err || cbor_encode_text_string(&curArray, val->value, strlen(val->value));
+                err = err | cbor_encode_text_string(&curArray, val->value, strlen(val->value));
                 val = val->next;
             }
-            err = err || cbor_encoder_close_container(&propMap, &curArray);
+            err = err | cbor_encoder_close_container(&propMap, &curArray);
         }
-        err = err || cbor_encoder_close_container(&map, &propMap);
+        err = err | cbor_encoder_close_container(&map, &propMap);
     }
 
     // Rep Map
     {
         CborEncoder repMap;
-        err = err || cbor_encode_text_string(&map,
+        err = err | cbor_encode_text_string(&map,
                 OC_RSRVD_REPRESENTATION,
                 sizeof(OC_RSRVD_REPRESENTATION) - 1);
-        err = err || cbor_encoder_create_map(&map, &repMap, CborIndefiniteLength);
+        err = err | cbor_encoder_create_map(&map, &repMap, CborIndefiniteLength);
         OCRepPayloadValue* value = payload->values;
         while(value)
         {
-            err = err || cbor_encode_text_string(&repMap,
+            err = err | cbor_encode_text_string(&repMap,
                     value->name,
                     strlen(value->name));
             switch(value->type)
             {
                 case OCREP_PROP_NULL:
-                    err = err || cbor_encode_null(&repMap);
+                    err = err | cbor_encode_null(&repMap);
                     break;
                 case OCREP_PROP_INT:
-                    err = err || cbor_encode_int(&repMap,
+                    err = err | cbor_encode_int(&repMap,
                             value->i);
                     break;
                 case OCREP_PROP_DOUBLE:
-                    err = err || cbor_encode_double(&repMap,
+                    err = err | cbor_encode_double(&repMap,
                             value->d);
                     break;
                 case OCREP_PROP_BOOL:
-                    err = err || cbor_encode_boolean(&repMap,
+                    err = err | cbor_encode_boolean(&repMap,
                             value->b);
                     break;
                 case OCREP_PROP_STRING:
-                    err = err || cbor_encode_text_string(&repMap,
+                    err = err | cbor_encode_text_string(&repMap,
                             value->str, strlen(value->str));
                     break;
                 case OCREP_PROP_OBJECT:
-                    err = err || OCConvertSingleRepPayload(&repMap, value->obj);
+                    err = err | OCConvertSingleRepPayload(&repMap, value->obj);
                     break;
                 case OCREP_PROP_ARRAY:
-                    err = err || OCConvertArray(&repMap, &value->arr);
+                    err = err | OCConvertArray(&repMap, &value->arr);
                     break;
                 default:
                     OC_LOG_V(ERROR, TAG, "Invalid Prop type: %d",
@@ -623,145 +612,93 @@ static bool OCConvertSingleRepPayload(CborEncoder* parent, const OCRepPayload* p
             value = value->next;
         }
 
-        err = err || cbor_encoder_close_container(&map, &repMap);
+        err = err | cbor_encoder_close_container(&map, &repMap);
     }
 
     // Close Map
-    err = err || cbor_encoder_close_container(parent, &map);
+    err = err | cbor_encoder_close_container(parent, &map);
 
     return err;
 }
 
-static OCStackResult OCConvertRepPayload(OCRepPayload* payload, uint8_t** outPayload, size_t* size)
+static int64_t OCConvertRepPayload(OCRepPayload* payload, uint8_t* outPayload, size_t* size)
 {
-    *outPayload = (uint8_t*)OICCalloc(1, MAX_REQUEST_LENGTH);
-    *size = MAX_REQUEST_LENGTH;
-
-    if(!*outPayload)
-    {
-        return OC_STACK_NO_MEMORY;
-    }
-
     CborEncoder encoder = {0};
-    bool err = false;
+    int64_t err = 0;
 
-    cbor_encoder_init(&encoder, *outPayload, *size, 0);
+    cbor_encoder_init(&encoder, outPayload, *size, 0);
     CborEncoder rootArray;
-    err = err || cbor_encoder_create_array(&encoder, &rootArray, CborIndefiniteLength);
-    err = err || cbor_encode_uint(&rootArray, PAYLOAD_TYPE_REPRESENTATION);
+    err = err | cbor_encoder_create_array(&encoder, &rootArray, CborIndefiniteLength);
+    err = err | cbor_encode_uint(&rootArray, PAYLOAD_TYPE_REPRESENTATION);
 
-    while(payload != NULL && !err)
+    while(payload != NULL && (err == 0 || err == CborErrorOutOfMemory))
     {
-        err = err || OCConvertSingleRepPayload(&rootArray, payload);
+        err = err | OCConvertSingleRepPayload(&rootArray, payload);
         payload = payload->next;
     }
 
     // Close main array
-    err = err || cbor_encoder_close_container(&encoder, &rootArray);
-
-    if(err)
-    {
-        OC_LOG_V(ERROR, TAG, "Convert Rep Payload failed with : %d", err);
-        return OC_STACK_ERROR;
-    }
-
-    *size = encoder.ptr - *outPayload;
-    uint8_t* tempPayload = (uint8_t*)OICRealloc(*outPayload, *size);
-
-    if(!tempPayload)
-    {
-        OC_LOG_V(ERROR, TAG, PCF("Payload realloc failed!"));
-        OICFree(*outPayload);
-        return OC_STACK_ERROR;
-    }
-
-    *outPayload = tempPayload;
+    err = err | cbor_encoder_close_container(&encoder, &rootArray);
 
-    return OC_STACK_OK;
+    return checkError(err, &encoder, outPayload, size);
 }
 
-static OCStackResult OCConvertPresencePayload(OCPresencePayload* payload,
-        uint8_t** outPayload, size_t* size)
+static int64_t OCConvertPresencePayload(OCPresencePayload* payload,
+        uint8_t* outPayload, size_t* size)
 {
-    *outPayload = (uint8_t*)OICCalloc(1, MAX_REQUEST_LENGTH);
-    *size = MAX_REQUEST_LENGTH;
-
-    if(!*outPayload)
-    {
-        return OC_STACK_NO_MEMORY;
-    }
-
     CborEncoder encoder = {0};
-    bool err = false;
+    int64_t err = 0;
 
-    cbor_encoder_init(&encoder, *outPayload, *size, 0);
+    cbor_encoder_init(&encoder, outPayload, *size, 0);
     CborEncoder rootArray;
 
-    err = err || cbor_encoder_create_array(&encoder, &rootArray, 2);
-    err = err || cbor_encode_uint(&rootArray, PAYLOAD_TYPE_PRESENCE);
+    err = err | cbor_encoder_create_array(&encoder, &rootArray, 2);
+    err = err | cbor_encode_uint(&rootArray, PAYLOAD_TYPE_PRESENCE);
 
 
     CborEncoder map;
-    err = err || cbor_encoder_create_map(&rootArray, &map, CborIndefiniteLength);
+    err = err | cbor_encoder_create_map(&rootArray, &map, CborIndefiniteLength);
 
     // Sequence Number
-    err = err || cbor_encode_text_string(&map,
+    err = err | cbor_encode_text_string(&map,
             OC_RSRVD_NONCE,
             sizeof(OC_RSRVD_NONCE) - 1);
-    err = err || cbor_encode_uint(&map, payload->sequenceNumber);
+    err = err | cbor_encode_uint(&map, payload->sequenceNumber);
 
     // Max Age
-    err = err || cbor_encode_text_string(&map,
+    err = err | cbor_encode_text_string(&map,
             OC_RSRVD_TTL,
             sizeof(OC_RSRVD_TTL) - 1);
-    err = err || cbor_encode_uint(&map, payload->maxAge);
+    err = err | cbor_encode_uint(&map, payload->maxAge);
 
     // Trigger
     const char* triggerStr = convertTriggerEnumToString(payload->trigger);
-    err = err || AddTextStringToMap(&map, OC_RSRVD_TRIGGER, sizeof(OC_RSRVD_TRIGGER) - 1,
+    err = err | AddTextStringToMap(&map, OC_RSRVD_TRIGGER, sizeof(OC_RSRVD_TRIGGER) - 1,
             triggerStr);
 
     // Resource type name
     if(payload->trigger != OC_PRESENCE_TRIGGER_DELETE)
     {
-        err = err || ConditionalAddTextStringToMap(&map, OC_RSRVD_RESOURCE_TYPE,
+        err = err | ConditionalAddTextStringToMap(&map, OC_RSRVD_RESOURCE_TYPE,
                 sizeof(OC_RSRVD_RESOURCE_TYPE) - 1, payload->resourceType);
     }
 
     // Close Map
-    err = err || cbor_encoder_close_container(&rootArray, &map);
-    err = err || cbor_encoder_close_container(&encoder, &rootArray);
-
-    if(err)
-    {
-        OC_LOG_V(ERROR, TAG, "Convert Presence Payload failed with : %d", err);
-        return OC_STACK_ERROR;
-    }
-
-    *size = encoder.ptr - *outPayload;
-    uint8_t* tempPayload = (uint8_t*)OICRealloc(*outPayload, *size);
-
-    if(!tempPayload)
-    {
-        OC_LOG_V(ERROR, TAG, PCF("Payload realloc failed!"));
-        OICFree(*outPayload);
-        return OC_STACK_ERROR;
-    }
-
-    *outPayload = tempPayload;
+    err = err | cbor_encoder_close_container(&rootArray, &map);
+    err = err | cbor_encoder_close_container(&encoder, &rootArray);
 
-    return OC_STACK_OK;
+    return checkError(err, &encoder, outPayload, size);
 }
 
-bool AddTextStringToMap(CborEncoder* map, const char* key, size_t keylen,
+static int64_t AddTextStringToMap(CborEncoder* map, const char* key, size_t keylen,
         const char* value)
 {
-    return cbor_encode_text_string(map, key, keylen) ||
+    return cbor_encode_text_string(map, key, keylen) |
            cbor_encode_text_string(map, value, strlen(value));
 }
 
-bool ConditionalAddTextStringToMap(CborEncoder* map, const char* key, size_t keylen,
+static int64_t ConditionalAddTextStringToMap(CborEncoder* map, const char* key, size_t keylen,
         const char* value)
 {
-    retu