Changeset for reviewing RI-CA integration changes. 01/401/10
authorSakthivel Samidurai <sakthivel.samidurai@intel.com>
Mon, 16 Mar 2015 22:37:32 +0000 (15:37 -0700)
committerSashi Penta <sashi.kumar.penta@intel.com>
Wed, 18 Mar 2015 20:22:00 +0000 (20:22 +0000)
--Added a single line at the end for full RI code review.
--For specific RI integration changes refer
https://gerrit.iotivity.org/gerrit/#/c/394/

Change-Id: I54e3fcf2e0c10c382d4be59d2d380eb4db5f9791
Signed-Off-By: Sudarshan Prasad <sudarshan.prasad@intel.com>
Signed-off-by: Erich Keane <erich.keane@intel.com>
Signed-off-by: Shilpa Sodani <shilpa.a.sodani@intel.com>
Signed-off-by: Sakthivel Samidurai <sakthivel.samidurai@intel.com>
Reviewed-on: https://gerrit.iotivity.org/gerrit/401
Tested-by: jenkins-iotivity <jenkins-iotivity@opendaylight.org>
Reviewed-by: Sashi Penta <sashi.kumar.penta@intel.com>
Tested-by: Sashi Penta <sashi.kumar.penta@intel.com>
208 files changed:
SConstruct
arduino.scons
auto_build.sh
examples/OICMiddle/Client.cpp
examples/OICMiddle/SConscript
examples/OICMiddle/makefile
examples/OICSensorBoard/SConstruct
extlibs/buildDependencies.sh
extlibs/hippomocks.scons
extra_options.scons
resource/SConscript
resource/artifact_output_locations.txt
resource/buildScript.mk
resource/csdk/README
resource/csdk/SConscript
resource/csdk/makefile
resource/csdk/ocmalloc/test/linux/makefile
resource/csdk/security/include/internal/ocsecurityinternal.h
resource/csdk/security/include/ocsecurity.h
resource/csdk/security/include/ocsecurityconfig.h
resource/csdk/security/src/ocsecurity.c
resource/csdk/stack/include/internal/occlientcb.h
resource/csdk/stack/include/internal/ocobserve.h
resource/csdk/stack/include/internal/ocresourcehandler.h
resource/csdk/stack/include/internal/ocserverrequest.h
resource/csdk/stack/include/internal/ocstackinternal.h
resource/csdk/stack/include/ocstack.h
resource/csdk/stack/samples/arduino/SimpleClientServer/ocserver/SConscript
resource/csdk/stack/samples/arduino/SimpleClientServer/ocserver/makefile
resource/csdk/stack/samples/arduino/SimpleClientServer/ocserver/ocserver.cpp
resource/csdk/stack/samples/linux/SimpleClientServer/SConscript
resource/csdk/stack/samples/linux/SimpleClientServer/common.cpp
resource/csdk/stack/samples/linux/SimpleClientServer/makefile
resource/csdk/stack/samples/linux/SimpleClientServer/occlient.cpp
resource/csdk/stack/samples/linux/SimpleClientServer/occlient.h
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/SimpleClientServer/occlientslow.h
resource/csdk/stack/samples/linux/SimpleClientServer/ocserver.cpp
resource/csdk/stack/samples/linux/SimpleClientServer/ocserver.h
resource/csdk/stack/samples/linux/SimpleClientServer/ocserverbasicops.cpp
resource/csdk/stack/samples/linux/SimpleClientServer/ocserverbasicops.h
resource/csdk/stack/samples/linux/SimpleClientServer/ocservercoll.cpp
resource/csdk/stack/samples/linux/SimpleClientServer/ocserverslow.cpp
resource/csdk/stack/samples/linux/SimpleClientServer/ocserverslow.h
resource/csdk/stack/samples/linux/secure/SConscript
resource/csdk/stack/samples/linux/secure/common.cpp
resource/csdk/stack/samples/linux/secure/common.h
resource/csdk/stack/samples/linux/secure/gen_sec_bin.cpp
resource/csdk/stack/samples/linux/secure/makefile
resource/csdk/stack/samples/linux/secure/occlientbasicops.cpp
resource/csdk/stack/samples/linux/secure/occlientbasicops.h
resource/csdk/stack/samples/linux/secure/ocserverbasicops.cpp
resource/csdk/stack/src/occlientcb.c
resource/csdk/stack/src/occollection.c
resource/csdk/stack/src/ocobserve.c
resource/csdk/stack/src/ocresource.c
resource/csdk/stack/src/ocserverrequest.c
resource/csdk/stack/src/ocstack.c
resource/csdk/stack/src/oicgroup.c
resource/csdk/stack/test/README
resource/csdk/stack/test/SConscript
resource/csdk/stack/test/android/README
resource/csdk/stack/test/arduino/README
resource/csdk/stack/test/arduino/makefile
resource/csdk/stack/test/arduino/ocserver.cpp
resource/csdk/stack/test/linux/makefile
resource/csdk/stack/test/linux/occlient.c
resource/csdk/stack/test/linux/ocserver.c
resource/csdk/stack/test/makefile
resource/csdk/stack/test/stacktests.cpp
resource/examples/SConscript
resource/examples/devicediscoveryclient.cpp
resource/examples/devicediscoveryserver.cpp
resource/examples/fridgeclient.cpp
resource/examples/fridgeserver.cpp
resource/examples/garageclient.cpp
resource/examples/garageserver.cpp
resource/examples/groupclient.cpp
resource/examples/groupserver.cpp
resource/examples/lightserver.cpp
resource/examples/makefile
resource/examples/presenceclient.cpp
resource/examples/presenceserver.cpp
resource/examples/roomclient.cpp
resource/examples/roomserver.cpp
resource/examples/simpleclient.cpp
resource/examples/simpleclientHQ.cpp
resource/examples/simpleclientserver.cpp
resource/examples/simpleserver.cpp
resource/examples/simpleserverHQ.cpp
resource/examples/threadingsample.cpp
resource/include/IClientWrapper.h
resource/include/InProcClientWrapper.h
resource/include/OCPlatform.h
resource/include/OCPlatform_impl.h
resource/include/OCRepresentation.h
resource/include/OCResource.h
resource/include/OCResourceResponse.h
resource/include/OCSerialization.h
resource/include/OCUtilities.h
resource/include/OutOfProcClientWrapper.h
resource/include/StringConstants.h
resource/makefile
resource/oc_logger/SConscript
resource/oc_logger/c/oc_logger.c
resource/oc_logger/examples/SConscript
resource/oc_logger/include/oc_logger_types.h
resource/oc_logger/samples/linux/makefile
resource/src/InProcServerWrapper.cpp
resource/src/OCException.cpp
resource/src/OCPlatform.cpp
resource/src/OCPlatform_impl.cpp
resource/src/OCRepresentation.cpp
resource/src/OCResource.cpp
resource/src/OCUtilities.cpp
resource/src/SConscript
resource/third_party_libs.scons
resource/unit_tests.scons
resource/unittests/ConstructResourceTest.cpp
resource/unittests/OCResourceTest.cpp
resource/unittests/README
resource/unittests/SConscript
resource/unittests/makefile
service/SConscript
service/notification-manager/NotificationManager/build/linux/Makefile
service/notification-manager/SConscript
service/notification-manager/SampleApp/linux/SConscript
service/notification-manager/build/tizen/CMakeLists.txt
service/protocol-plugin/plugin-manager/SConscript
service/protocol-plugin/plugins/SConscript
service/protocol-plugin/plugins/mqtt-fan/build/linux/Makefile
service/protocol-plugin/plugins/mqtt-light/build/linux/Makefile
service/protocol-plugin/sample-app/linux/SConscript
service/protocol-plugin/sample-app/linux/mqtt/Makefile
service/protocol-plugin/sample-app/linux/mqtt/mqttclient.cpp
service/soft-sensor-manager/SConscript
service/soft-sensor-manager/SSMCore/build/linux/Makefile
service/soft-sensor-manager/SSMCore/src/SSMInterface/SSMCore.h
service/soft-sensor-manager/SSMCore/src/SSMInterface/SSMCore_JNI.cpp
service/soft-sensor-manager/SSMCore/src/SSMInterface/SSMCore_JNI.h
service/soft-sensor-manager/SSMCore/src/SSMInterface/SSMModelDefinition.h
service/soft-sensor-manager/SSMCore/src/SSMInterface/SSMResourceServer.cpp
service/soft-sensor-manager/SSMCore/src/SensorProcessor/ResourceFinder.cpp
service/soft-sensor-manager/SampleApp/arduino/Reference_Thing/build/makefile
service/soft-sensor-manager/SampleApp/arduino/Reference_Thing/include/bleLib.h
service/soft-sensor-manager/SampleApp/arduino/Reference_Thing/src/bleLib.cpp
service/soft-sensor-manager/SampleApp/arduino/Reference_Thing/src/oic_lanLib.cpp
service/soft-sensor-manager/SampleApp/arduino/THSensorApp/build/makefile
service/soft-sensor-manager/SampleApp/arduino/THSensorApp/src/thserver.cpp
service/soft-sensor-manager/SampleApp/arduino/THSensorApp1/build/makefile
service/soft-sensor-manager/SampleApp/arduino/THSensorApp1/src/thserver.cpp
service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/build/makefile
service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/include/bleLib.h
service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/include/proximity.h
service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/include/trackee.h
service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/src/bleLib.cpp
service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/src/oic_lanLib.cpp
service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/src/proximity.cpp
service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/src/trackee.cpp
service/soft-sensor-manager/SampleApp/linux/SSMTesterApp/SConscript
service/soft-sensor-manager/SampleApp/linux/THSensorApp/SConscript
service/soft-sensor-manager/SampleApp/linux/THSensorApp/build/Makefile
service/soft-sensor-manager/SampleApp/linux/THSensorApp1/SConscript
service/soft-sensor-manager/SampleApp/linux/THSensorApp1/build/Makefile
service/soft-sensor-manager/SampleApp/tizen/SSMTesterApp/README
service/soft-sensor-manager/SampleApp/tizen/SSMTesterApp/RELEASE.txt
service/soft-sensor-manager/SampleApp/tizen/SSMTesterApp/makefile_org
service/soft-sensor-manager/SampleApp/tizen/SSMTesterApp/oic-sample/CMakeLists.txt
service/soft-sensor-manager/SampleApp/tizen/SSMTesterApp/oic-sample/com.samsung.ssmtester.rule
service/soft-sensor-manager/SampleApp/tizen/SSMTesterApp/oic-sample/com.samsung.ssmtester.xml
service/soft-sensor-manager/SampleApp/tizen/SSMTesterApp/oic-sample/src/oicapp-log.h
service/soft-sensor-manager/SampleApp/tizen/SSMTesterApp/oic-sample/src/oicapp-test.cpp
service/soft-sensor-manager/SampleApp/tizen/SSMTesterApp/oic-sample/src/oicapp-test.h
service/soft-sensor-manager/SampleApp/tizen/SSMTesterApp/oic-sample/src/oicapp-utils.c
service/soft-sensor-manager/SampleApp/tizen/SSMTesterApp/oic-sample/src/oicapp-utils.h
service/soft-sensor-manager/SampleApp/tizen/SSMTesterApp/packaging/ssm.manifest
service/soft-sensor-manager/SampleApp/tizen/SSMTesterApp/packaging/ssm.spec
service/soft-sensor-manager/SoftSensorPlugin/DiscomfortIndexSensor/include/DiscomfortIndexSensor.h
service/soft-sensor-manager/SoftSensorPlugin/DiscomfortIndexSensor/src/DiscomfortIndexSensor.cpp
service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/include/ITS.h
service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/src/GeneralData.cpp
service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/src/ITS.cpp
service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/src/Trajectory.cpp
service/soft-sensor-manager/build/tizen/SampleApp/CMakeLists.txt
service/soft-sensor-manager/build/tizen/SampleApp/THSensorApp/CMakeLists.txt
service/soft-sensor-manager/build/tizen/SampleApp/THSensorApp1/CMakeLists.txt
service/things-manager/SConscript
service/things-manager/sampleapp/SConscript
service/things-manager/sampleapp/linux/configuration/SConscript
service/things-manager/sampleapp/linux/configuration/con-client.cpp
service/things-manager/sampleapp/linux/configuration/con-server.cpp
service/things-manager/sampleapp/linux/configuration/makefile
service/things-manager/sampleapp/linux/groupaction/SConscript
service/things-manager/sampleapp/linux/groupaction/groupserver.cpp
service/things-manager/sampleapp/linux/groupaction/makefile
service/things-manager/sampleapp/linux/groupsyncaction/SConscript
service/things-manager/sampleapp/linux/groupsyncaction/group.cpp
service/things-manager/sampleapp/linux/groupsyncaction/makefile
service/things-manager/sdk/build/linux/Makefile
service/things-manager/sdk/src/GroupManager.cpp
service/things-manager/sdk/src/GroupSynchronization.cpp
service/things-manager/sdk/src/GroupSynchronization.h
service/things-manager/sdk/src/ThingsConfiguration.cpp
service/things-manager/sdk/src/ThingsDiagnostics.cpp
service/third_party_libs.scons

index 3ffc00c..d58a301 100644 (file)
@@ -1,3 +1,23 @@
+#******************************************************************
+#
+# Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
 ##
 # The main build script
 #
@@ -39,3 +59,4 @@ env.PrintTargets()
 # Print bin upload command line (arduino only)
 if target_os == 'arduino':
        env.UploadHelp()
+
index fb9adfa..143b114 100644 (file)
@@ -1,3 +1,23 @@
+#******************************************************************
+#
+# Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#
 ##
 # This script includes arduino specific config for oic-resource
 ##
index ab4ddb1..41bba84 100755 (executable)
@@ -104,3 +104,4 @@ build $1 $2 true
 build $1 $2 false
 scons resource TEST=1
 echo "===================== done ====================="
+
index 1aafde9..fbb6866 100644 (file)
@@ -1,6 +1,6 @@
 //******************************************************************
 //
-// Copyright 2014 Intel Corporation.
+// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 //
@@ -19,6 +19,7 @@
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
 #include <map>
+#include <stdexcept>
 
 #include "WrapResource.h"
 #include "Client.h"
@@ -66,14 +67,21 @@ void MiddleClient::foundOCResource(shared_ptr<OCResource> resource)
  */
 string MiddleClient::formatResourceID(std::shared_ptr<OCResource> resource)
 {
-    string host = resource->host();
-    if (host.compare(0, 7, "coap://") == 0)
-        host = host.erase(0, 7);
-    return host + resource->uri();
+    if(!resource)
+    {
+        throw invalid_argument("Invalid resource object in formatResourceID");
+    }
+
+    return resource->sid() + resource->uri();
 }
 
 void MiddleClient::addResource(WrapResource *wres)
 {
+    if(!wres)
+    {
+        throw invalid_argument("Invalid WrapResource object in addResource");
+    }
+
     string resourceID = wres->getResourceID();
     try {
         m_resourceMap[resourceID];
@@ -81,3 +89,4 @@ void MiddleClient::addResource(WrapResource *wres)
         m_resourceMap[resourceID] = wres;
     }
 }
+
index db55684..04b26fe 100644 (file)
@@ -1,3 +1,23 @@
+#******************************************************************
+#
+# Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
 ##
 # Examples build script
 ##
@@ -54,3 +74,4 @@ Alias("examples", [OICMiddle])
 env.AppendTarget('examples')
 
 
+
index 1a034bb..4a40c95 100644 (file)
@@ -1,6 +1,6 @@
 #//******************************************************************
 #//
-#// Copyright 2014 Intel Corporation.
+#// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
 #//
 #//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 #//
@@ -85,3 +85,4 @@ clean:
        rm -rf debug
        rm -rf release
 
+
index 8a4ef04..2a468aa 100644 (file)
@@ -1,9 +1,29 @@
-#This script builds edisonclient for Ubuntu and edisonserver for Yocto. 
+#******************************************************************
+#
+# Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#This script builds edisonclient for Ubuntu and edisonserver for Yocto.
 
 #Client build for Ubuntu
 #Set IOTIVITY_ROOT to the root of oic-resource on Ubuntu.
-IOTIVITY_ROOT = '' 
-#Set IOTIVITY_LIBS_PATH to path on Ubuntu that contains liboc.so, liboctbstack.so, liboc_logger.so and libcoap.so.               
+IOTIVITY_ROOT = ''
+#Set IOTIVITY_LIBS_PATH to path on Ubuntu that contains liboc.so, liboctbstack.so, liboc_logger.so and libcoap.so.
 IOTIVITY_LIBS_PATH = ''
 
 env = DefaultEnvironment()
@@ -13,7 +33,7 @@ env.AppendUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'coap'])
 
 envClient = env.Clone()
 envClient.AppendUnique(CPPPATH = [
-                IOTIVITY_ROOT + '/resource/include', 
+                IOTIVITY_ROOT + '/resource/include',
                 IOTIVITY_ROOT + '/resource/csdk/stack/include',
                 IOTIVITY_ROOT + '/resource/oc_logger/include',
                 ])
@@ -58,6 +78,7 @@ try:
                 sdk_root + '/usr/include/iotivity/',
                 sdk_root + '/usr/include/iotivity/stack/',
                 sdk_root + '/usr/include/iotivity/oc_logger/',
-                ])                     
+                ])
 except:
     print "ERROR configuring Yocto cross-toolchain environment. This is required for building the server"
+
index 9c65248..a774338 100755 (executable)
@@ -93,3 +93,4 @@ function checkBoost {
 
 checkBoost 19 arm-linux-androideabi 4.9
 checkBoost 19 x86 4.9
+
index 9c59d82..6d5b5a4 100644 (file)
@@ -1,3 +1,23 @@
+#******************************************************************
+#
+# Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
 ##
 # 'hippomocks' script to check if Hippo Mocks Unit Test library is installed.
 # If not, get it and install it
@@ -35,3 +55,4 @@ if target_os == 'linux':
                os.rename(hippomocks_dir_src, hippomocks_dir_dest)
 
 
+
index 21739c5..ee0406a 100644 (file)
@@ -1,3 +1,23 @@
+#******************************************************************
+#
+# Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
 ######################################################################
 # This script manages extra build options
 #
@@ -31,3 +51,4 @@ if not os.path.exists(src_dir + '/extlibs/cereal'):
 *********************************************************************************
 '''
        Exit(1)
+
index d7adf7b..77af932 100644 (file)
@@ -1,3 +1,23 @@
+#******************************************************************
+#
+# Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
 ##
 # 'resource' sub-project main build script
 #
@@ -41,3 +61,4 @@ if target_os == 'linux':
 
 elif target_os == 'arduino':
        SConscript('csdk/stack/samples/arduino/SimpleClientServer/ocserver/SConscript')
+
index 70a2365..72b2ca5 100644 (file)
@@ -93,7 +93,7 @@ UB OCICUC:
        <oic-resource>/examples/ocicuc/client
        <oic-resource>/examples/ocicuc/monoprocess
        <oic-resource>/examples/ocicuc/server
-               
+
 
 ===============================================================================
 ====           Arduino ATMega 2560 - Release & Debug - Ethernet Shield     ====
@@ -179,3 +179,4 @@ TB Examples:
 
 
 
+
index f5be69d..7df8ce6 100644 (file)
@@ -503,3 +503,4 @@ clean:
 arduino:
        $(error "You must specify "arduinomega" or "arduinodue" when trying to\
        build arduino targets.")
+
index ac1d43e..7839acd 100644 (file)
@@ -60,3 +60,4 @@ dependencies:
 
        make deepclean
 
+
index c1b81b9..a2367f9 100644 (file)
@@ -1,3 +1,23 @@
+#******************************************************************
+#
+# Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
 ##
 # liboctbstack (share library) build script
 ##
@@ -69,7 +89,7 @@ liboctbstack_src = [
        OCTBSTACK_SRC + 'occlientcb.c',
        OCTBSTACK_SRC + 'ocresource.c',
        OCTBSTACK_SRC + 'ocobserve.c',
-    OCTBSTACK_SRC + 'ocserverrequest.c',
+       OCTBSTACK_SRC + 'ocserverrequest.c',
        OCTBSTACK_SRC + 'occollection.c',
        OCTBSTACK_SRC + 'oicgroup.c',
        'security/src/ocsecurity.c',
@@ -83,3 +103,4 @@ else:
        liboctbstack = liboctbstack_env.SharedLibrary('octbstack', liboctbstack_src)
 
 liboctbstack_env.InstallTarget(liboctbstack, 'liboctbstack')
+
index 24363bb..31cc697 100644 (file)
@@ -222,3 +222,4 @@ legacy_deepclean:
        rm -rf $(OBJ_DIR)
        rm -rf release
        rm -rf debug
+
index fad0401..5beaea8 100644 (file)
@@ -96,3 +96,4 @@ clean: legacy_clean
 
 legacy_clean:
        rm -f *.o $(PROGRAMS)
+
index ca8fe71..5f5b2d1 100644 (file)
@@ -63,3 +63,4 @@ void GetDtlsPskCredentials(OCDtlsPskCredsBlob **credInfo);
 void DeinitOCSecurityInfo();
 
 #endif //OC_SECURITY_INTERNAL_H
+
index eceaabb..1d1b3e4 100644 (file)
@@ -47,3 +47,4 @@ OCStackResult OCSecSetConfigData(const OCSecConfigData *cfgData,
 #endif // __cplusplus
 
 #endif //OC_SECURITY_H
+
index e8db4cc..cf2fd74 100644 (file)
@@ -141,7 +141,7 @@ OCStackResult ValidateBlobTypePSK(const OCSecBlob *secBlob)
     OCDtlsPskCredsBlob *pskCredsBlob;
     uint16_t validLen;
 
-    if(secBlob->len == 0)
+    if(!secBlob || secBlob->len == 0)
     {
         return OC_STACK_INVALID_PARAM;
     }
@@ -253,3 +253,4 @@ OCStackResult OCSecSetConfigData(const OCSecConfigData *cfgData,
 }
 
 
+
index 2bc2355..b3f100f 100644 (file)
 #include <ocresource.h>
 #include "cacommon.h"
 
-typedef struct OCPresence {
+typedef struct OCPresence
+{
     // This is the TTL associated with presence
     uint32_t TTL;
     uint32_t * timeOut;
     uint32_t TTLlevel;
-}OCPresence;
+} OCPresence;
 
-typedef struct OCMulticastNode {
-    unsigned char * uri;
+typedef struct OCMulticastNode
+{
+    char * uri;
     uint32_t nonce;
     struct OCMulticastNode * next;
 } OCMulticastNode;
 
-extern OCMulticastNode * mcPresenceNodes;
-
 typedef struct ClientCB {
     // callback method defined in application address space
     OCClientResponseHandler callBack;
@@ -59,7 +59,7 @@ typedef struct ClientCB {
     // This is the sequence identifier the server applies to the invocation tied to 'handle'.
     uint32_t sequenceNumber;
     // This is the request uri associated with the call back
-    unsigned char * requestUri;
+    char * requestUri;
     // Struct to hold TTL info for presence
     #ifdef WITH_PRESENCE
     OCPresence * presence;
@@ -71,19 +71,20 @@ typedef struct ClientCB {
 
 extern struct ClientCB *cbList;
 
-//-- AddClientCB -----------------------------------------------------------
 /** @ingroup ocstack
  *
  * This method is used to add a client callback method in cbList.
  *
  * @param[out] clientCB
  *              The resulting node from making this call. Null if out of memory.
- * @param[in] cb
+ * @param[in] cbData
  *              address to client callback function.
  * @param[in] token
  *              identifier for OTA CoAP comms.
  * @param[in] handle
  *              Masked in the public API as an 'invocation handle' - Used for callback management.
+ * @param[in] method
+ *              OCMethod via which this client callback is expected to operate
  * @param[in] requestUri
  *              the resource uri of the request.
  * @param[in] resourceType
@@ -91,15 +92,13 @@ extern struct ClientCB *cbList;
  *
  * @brief If the handle you're looking for does not exist, the stack will reply with a RST message.
  *
- * @retval OC_STACK_OK for Success, otherwise some error value
+ * @return OC_STACK_OK for Success, otherwise some error value
  */
-//------------------------------------------------------------------------
 OCStackResult
 AddClientCB (ClientCB** clientCB, OCCallbackData* cbData,
              CAToken_t * token, OCDoHandle *handle, OCMethod method,
-             unsigned char * requestUri, unsigned char * resourceTypeName);
+             char * requestUri, char * resourceTypeName);
 
-//-- DeleteClientCB -----------------------------------------------------------
 /** @ingroup ocstack
  *
  * This method is used to remove a callback node from cbList.
@@ -107,14 +106,12 @@ AddClientCB (ClientCB** clientCB, OCCallbackData* cbData,
  * @param[in] cbNode
  *              address to client callback node.
  */
-//------------------------------------------------------------------------
 void DeleteClientCB(ClientCB *cbNode);
 
 
-//-- GetClientCB ---------------------------------------------------------
 /** @ingroup ocstack
  *
- * This method is used to search a cb node in cbList.
+ * This method is used to search and retrieve a cb node in cbList.
  *
  * @param[in] token
  *              token to search for.
@@ -123,18 +120,19 @@ void DeleteClientCB(ClientCB *cbNode);
  * @param[in] requestUri
  *              Uri to search for.
  *
- * @brief You can search by token OR by handle. Not both.
+ * @brief You can search by token OR by handle, but not both.
  *
- * @retval address of the node if found, otherwise NULL
+ * @return address of the node if found, otherwise NULL
  */
-//------------------------------------------------------------------------
-ClientCB* GetClientCB(const CAToken_t * token, OCDoHandle handle, const unsigned char * requestUri);
+ClientCB* GetClientCB(const CAToken_t * token, OCDoHandle handle, const char * requestUri);
 
 /**
- * Inserts a new resource type filter into this clientCB node.
+ * Inserts a new resource type filter into this cb node.
  *
- * @param cbNode - the node to add the new resourceType filter to
- * @param resourceTypeName - the value to create the new resourceType filter from
+ * @param[in] cbNode
+ *              the node to add the new resourceType filter to
+ * @param[in] resourceTypeName
+ *              the value to create the new resourceType filter from
  *
  * @return
  *      OC_STACK_OK on success
@@ -145,16 +143,13 @@ ClientCB* GetClientCB(const CAToken_t * token, OCDoHandle handle, const unsigned
 OCStackResult InsertResourceTypeFilter(ClientCB * cbNode, const char * resourceTypeName);
 #endif // WITH_PRESENCE
 
-//-- DeleteClientCBList --------------------------------------------------
 /** @ingroup ocstack
  *
  * This method is used to clear the cbList.
  *
  */
-//------------------------------------------------------------------------
 void DeleteClientCBList();
 
-//-- FindAndDeleteClientCB -----------------------------------------------
 /** @ingroup ocstack
  *
  * This method is used to verify the presence of a cb node in cbList
@@ -163,7 +158,6 @@ void DeleteClientCBList();
  * @param[in] cbNode
  *              address to client callback node.
  */
-//------------------------------------------------------------------------
 void FindAndDeleteClientCB(ClientCB * cbNode);
 
 /** @ingroup ocstack
@@ -177,7 +171,7 @@ void FindAndDeleteClientCB(ClientCB * cbNode);
  *              The resulting node from making this call. Null if doesn't exist.
  */
 //------------------------------------------------------------------------
-OCMulticastNode* GetMCPresenceNode(const unsigned char * uri);
+OCMulticastNode* GetMCPresenceNode(const char * uri);
 
 /** @ingroup ocstack
  *
@@ -193,6 +187,7 @@ OCMulticastNode* GetMCPresenceNode(const unsigned char * uri);
  * @return OC_STACK_OK for Success, otherwise some error value
  */
 //------------------------------------------------------------------------
-OCStackResult AddMCPresenceNode(OCMulticastNode** outnode, unsigned char* uri, uint32_t nonce);
+OCStackResult AddMCPresenceNode(OCMulticastNode** outnode, char* uri, uint32_t nonce);
 
 #endif //OC_CLIENT_CB
+
index 9125b9f..28af694 100644 (file)
 #ifndef OC_OBSERVE_H
 #define OC_OBSERVE_H
 
-/* In CoAP sequence number is a 24 bit field */
+/* Sequence number is a 24 bit field */
 #define MAX_SEQUENCE_NUMBER              (0xFFFFFF)
 
 #define MAX_OBSERVER_FAILED_COMM         (2)
 #define MAX_OBSERVER_NON_COUNT           (3)
 
 /* This information is stored for each registerd observer */
-typedef struct ResourceObserver {
+typedef struct ResourceObserver
+{
     // Observation Identifier for request
     OCObservationId observeId;
     // URI of observed resource
-    unsigned char *resUri;
+    char *resUri;
     // Query
-    unsigned char *query;
+    char *query;
     //token for the observe request
     CAToken_t token;
     // Resource handle
@@ -65,7 +66,7 @@ OCStackResult SendAllObserverNotification (OCMethod method, OCResource *resPtr,
 #endif
 OCStackResult SendListObserverNotification (OCResource * resource,
         OCObservationId  *obsIdList, uint8_t numberOfIds,
-        unsigned char *notificationJSONPayload, uint32_t maxAge,
+        const char *notificationJSONPayload, uint32_t maxAge,
         OCQualityOfService qos);
 
 void DeleteObserverList();
@@ -78,10 +79,11 @@ OCStackResult AddObserver (const char         *resUri,
                            CAToken_t          *token,
                            OCResource         *resHandle,
                            OCQualityOfService qos,
-                           CAAddress_t          *addressInfo,
+                           const CAAddress_t  *addressInfo,
                            CAConnectivityType_t connectivityType);
 
 OCStackResult DeleteObserverUsingToken (CAToken_t * token);
+
 ResourceObserver* GetObserverUsingToken (const CAToken_t * token);
 
 ResourceObserver* GetObserverUsingId (const OCObservationId observeId);
@@ -97,3 +99,4 @@ GetObserveHeaderOption (uint32_t * observationOption,
                         uint8_t * numOptions);
 
 #endif //OC_OBSERVE_H
+
index fef013d..7a2859e 100644 (file)
@@ -28,6 +28,8 @@
 #define OC_RSRVD_OC                     "oc"
 #define OC_RSRVD_PAYLOAD                "payload"
 #define OC_RSRVD_HREF                   "href"
+#define OC_RSRVD_REPRESENTATION         "rep"
+#define OC_RSRVD_CONTENT_TYPE           "ct"
 #define OC_RSRVD_RESOURCE_TYPE          "rt"
 #define OC_RSRVD_RESOURCE_TYPE_PRESENCE "core.presence"
 #define OC_RSRVD_INTERFACE              "if"
 #define OC_RSRVD_INTERFACE_BATCH        "oc.mi.b"
 #define OC_RSRVD_INTERFACE_GROUP        "oc.mi.grp"
 
+#define OC_RSRVD_MFG_DATE               "mndt"
+#define OC_RSRVD_FW_VERSION             "mnfv"
+#define OC_RSRVD_HOST_NAME              "hn"
+#define OC_RSRVD_MFG_NAME               "mnmn"
+#define OC_RSRVD_MFG_URL                "mnml"
+#define OC_RSRVD_MODEL_NUM              "mnmo"
+#define OC_RSRVD_PLATFORM_VERSION       "mnpv"
+#define OC_RSRVD_SUPPORT_URL            "mnsl"
+#define OC_RSRVD_VERSION                "icv"
+
 
 #define OC_RSRVD_OBSERVABLE             "obs"
 #define OC_RSRVD_SECURE                 "sec"
@@ -54,7 +66,8 @@
 #define OC_RESOURCE_OBSERVABLE   1
 #define OC_RESOURCE_SECURE       1
 
-typedef enum {
+typedef enum
+{
     STACK_RES_DISCOVERY_NOFILTER = 0,
     STACK_RES_DISCOVERY_IF_FILTER,
     STACK_RES_DISCOVERY_RT_FILTER,
@@ -62,7 +75,8 @@ typedef enum {
     STACK_DEVICE_DISCOVERY_DN_FILTER
 } StackQueryTypes;
 
-typedef enum {
+typedef enum
+{
     OC_RESOURCE_VIRTUAL = 0,
     OC_RESOURCE_NOT_COLLECTION_WITH_ENTITYHANDLER,
     OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER,
@@ -98,3 +112,4 @@ BuildVirtualResourceResponse(OCResource *resourcePtr, uint8_t filterOn,
 OCStackResult EntityHandlerCodeToOCStackCode(OCEntityHandlerResult ehResult);
 
 #endif //OC_RESOURCEHANDLER_H
+
index beb63aa..8c28fe7 100644 (file)
@@ -31,13 +31,14 @@ OCStackResult HandleSingleResponse(OCEntityHandlerResponse * ehResponse);
 OCStackResult HandleAggregateResponse(OCEntityHandlerResponse * ehResponse);
 
 // following structure will be created in occoap and passed up the stack on the server side
-typedef struct OCServerRequest {
+typedef struct OCServerRequest
+{
     // the REST method retrieved from received request PDU
     OCMethod method;
     // resourceUrl will be filled in occoap using the path options in received request PDU
-    unsigned char resourceUrl[MAX_URI_LENGTH];
+    char resourceUrl[MAX_URI_LENGTH];
     // resource query send by client
-    unsigned char query[MAX_QUERY_LENGTH];
+    char query[MAX_QUERY_LENGTH];
 
     // qos is indicating if the request is CON or NON
     OCQualityOfService qos;
@@ -66,14 +67,14 @@ typedef struct OCServerRequest {
     uint8_t slowFlag;
     uint8_t notificationFlag;
     // reqJSON is retrieved from the payload of the received request PDU
-    unsigned char reqJSONPayload[1];
+    char reqJSONPayload[1];
 } OCServerRequest;
 
 // following structure will be created in ocstack to aggregate responses (in future: for block transfer)
 typedef struct OCServerResponse {
     struct OCServerResponse * next;
     // this is the pointer to server payload data to be transferred
-    unsigned char *payload;
+    char *payload;
     uint16_t remainingPayloadSize;
     OCRequestHandle requestHandle;
 } OCServerResponse;
@@ -87,17 +88,17 @@ OCServerResponse * GetServerResponseUsingHandle (const OCServerRequest * handle)
 OCStackResult AddServerRequest (OCServerRequest ** request, uint16_t coapID,
         uint8_t delayedResNeeded, uint8_t secured, uint8_t notificationFlag, OCMethod method,
         uint8_t numRcvdVendorSpecificHeaderOptions, uint32_t observationOption,
-        OCQualityOfService qos, unsigned char * query,
+        OCQualityOfService qos, char * query,
         OCHeaderOption * rcvdVendorSpecificHeaderOptions,
-        unsigned char * reqJSONPayload, CAToken_t * requestToken,
-        unsigned char * resourceUrl, size_t reqTotalSize,
+        char * reqJSONPayload, CAToken_t * requestToken,
+        char * resourceUrl, size_t reqTotalSize,
         CAAddress_t *addressInfo, CAConnectivityType_t connectivityType);
 
 OCStackResult AddServerResponse (OCServerResponse ** response, OCRequestHandle requestHandle);
 
 // Internal function to create OCEntityHandlerRequest at the server from a received coap pdu
 OCStackResult FormOCEntityHandlerRequest(OCEntityHandlerRequest * entityHandlerRequest, OCRequestHandle request,
-        OCMethod method, OCResourceHandle resource, unsigned char * queryBuf, unsigned char * bufReqPayload,
+        OCMethod method, OCResourceHandle resource, char * queryBuf, char * bufReqPayload,
         uint8_t numVendorOptions, OCHeaderOption * vendorOptions, OCObserveAction observeAction,
         OCObservationId observeID);
 
@@ -110,3 +111,4 @@ void FindAndDeleteServerResponse(OCServerResponse * serverResponse);
 void DeleteServerResponse(OCServerResponse * serverResponse);
 
 #endif //OC_SERVER_REQUEST_H
+
index 80e784f..ef73531 100644 (file)
@@ -54,7 +54,8 @@ extern OCDeviceEntityHandler defaultDeviceHandler;
 #define OC_COAP_SCHEME "coap://"
 #define OC_OFFSET_SEQUENCE_NUMBER (4) // the first outgoing sequence number will be 5
 
-typedef struct {
+typedef struct
+{
     // Observe option field
     uint32_t option;
     // IP address & port of client registered for observe
@@ -67,17 +68,18 @@ typedef struct {
 } OCObserveReq;
 
 // following structure will be created in occoap and passed up the stack on the server side
-typedef struct {
+typedef struct
+{
     // Observe option field
     uint32_t observationOption;
     // the REST method retrieved from received request PDU
     OCMethod method;
     // resourceUrl will be filled in occoap using the path options in received request PDU
-    unsigned char resourceUrl[MAX_URI_LENGTH];
+    char resourceUrl[MAX_URI_LENGTH];
     // resource query send by client
-    unsigned char query[MAX_QUERY_LENGTH];
+    char query[MAX_QUERY_LENGTH];
     // reqJSON is retrieved from the payload of the received request PDU
-    unsigned char reqJSONPayload[MAX_REQUEST_LENGTH];
+    char reqJSONPayload[MAX_REQUEST_LENGTH];
     // qos is indicating if the request is CON or NON
     OCQualityOfService qos;
     // An array of the received vendor specific header options
@@ -130,28 +132,29 @@ typedef struct
     uint8_t slowFlag;
     uint8_t notificationFlag;
     // this is the pointer to server payload data to be transferred
-    unsigned char *payload;
+    char *payload;
     // size of server payload data.  Don't rely on null terminated data for size
     uint16_t payloadSize;
     // An array of the vendor specific header options the entity handler wishes to use in response
     uint8_t numSendVendorSpecificHeaderOptions;
     OCHeaderOption *sendVendorSpecificHeaderOptions;
     // URI of new resource that entity handler might create
-    unsigned char * resourceUri;
+    char * resourceUri;
 } OCServerProtocolResponse;
 
 // following structure will be created in occoap and passed up the stack on the client side
-typedef struct {
+typedef struct
+{
     // handle is retrieved by comparing the token-handle pair in the PDU.
     ClientCB * cbNode;
     // This is how long this response is valid for (in seconds).
     uint32_t maxAge;
     // This is the Uri of the resource. (ex. "coap://192.168.1.1/a/led")
-    unsigned char * fullUri;
+    char * fullUri;
     // This is the relative Uri of the resource. (ex. "/a/led")
-    unsigned char * rcvdUri;
+    char * rcvdUri;
     // This is the received payload.
-    unsigned char * bufRes;
+    char * bufRes;
 
     // This is the token received OTA.
     CAToken_t * rcvdToken;
@@ -175,7 +178,7 @@ OCStackResult HandleStackResponses(OCResponse * response);
 OCStackResult SendPresenceNotification(OCResourceType *resourceType);
 OCStackResult SendStopNotification();
 #endif // WITH_PRESENCE
-int ParseIPv4Address(unsigned char * ipAddrStr, uint8_t * ipAddr, uint16_t * port);
+int ParseIPv4Address(char * ipAddrStr, uint8_t * ipAddr, uint16_t * port);
 
 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
                                             const char *resourceInterfaceName);
@@ -211,3 +214,4 @@ OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
 #endif // __cplusplus
 
 #endif /* OCSTACKINTERNAL_H_ */
+
index 2507d10..eec9c29 100644 (file)
@@ -40,7 +40,6 @@ extern "C" {
 #define OC_MULTICAST_PREFIX                  "224.0.1.187:5683"
 #define OC_MULTICAST_IP                      "224.0.1.187"
 
-#define USE_RANDOM_PORT (0)
 #ifdef WITH_PRESENCE
 #define OC_DEFAULT_PRESENCE_TTL (60)
 #define OC_PRESENCE_URI                      "/oc/presence"
@@ -63,7 +62,7 @@ typedef struct OCDevAddr
 {
     uint32_t     size;                    /**< length of the address stored in addr field. */
     uint8_t      addr[DEV_ADDR_SIZE_MAX]; /**< device address. */
-}OCDevAddr;
+} OCDevAddr;
 
 /**
  * OC Virtual resources supported by every OC device
@@ -82,7 +81,8 @@ typedef enum
 /**
  * Standard RESTful HTTP Methods
  */
-typedef enum {
+typedef enum
+{
     OC_REST_NOMETHOD    = 0,
     OC_REST_GET         = (1 << 0),     // Read
     OC_REST_PUT         = (1 << 1),     // Write
@@ -103,17 +103,18 @@ typedef enum {
 /**
  * Host Mode of Operation
  */
-typedef enum {
+typedef enum
+{
     OC_CLIENT = 0,
     OC_SERVER,
     OC_CLIENT_SERVER
 } OCMode;
 
-extern OCMode myStackMode;
 /**
  * Quality of Service
  */
-typedef enum {
+typedef enum
+{
     OC_LOW_QOS = 0,
     OC_MEDIUM_QOS,
     OC_HIGH_QOS,
@@ -133,7 +134,8 @@ typedef enum {
  *                   requests from clients.
  * OC_SECURE       - When this bit is set, the resource is a secure resource.
  */
-typedef enum {
+typedef enum
+{
     OC_ACTIVE       = (1 << 0),
     OC_DISCOVERABLE = (1 << 1),
     OC_OBSERVABLE   = (1 << 2),
@@ -144,7 +146,8 @@ typedef enum {
 /**
  * Transport Protocol IDs
  */
-typedef enum {
+typedef enum
+{
     OC_INVALID_ID   = (1 << 0),
     OC_COAP_ID      = (1 << 1)
 } OCTransportProtocolID;
@@ -152,7 +155,8 @@ typedef enum {
 /**
  * Adaptor types
  */
-typedef enum {
+typedef enum
+{
     OC_ETHERNET = 0,
     OC_WIFI,
     OC_EDR,
@@ -163,7 +167,8 @@ typedef enum {
 /**
  * Declares Stack Results & Errors
  */
-typedef enum {
+typedef enum
+{
     /* Success status code - START HERE */
     OC_STACK_OK = 0,
     OC_STACK_RESOURCE_CREATED,
@@ -230,13 +235,15 @@ typedef uint8_t OCObservationId;
 /**
  * Action associated with observation
  */
-typedef enum {
+typedef enum
+{
     OC_OBSERVE_REGISTER = 0,
     OC_OBSERVE_DEREGISTER = 1,
     OC_OBSERVE_NO_OPTION = 2
 } OCObserveAction;
 
-typedef struct {
+typedef struct
+{
     // Action associated with observation request
     OCObserveAction action;
     // Identifier for observation being registered/deregistered
@@ -246,7 +253,8 @@ typedef struct {
 /**
  * Possible returned values from entity handler
  */
-typedef enum {
+typedef enum
+{
     OC_EH_OK = 0,
     OC_EH_ERROR,
     OC_EH_RESOURCE_CREATED,
@@ -258,7 +266,8 @@ typedef enum {
 // following structure will be used to define the vendor specific header options to be included
 // in communication packets
 
-typedef struct OCHeaderOption {
+typedef struct OCHeaderOption
+{
     // The protocol ID this option applies to
     OCTransportProtocolID protocolID;
     // The header option ID which will be added to communication packets
@@ -270,17 +279,20 @@ typedef struct OCHeaderOption {
 } OCHeaderOption;
 
 /**
- * Incoming requests handled by the server. Requests are passed in as a parameter to the @ref OCEntityHandler callback API.
- * @brief The @ref OCEntityHandler callback API must be implemented in the application in order to receive these requests.
+ * Incoming requests handled by the server. Requests are passed in as a parameter to the
+ * @ref OCEntityHandler callback API.
+ * @brief The @ref OCEntityHandler callback API must be implemented in the application in order
+ * to receive these requests.
  */
-typedef struct {
+typedef struct
+{
     // Associated resource
     OCResourceHandle resource;
     OCRequestHandle requestHandle;
     // the REST method retrieved from received request PDU
     OCMethod method;
     // resource query send by client
-    unsigned char * query;
+    char * query;
     // Information associated with observation - valid only when OCEntityHandler
     // flag includes OC_OBSERVE_FLAG
     OCObservationInfo obsInfo;
@@ -288,13 +300,14 @@ typedef struct {
     uint8_t numRcvdVendorSpecificHeaderOptions;
     OCHeaderOption * rcvdVendorSpecificHeaderOptions;
     // reqJSON is retrieved from the payload of the received request PDU
-    unsigned char * reqJSONPayload;
-}OCEntityHandlerRequest;
+    char * reqJSONPayload;
+} OCEntityHandlerRequest;
 
 /**
  * Response from queries to remote servers. Queries are made by calling the @ref OCDoResource API.
  */
-typedef struct {
+typedef struct
+{
     // Address of remote server
     OCDevAddr * addr;
     // Indicates adaptor type on which the response was received
@@ -304,11 +317,11 @@ typedef struct {
     // If associated with observe, this will represent the sequence of notifications from server.
     uint32_t sequenceNumber;
     // resJSONPayload is retrieved from the payload of the received request PDU
-    unsigned  const char * resJSONPayload;
+    const char * resJSONPayload;
     // An array of the received vendor specific header options
     uint8_t numRcvdVendorSpecificHeaderOptions;
     OCHeaderOption rcvdVendorSpecificHeaderOptions[MAX_HEADER_OPTIONS];
-}OCClientResponse;
+} OCClientResponse;
 
 /**
  * Following structure describes the device properties. All non-Null properties will be included
@@ -342,26 +355,28 @@ typedef struct
     // Allow the entity handler to pass a result with the response
     OCEntityHandlerResult  ehResult;
     // this is the pointer to server payload data to be transferred
-    unsigned char *payload;
+    char *payload;
     // size of server payload data.  I don't think we should rely on null terminated data for size
     uint16_t payloadSize;
     // An array of the vendor specific header options the entity handler wishes to use in response
     uint8_t numSendVendorSpecificHeaderOptions;
     OCHeaderOption sendVendorSpecificHeaderOptions[MAX_HEADER_OPTIONS];
     // URI of new resource that entity handler might create
-    unsigned char resourceUri[MAX_URI_LENGTH];
+    char resourceUri[MAX_URI_LENGTH];
     // Server sets to true for persistent response buffer, false for non-persistent response buffer
     uint8_t persistentBufferFlag;
 } OCEntityHandlerResponse;
 
-typedef enum {
+typedef enum
+{
     OC_INIT_FLAG    = (1 << 0),
     OC_REQUEST_FLAG = (1 << 1),
     OC_OBSERVE_FLAG = (1 << 2)
 } OCEntityHandlerFlag; //entity_handler_flag_t ;
 
 // possible returned values from client application
-typedef enum {
+typedef enum
+{
     OC_STACK_DELETE_TRANSACTION = 0,
     OC_STACK_KEEP_TRANSACTION
 } OCStackApplicationResult;
@@ -385,7 +400,8 @@ typedef void (* OCClientContextDeleter)(void *context);
 /*
  * This info is passed from application to OC Stack when initiating a request to Server
  */
-typedef struct {
+typedef struct
+{
     void *context;
     OCClientResponseHandler cb;
     OCClientContextDeleter cd;
@@ -468,7 +484,7 @@ OCStackResult OCProcess();
  *                             the well-known multicast IP address, the qos will be forced to
  *                             OC_LOW_QOS
  *                             since it is impractical to send other QOS levels on such addresses.
- * @param clientApplicationCB- asynchronous callback function that is invoked
+ * @param cbData             - asynchronous callback function that is invoked
  *                             by the stack when discovery or resource interaction is complete
  * @param options            - The address of an array containing the vendor specific
  *                             header options to be sent with the request
@@ -732,10 +748,10 @@ const char *OCGetResourceUri(OCResourceHandle handle);
  *
  * @param handle - handle of resource
  * @return
- *    property bitmap - if resource found
- *    NULL - resource not found
+ *    OCResourceProperty Bitmask
+ *    -1 if resource is not found
  */
-uint8_t OCGetResourceProperties(OCResourceHandle handle);
+OCResourceProperty OCGetResourceProperties(OCResourceHandle handle);
 
 /**
  * Get the number of resource types of the resource.
@@ -765,14 +781,15 @@ const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index);
  * Get the number of resource interfaces of the resource.
  *
  * @param handle - handle of resource
- * @param numResources - pointer to count variable
+ * @param numResourceInterfaces - pointer to count variable
  *
  * @return
  *     OC_STACK_OK    - no errors
  *     OC_STACK_ERROR - stack process error
 
  */
-OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle, uint8_t *numResourceInterfaces);
+OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
+        uint8_t *numResourceInterfaces);
 
 /**
  * Get name of resource interface of the resource.
@@ -808,7 +825,8 @@ uint8_t OCGetResourceInterfaceAllowedMethods(OCResourceHandle handle, uint8_t in
  *    handle to contained resource - if resource found
  *    NULL - resource not found
  */
-OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle, uint8_t index);
+OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
+        uint8_t index);
 
 /**
  * Get the entity handler for a resource.
@@ -827,6 +845,7 @@ OCEntityHandler OCGetResourceHandler(OCResourceHandle handle);
  * if the query is valid after the resource representation has changed.
  *
  * @param handle - handle of resource
+ * @param qos    - desired quality of service for the observation notifications
  *
  * @return
  *     OC_STACK_OK    - no errors
@@ -857,7 +876,7 @@ OCStackResult
 OCNotifyListOfObservers (OCResourceHandle handle,
                             OCObservationId  *obsIdList,
                             uint8_t          numberOfIds,
-                            unsigned char    *notificationJSONPayload,
+                            const char    *notificationJSONPayload,
                             OCQualityOfService qos);
 
 
@@ -926,3 +945,5 @@ int32_t OCDevAddrToPort(OCDevAddr *ipAddr, uint16_t *port);
 #endif // __cplusplus
 
 #endif /* OCSTACK_H_ */
+
+
index edf9076..9da4c16 100644 (file)
@@ -1,3 +1,23 @@
+#******************************************************************
+#
+# Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
 Import('env')
 
 arduino_simplecs_env = env.Clone()
index 1591210..2b08e12 100644 (file)
@@ -189,10 +189,11 @@ OCEntityHandlerResult OCEntityHandlerCb(OCEntityHandlerFlag flag, OCEntityHandle
             response.requestHandle = entityHandlerRequest->requestHandle;
             response.resourceHandle = entityHandlerRequest->resource;
             response.ehResult = ehRet;
-            response.payload = (unsigned char *)payload;
+            response.payload = payload;
             response.payloadSize = strlen(payload);
             response.numSendVendorSpecificHeaderOptions = 0;
-            memset(response.sendVendorSpecificHeaderOptions, 0, sizeof response.sendVendorSpecificHeaderOptions);
+            memset(response.sendVendorSpecificHeaderOptions, 0,
+                    sizeof response.sendVendorSpecificHeaderOptions);
             memset(response.resourceUri, 0, sizeof response.resourceUri);
             // Indicate that response is NOT in a persistent buffer
             response.persistentBufferFlag = 0;
@@ -228,7 +229,8 @@ void *ChangeLightRepresentation (void *param)
     (void)param;
     OCStackResult result = OC_STACK_ERROR;
     modCounter += 1;
-    if(modCounter % 10 == 0)  // Matching the timing that the Linux Sample Server App uses for the same functionality.
+    // Matching the timing that the Linux Sample Server App uses for the same functionality.
+    if(modCounter % 10 == 0)
     {
         Light.power += 5;
         if (gLightUnderObservation)
@@ -274,7 +276,7 @@ void setup()
 void loop()
 {
     // This artificial delay is kept here to avoid endless spinning
-    // of Arduino microcontroller. Modify it as per specfic application needs.
+    // of Arduino microcontroller. Modify it as per specific application needs.
     delay(2000);
 
     // This call displays the amount of free SRAM available on Arduino
@@ -339,3 +341,4 @@ const char *getResult(OCStackResult result) {
         return "UNKNOWN";
     }
 }
+
index f02c19f..a9b3aac 100644 (file)
@@ -1,3 +1,22 @@
+#******************************************************************
+#
+# Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
 Import('env')
 
@@ -45,3 +64,4 @@ Alias("samples", [ocserver, occlient,
 
 env.AppendTarget('samples')
 
+
index b4e20ba..9dce85f 100644 (file)
@@ -72,7 +72,7 @@ void handleSigInt(int signum)
 
 static void PrintUsage()
 {
-    OC_LOG(INFO, TAG, "Usage : occlient -u <0|1> -t <1|2|3|4|5|6|7> -c <0|1>");
+    OC_LOG(INFO, TAG, "Usage : occlient -u <0|1> -t <1..17> -c <0|1>");
     OC_LOG(INFO, TAG, "-u <0|1> : Perform multicast/unicast discovery of resources");
     OC_LOG(INFO, TAG, "-c <0|1> : Send unicast messages over Ethernet or WIFI");
     OC_LOG(INFO, TAG, "-t 1  :  Discover Resources");
@@ -153,6 +153,10 @@ OCStackApplicationResult putReqCB(void* ctx, OCDoHandle handle, OCClientResponse
         OC_LOG_V(INFO, TAG, "JSON = %s =============> Put Response",
                 clientResponse->resJSONPayload);
     }
+    else
+    {
+        OC_LOG_V(INFO, TAG, "putReqCB received Null clientResponse");
+    }
     return OC_STACK_DELETE_TRANSACTION;
 }
 
@@ -169,6 +173,10 @@ OCStackApplicationResult postReqCB(void *ctx, OCDoHandle handle, OCClientRespons
         OC_LOG_V(INFO, TAG, "JSON = %s =============> Post Response",
                 clientResponse->resJSONPayload);
     }
+    else
+    {
+        OC_LOG_V(INFO, TAG, "postReqCB received Null clientResponse");
+    }
     return OC_STACK_DELETE_TRANSACTION;
 }
 
@@ -186,6 +194,10 @@ OCStackApplicationResult deleteReqCB(void *ctx,
         OC_LOG_V(INFO, TAG, "JSON = %s =============> Delete Response",
                 clientResponse->resJSONPayload);
     }
+    else
+    {
+        OC_LOG_V(INFO, TAG, "deleteReqCB received Null clientResponse");
+    }
     return OC_STACK_DELETE_TRANSACTION;
 }
 
@@ -193,9 +205,10 @@ OCStackApplicationResult getReqCB(void* ctx, OCDoHandle handle, OCClientResponse
 {
     if(clientResponse == NULL)
     {
-        OC_LOG(INFO, TAG, "The clientResponse is NULL");
+        OC_LOG(INFO, TAG, "getReqCB received NULL clientResponse");
         return   OC_STACK_DELETE_TRANSACTION;
     }
+
     if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
     {
         OC_LOG(INFO, TAG, "Callback Context for GET query recvd successfully");
@@ -274,6 +287,10 @@ OCStackApplicationResult obsReqCB(void* ctx, OCDoHandle handle, OCClientResponse
             return OC_STACK_DELETE_TRANSACTION;
         }
     }
+    else
+    {
+        OC_LOG_V(INFO, TAG, "obsReqCB received Null clientResponse");
+    }
     return OC_STACK_KEEP_TRANSACTION;
 }
 #ifdef WITH_PRESENCE
@@ -302,6 +319,10 @@ OCStackApplicationResult presenceCB(void* ctx, OCDoHandle handle, OCClientRespon
             return OC_STACK_DELETE_TRANSACTION;
         }
     }
+    else
+    {
+        OC_LOG_V(INFO, TAG, "presenceCB received Null clientResponse");
+    }
     return OC_STACK_KEEP_TRANSACTION;
 }
 #endif
@@ -341,7 +362,7 @@ OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
                 InitGetRequest(OC_LOW_QOS, 0);
                 break;
             case TEST_PUT_REQ_NON:
-                InitPutRequest();
+                InitPutRequest(OC_LOW_QOS);
                 break;
             case TEST_POST_REQ_NON:
                 InitPostRequest(OC_LOW_QOS);
@@ -354,7 +375,7 @@ OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
                 InitObserveRequest(OC_LOW_QOS);
                 break;
             case TEST_GET_UNAVAILABLE_RES_REQ_NON:
-                InitGetRequestToUnavailableResource();
+                InitGetRequestToUnavailableResource(OC_LOW_QOS);
                 break;
             case TEST_GET_REQ_CON:
                 InitGetRequest(OC_HIGH_QOS, 0);
@@ -379,13 +400,17 @@ OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
                 InitGetRequest(OC_LOW_QOS, 1);
                 break;
             case TEST_DISCOVER_DEV_REQ:
-                InitDeviceDiscovery();
+                InitDeviceDiscovery(OC_LOW_QOS);
                 break;
             default:
                 PrintUsage();
                 break;
         }
     }
+    else
+    {
+        OC_LOG_V(INFO, TAG, "discoveryReqCB received Null clientResponse");
+    }
     return OC_STACK_KEEP_TRANSACTION;
 }
 
@@ -403,6 +428,10 @@ OCStackApplicationResult DeviceDiscoveryReqCB (void* ctx, OCDoHandle handle,
         fprintf(stderr, "Discovery response: \n %s\n", clientResponse->resJSONPayload);
         fflush(stderr);
     }
+    else
+    {
+        OC_LOG_V(INFO, TAG, "DeviceDiscoveryReqCB received Null clientResponse");
+    }
 
     return (UNICAST_DISCOVERY) ? OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION;
 }
@@ -441,12 +470,13 @@ int InitPresence()
 }
 #endif
 
-int InitGetRequestToUnavailableResource()
+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, OC_LOW_QOS, getReqCB, NULL, 0));
+    return (InvokeOCDoResource(query, OC_REST_GET, (qos == OC_HIGH_QOS)? OC_HIGH_QOS:OC_LOW_QOS,
+            getReqCB, NULL, 0));
 }
 
 int InitObserveRequest(OCQualityOfService qos)
@@ -458,12 +488,13 @@ int InitObserveRequest(OCQualityOfService qos)
             OC_REST_OBSERVE, (qos == OC_HIGH_QOS)? OC_HIGH_QOS:OC_LOW_QOS, obsReqCB, NULL, 0));
 }
 
-int InitPutRequest()
+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, OC_LOW_QOS, putReqCB, NULL, 0));
+    return (InvokeOCDoResource(query, OC_REST_PUT, (qos == OC_HIGH_QOS)? OC_HIGH_QOS:OC_LOW_QOS,
+            putReqCB, NULL, 0));
 }
 
 int InitPostRequest(OCQualityOfService qos)
@@ -591,7 +622,7 @@ int InitGetRequest(OCQualityOfService qos, uint8_t withVendorSpecificHeaderOptio
     }
 }
 
-int InitDeviceDiscovery()
+int InitDeviceDiscovery(OCQualityOfService qos)
 {
     OCStackResult ret;
     OCCallbackData cbData;
@@ -614,12 +645,12 @@ int InitDeviceDiscovery()
     if(UNICAST_DISCOVERY)
     {
         ret = OCDoResource(NULL, OC_REST_GET, szQueryUri, 0, 0, OC_CONNTYPE,
-                OC_LOW_QOS, &cbData, NULL, 0);
+                (qos == OC_HIGH_QOS) ? OC_HIGH_QOS : OC_LOW_QOS, &cbData, NULL, 0);
     }
     else
     {
         ret = OCDoResource(NULL, OC_REST_GET, szQueryUri, 0, 0, (OC_ALL),
-                OC_LOW_QOS, &cbData, NULL, 0);
+                (qos == OC_HIGH_QOS) ? OC_HIGH_QOS : OC_LOW_QOS, &cbData, NULL, 0);
     }
 
     if (ret != OC_STACK_OK)
@@ -630,7 +661,7 @@ int InitDeviceDiscovery()
     return ret;
 }
 
-int InitDiscovery()
+int InitDiscovery(OCQualityOfService qos)
 {
     OCStackResult ret;
     OCCallbackData cbData;
@@ -652,12 +683,12 @@ int InitDiscovery()
     if(UNICAST_DISCOVERY)
     {
         ret = OCDoResource(NULL, OC_REST_GET, szQueryUri, 0, 0, OC_CONNTYPE,
-                OC_LOW_QOS, &cbData, NULL, 0);
+                (qos == OC_HIGH_QOS) ? OC_HIGH_QOS : OC_LOW_QOS, &cbData, NULL, 0);
     }
     else
     {
         ret = OCDoResource(NULL, OC_REST_GET, szQueryUri, 0, 0, (OC_ALL),
-                OC_LOW_QOS, &cbData, NULL, 0);
+                (qos == OC_HIGH_QOS) ? OC_HIGH_QOS : OC_LOW_QOS, &cbData, NULL, 0);
     }
     if (ret != OC_STACK_OK)
     {
@@ -719,11 +750,11 @@ int main(int argc, char* argv[])
 
     if(UNICAST_DISCOVERY  == 0  && TEST_CASE == TEST_DISCOVER_DEV_REQ)
     {
-        InitDeviceDiscovery();
+        InitDeviceDiscovery(OC_LOW_QOS);
     }
     else
     {
-        InitDiscovery();
+        InitDiscovery(OC_LOW_QOS);
     }
 
     // Break from loop with Ctrl+C
@@ -825,3 +856,4 @@ void parseClientResponse(OCClientResponse * clientResponse)
     coapServerPort = getPortTBServer(clientResponse);
     coapServerResource = getQueryStrForGetPut(clientResponse);
 }
+
index b1fe562..c37ac29 100644 (file)
@@ -87,15 +87,15 @@ std::string getQueryStrForGetPut(OCClientResponse * clientResponse);
 /* Following are initialization functions for GET, Observe, PUT
  * POST, Delete & Discovery operations
  */
-int InitGetRequestToUnavailableResource();
+int InitGetRequestToUnavailableResource(OCQualityOfService qos);
 int InitObserveRequest(OCQualityOfService qos);
-int InitPutRequest();
+int InitPutRequest(OCQualityOfService qos);
 int InitGetRequest(OCQualityOfService qos, uint8_t withVendorSpecificHeaderOptions);
 int InitPostRequest(OCQualityOfService qos);
 int InitDeleteRequest(OCQualityOfService qos);
 int InitGetRequest(OCQualityOfService qos);
-int InitDeviceDiscovery();
-int InitDiscovery();
+int InitDeviceDiscovery(OCQualityOfService qos);
+int InitDiscovery(OCQualityOfService qos);
 
 /* Function to retrieve ip address, port no. of the server
  *  and query for the operations to be performed.
@@ -138,3 +138,4 @@ OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
 
 
 #endif
+
index 58c9df2..e126035 100644 (file)
@@ -342,7 +342,7 @@ int InitDiscovery()
     OCStackResult ret;
     OCCallbackData cbData;
     /* Start a discovery query*/
-    char szQueryUri[64] = { 0 };
+    char szQueryUri[64] = {};
     if (UNICAST_DISCOVERY)
     {
         char ipv4addr[IPV4_ADDR_SIZE];
@@ -427,7 +427,7 @@ const char * getPort(const OCClientResponse * clientResponse)
     return port;
 }
 
-int parseJSON(unsigned  const char * resJSONPayload, char ** sid_c,
+int parseJSON(const char * resJSONPayload, char ** sid_c,
               char *** uri_c, int * totalRes)
 {
     cJSON * root = NULL;
@@ -739,3 +739,4 @@ int main(int argc, char* argv[])
     return 0;
 }
 
+
index 2a33c49..c9d0dc9 100644 (file)
@@ -156,3 +156,4 @@ OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
         OCClientResponse * clientResponse);
 void StripNewLineChar(char* str);
 #endif
+
index 8422e37..dcdac06 100644 (file)
@@ -30,7 +30,7 @@
 const char *getResult(OCStackResult result);
 std::string getIPAddrTBServer(OCClientResponse * clientResponse);
 std::string getPortTBServer(OCClientResponse * clientResponse);
-std::string getQueryStrForGetPut(unsigned  const char * responsePayload);
+std::string getQueryStrForGetPut(const char * responsePayload);
 
 #define TAG PCF("occlient")
 #define DEFAULT_CONTEXT_VALUE 0x99
@@ -57,7 +57,7 @@ unsigned static int TEST = TEST_INVALID;
 
 typedef struct
 {
-    unsigned char text[30];
+    char text[30];
     CLIENT_TEST test;
 } testToTextMap;
 
@@ -445,10 +445,11 @@ std::string getPortTBServer(OCClientResponse * clientResponse)
     return ss.str();
 }
 
-std::string getQueryStrForGetPut(unsigned  const char * responsePayload)
+std::string getQueryStrForGetPut(const char * responsePayload)
 {
 
-    std::string jsonPayload(reinterpret_cast<char*>(const_cast<unsigned char*>(responsePayload)));
+    std::string jsonPayload(responsePayload);
 
     return "/a/room";
 }
+
index dc230c4..a31b9c7 100644 (file)
@@ -57,7 +57,7 @@ void handleSigInt(int signum)
 
 static void PrintUsage()
 {
-    OC_LOG(INFO, TAG, "Usage : occlient -u <0|1> -t <1|2|3> -c <0|1>");
+    OC_LOG(INFO, TAG, "Usage : occlient -c <0|1> -u <0|1> -t <1|2|3>");
     OC_LOG(INFO, TAG, "-c <0|1> : Send unicast messages over Ethernet or WIFI");
     OC_LOG(INFO, TAG, "-u <0|1> : Perform multicast/unicast discovery of resources");
     OC_LOG(INFO, TAG, "-t 1 : Discover Resources");
@@ -322,3 +322,4 @@ void parseClientResponse(OCClientResponse * clientResponse)
     coapServerPort = getPortTBServer(clientResponse);
     coapServerResource = getQueryStrForGetPut(clientResponse);
 }
+
index a2df222..8b6bcc4 100644 (file)
@@ -94,3 +94,4 @@ OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
         OCClientResponse * clientResponse);
 
 #endif
+
index 9e76255..dbfeec7 100644 (file)
@@ -470,7 +470,7 @@ OCDeviceEntityHandlerCb (OCEntityHandlerFlag flag,
             response.requestHandle = entityHandlerRequest->requestHandle;
             response.resourceHandle = entityHandlerRequest->resource;
             response.ehResult = ehResult;
-            response.payload = (unsigned char *)payload;
+            response.payload = payload;
             response.payloadSize = strlen(payload);
             // Indicate that response is NOT in a persistent buffer
             response.persistentBufferFlag = 0;
@@ -572,7 +572,7 @@ OCEntityHandlerCb (OCEntityHandlerFlag flag,
             response.requestHandle = entityHandlerRequest->requestHandle;
             response.resourceHandle = entityHandlerRequest->resource;
             response.ehResult = ehResult;
-            response.payload = (unsigned char *)payload;
+            response.payload = payload;
             response.payloadSize = strlen(payload);
             // Indicate that response is NOT in a persistent buffer
             response.persistentBufferFlag = 0;
@@ -683,7 +683,7 @@ void *ChangeLightRepresentation (void *param)
                 char * obsResp = cJSON_Print(json);
                 cJSON_Delete(json);
                 result = OCNotifyListOfObservers (Light.handle, obsNotify, j,
-                        (unsigned char *)obsResp, OC_NA_QOS);
+                        obsResp, OC_NA_QOS);
                 free(obsResp);
             }
             else if (gObserveNotifyType == 0)
@@ -1032,3 +1032,4 @@ OCStackResult SetDeviceInfo(const char *contentType, const char *dateOfManufactu
     DeleteDeviceInfo();
     return OC_STACK_ERROR;
 }
+
index 3eb0943..d5167ca 100644 (file)
@@ -49,6 +49,13 @@ char *gResourceUri= (char *)"/a/led";
 char* constructJsonResponse (OCEntityHandlerRequest *ehRequest)
 {
     cJSON *json = cJSON_CreateObject();
+
+    if(!json)
+    {
+        OC_LOG (ERROR, TAG, "json object not created properly");
+        return NULL;
+    }
+
     cJSON *format;
     char *jsonResponse;
     LEDResource *currLEDResource = &LED;
@@ -67,6 +74,13 @@ char* constructJsonResponse (OCEntityHandlerRequest *ehRequest)
     if(OC_REST_PUT == ehRequest->method)
     {
         cJSON *putJson = cJSON_Parse((char *)ehRequest->reqJSONPayload);
+
+        if(!putJson)
+        {
+            OC_LOG (ERROR, TAG, "putJson object not created properly");
+            cJSON_Delete(json);
+            return NULL;
+        }
         currLEDResource->state = ( !strcmp(cJSON_GetObjectItem(putJson,"state")->valuestring ,
                 "on") ? true:false);
         currLEDResource->power = cJSON_GetObjectItem(putJson,"power")->valuedouble;
@@ -74,7 +88,16 @@ char* constructJsonResponse (OCEntityHandlerRequest *ehRequest)
     }
 
     cJSON_AddStringToObject(json,"href",gResourceUri);
-    cJSON_AddItemToObject(json, "rep", format=cJSON_CreateObject());
+    format = cJSON_CreateObject();
+
+    if(!format)
+    {
+        OC_LOG (ERROR, TAG, "format object not created properly");
+        cJSON_Delete(json);
+        return NULL;
+    }
+
+    cJSON_AddItemToObject(json, "rep", format);
     cJSON_AddStringToObject(format, "state", (char *) (currLEDResource->state ? "on":"off"));
     cJSON_AddNumberToObject(format, "power", currLEDResource->power);
 
@@ -83,51 +106,68 @@ char* constructJsonResponse (OCEntityHandlerRequest *ehRequest)
     return jsonResponse;
 }
 
-OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest, char *payload, uint16_t maxPayloadSize)
+OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest, char *payload,
+        uint16_t maxPayloadSize)
 {
     OCEntityHandlerResult ehResult;
     char *getResp = constructJsonResponse(ehRequest);
 
-    if (maxPayloadSize > strlen ((char *)getResp))
+    if(getResp)
     {
-        strncpy(payload, getResp, strlen((char *)getResp));
-        ehResult = OC_EH_OK;
+        if (maxPayloadSize > strlen ((char *)getResp))
+        {
+            strncpy(payload, getResp, strlen((char *)getResp));
+            ehResult = OC_EH_OK;
+        }
+        else
+        {
+            OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
+                    maxPayloadSize);
+            ehResult = OC_EH_ERROR;
+        }
+
+        free(getResp);
     }
     else
     {
-        OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
-                maxPayloadSize);
         ehResult = OC_EH_ERROR;
     }
 
-    free(getResp);
-
     return ehResult;
 }
 
-OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest, char *payload, uint16_t maxPayloadSize)
+OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest, char *payload,
+        uint16_t maxPayloadSize)
 {
     OCEntityHandlerResult ehResult;
     char *putResp = constructJsonResponse(ehRequest);
 
-    if (maxPayloadSize > strlen ((char *)putResp))
+    if(putResp)
     {
-        strncpy(payload, putResp, strlen((char *)putResp));
-        ehResult = OC_EH_OK;
+        if (maxPayloadSize > strlen ((char *)putResp))
+        {
+            strncpy(payload, putResp, strlen((char *)putResp));
+            ehResult = OC_EH_OK;
+        }
+        else
+        {
+            OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
+                    maxPayloadSize);
+            ehResult = OC_EH_ERROR;
+        }
+
+        free(putResp);
     }
     else
     {
-        OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
-                maxPayloadSize);
         ehResult = OC_EH_ERROR;
     }
 
-    free(putResp);
-
     return ehResult;
 }
 
-OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest, char *payload, uint16_t maxPayloadSize)
+OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest, char *payload,
+        uint16_t maxPayloadSize)
 {
     char *respPLPost_led = NULL;
     cJSON *json;
@@ -154,9 +194,20 @@ OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest, cha
             snprintf(newLedUri, URI_MAXSIZE, "/a/led/%d", gCurrLedInstance);
 
             json = cJSON_CreateObject();
+            if(!json)
+            {
+                return OC_EH_ERROR;
+            }
 
             cJSON_AddStringToObject(json,"href",gResourceUri);
-            cJSON_AddItemToObject(json, "rep", format=cJSON_CreateObject());
+            format = cJSON_CreateObject();
+
+            if(!format)
+            {
+                return OC_EH_ERROR;
+            }
+
+            cJSON_AddItemToObject(json, "rep", format);
             cJSON_AddStringToObject(format, "createduri", (char *) newLedUri);
 
             if (0 == createLEDResource (newLedUri, &gLedInstance[gCurrLedInstance], false, 0))
@@ -258,7 +309,7 @@ OCEntityHandlerCb (OCEntityHandlerFlag flag,
                 response.requestHandle = entityHandlerRequest->requestHandle;
                 response.resourceHandle = entityHandlerRequest->resource;
                 response.ehResult = ehResult;
-                response.payload = (unsigned char *)payload;
+                response.payload = payload;
                 response.payloadSize = strlen(payload);
                 response.numSendVendorSpecificHeaderOptions = 0;
                 memset(response.sendVendorSpecificHeaderOptions, 0, sizeof response.sendVendorSpecificHeaderOptions);
@@ -345,3 +396,4 @@ int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState,
 
     return 0;
 }
+
index 71d8d46..5f65d4d 100644 (file)
@@ -216,7 +216,7 @@ OCEntityHandlerResult OCEntityHandlerRoomCb(OCEntityHandlerFlag flag,
                 response.requestHandle = ehRequest->requestHandle;
                 response.resourceHandle = ehRequest->resource;
                 response.ehResult = ret;
-                response.payload = (unsigned char *)payload;
+                response.payload = payload;
                 response.payloadSize = strlen(payload);
                 response.numSendVendorSpecificHeaderOptions = 0;
                 memset(response.sendVendorSpecificHeaderOptions,
@@ -288,7 +288,7 @@ OCEntityHandlerResult OCEntityHandlerRoomCb(OCEntityHandlerFlag flag,
                 response.requestHandle = ehRequest->requestHandle;
                 response.resourceHandle = ehRequest->resource;
                 response.ehResult = ret;
-                response.payload = (unsigned char *)payload;
+                response.payload = payload;
                 response.payloadSize = strlen(payload);
                 response.numSendVendorSpecificHeaderOptions = 0;
                 memset(response.sendVendorSpecificHeaderOptions,
@@ -353,7 +353,7 @@ OCEntityHandlerResult OCEntityHandlerLightCb(OCEntityHandlerFlag flag,
             response.requestHandle = ehRequest->requestHandle;
             response.resourceHandle = ehRequest->resource;
             response.ehResult = ret;
-            response.payload = (unsigned char *)payload;
+            response.payload = payload;
             response.payloadSize = strlen(payload);
             response.numSendVendorSpecificHeaderOptions = 0;
             memset(response.sendVendorSpecificHeaderOptions,
@@ -413,7 +413,7 @@ OCEntityHandlerResult OCEntityHandlerFanCb(OCEntityHandlerFlag flag,
             response.requestHandle = ehRequest->requestHandle;
             response.resourceHandle = ehRequest->resource;
             response.ehResult = ret;
-            response.payload = (unsigned char *)payload;
+            response.payload = payload;
             response.payloadSize = strlen(payload);
             response.numSendVendorSpecificHeaderOptions = 0;
             memset(response.sendVendorSpecificHeaderOptions,
@@ -593,3 +593,4 @@ void createResources()
     res = OCBindResource(room, fan);
     OC_LOG_V(INFO, TAG, "OC Bind Contained Resource to resource: %s", getResult(res));
 }
+
index a403915..533787a 100644 (file)
@@ -50,6 +50,13 @@ char *gResourceUri= (char *)"/a/led";
 char* constructJsonResponse (OCEntityHandlerRequest *ehRequest)
 {
     cJSON *json = cJSON_CreateObject();
+
+    if(!json)
+    {
+        OC_LOG(ERROR, TAG, "CreateObject result in null for json");
+        return NULL;
+    }
+
     cJSON *format;
     char *jsonResponse;
     LEDResource *currLEDResource = &LED;
@@ -72,6 +79,14 @@ char* constructJsonResponse (OCEntityHandlerRequest *ehRequest)
     if(OC_REST_PUT == ehRequest->method)
     {
         cJSON *putJson = cJSON_Parse((char *)ehRequest->reqJSONPayload);
+
+        if(!putJson)
+        {
+            OC_LOG(ERROR, TAG, "CreateObject result in null for putJson");
+            cJSON_Delete(json);
+            return NULL;
+        }
+
         currLEDResource->state = ( !strcmp(cJSON_GetObjectItem(putJson,"state")->valuestring ,
                 "on") ? true:false);
         currLEDResource->power = cJSON_GetObjectItem(putJson,"power")->valuedouble;
@@ -79,7 +94,16 @@ char* constructJsonResponse (OCEntityHandlerRequest *ehRequest)
     }
 
     cJSON_AddStringToObject(json,"href",gResourceUri);
-    cJSON_AddItemToObject(json, "rep", format=cJSON_CreateObject());
+    format = cJSON_CreateObject();
+
+    if(!format)
+    {
+        OC_LOG(ERROR, TAG, "CreateObject result in null for format");
+        cJSON_Delete(json);
+        return NULL;
+    }
+
+    cJSON_AddItemToObject(json, "rep", format);
     cJSON_AddStringToObject(format, "state", (char *) (currLEDResource->state ? "on":"off"));
     cJSON_AddNumberToObject(format, "power", currLEDResource->power);
 
@@ -103,7 +127,7 @@ void ProcessGetRequest (OCEntityHandlerRequest *ehRequest)
     response.requestHandle = ehRequest->requestHandle;
     response.resourceHandle = ehRequest->resource;
     response.ehResult = OC_EH_OK;
-    response.payload = (unsigned char *)getResp;
+    response.payload = getResp;
     response.payloadSize = strlen(getResp) + 1;
     response.numSendVendorSpecificHeaderOptions = 0;
     memset(response.sendVendorSpecificHeaderOptions,
@@ -132,13 +156,13 @@ OCEntityHandlerRequest *CopyRequest(OCEntityHandlerRequest *entityHandlerRequest
         memcpy(request, entityHandlerRequest, sizeof(OCEntityHandlerRequest));
         // Do deep copy of query
         request->query =
-                (unsigned char * )OCMalloc(strlen((const char *)entityHandlerRequest->query) + 1);
+                (char * )OCMalloc(strlen((const char *)entityHandlerRequest->query) + 1);
         if (request->query)
         {
             strcpy((char *)request->query, (const char *)entityHandlerRequest->query);
 
             // Copy the request payload
-            request->reqJSONPayload = (unsigned char * )OCMalloc(
+            request->reqJSONPayload = (char * )OCMalloc(
                             strlen((const char *)entityHandlerRequest->reqJSONPayload) + 1);
             if (request->reqJSONPayload)
             {
@@ -347,3 +371,4 @@ int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState,
 
     return 0;
 }
+
index 451d3f5..c312d35 100644 (file)
@@ -1,3 +1,22 @@
+#******************************************************************
+#
+# Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
 Import('env')
 
@@ -54,3 +73,4 @@ gen_sec_bin = samples_env.Program('gen_sec_bin', ['gen_sec_bin.cpp'])
 Alias("samples", [ocserverbasicops, occlientbasicops])
 
 env.AppendTarget('samples')
+
index 0a65ea0..e5aad51 100644 (file)
@@ -166,12 +166,12 @@ OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
             {
                 case TEST_NON_CON_OP:
                     InitGetRequest(OC_LOW_QOS);
-                    InitPutRequest();
+                    InitPutRequest(OC_LOW_QOS);
                     //InitPostRequest(OC_LOW_QOS);
                     break;
                 case TEST_CON_OP:
                     InitGetRequest(OC_HIGH_QOS);
-                    InitPutRequest();
+                    InitPutRequest(OC_HIGH_QOS);
                     //InitPostRequest(OC_HIGH_QOS);
                     break;
             }
@@ -182,13 +182,14 @@ OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
 
 }
 
-int InitPutRequest()
+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, OC_LOW_QOS, putReqCB, NULL, 0));
+    return (InvokeOCDoResource(query, OC_REST_PUT,
+            ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS), putReqCB, NULL, 0));
 }
 
 int InitPostRequest(OCQualityOfService qos)
@@ -235,7 +236,7 @@ int InitGetRequest(OCQualityOfService qos)
             OC_HIGH_QOS:OC_LOW_QOS, getReqCB, NULL, 0));
 }
 
-int InitDiscovery()
+int InitDiscovery(OCQualityOfService qos)
 {
     OCStackResult ret;
     OCCallbackData cbData;
@@ -278,7 +279,8 @@ int InitDiscovery()
         szQueryUri);
 
     ret = OCDoResource(NULL, OC_REST_GET, szQueryUri, 0, 0,
-            discoveryReqConnType, OC_LOW_QOS, &cbData, NULL, 0);
+            discoveryReqConnType, ((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");
@@ -331,7 +333,14 @@ int main(int argc, char* argv[])
         return 0;
     }
 
-    InitDiscovery();
+    if(TEST_CASE == TEST_NON_CON_OP)
+    {
+        InitDiscovery(OC_LOW_QOS);
+    }
+    else if(TEST_CASE == TEST_CON_OP)
+    {
+        InitDiscovery(OC_HIGH_QOS);
+    }
 
     timeout.tv_sec  = 0;
     timeout.tv_nsec = 100000000L;
@@ -458,3 +467,4 @@ int parseClientResponse(OCClientResponse * clientResponse)
     }
     return 0;
 }
+
index 689d7e6..8f8326c 100644 (file)
@@ -53,10 +53,10 @@ std::string getQueryStrForGetPut(OCClientResponse * clientResponse);
 /* Following are initialization functions for GET, PUT
  * POST & Discovery operations
  */
-int InitPutRequest();
+int InitPutRequest(OCQualityOfService qos);
 int InitGetRequest(OCQualityOfService qos);
 int InitPostRequest(OCQualityOfService qos);
-int InitDiscovery();
+int InitDiscovery(OCQualityOfService qos);
 
 /* Function to retrieve ip address, port no. of the server
  *  and query for the operations to be performed.
index 4105740..582902c 100644 (file)
@@ -91,20 +91,27 @@ OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest,
     OCEntityHandlerResult ehResult;
 
     char *getResp = constructJsonResponse(ehRequest);
-    if (maxPayloadSize > strlen (getResp))
+    if(getResp)
     {
-        strcpy(payload, getResp);
-        ehResult = OC_EH_OK;
+        if (maxPayloadSize > strlen (getResp))
+        {
+            strcpy(payload, getResp);
+            ehResult = OC_EH_OK;
+        }
+        else
+        {
+            OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
+                    maxPayloadSize);
+            ehResult = OC_EH_ERROR;
+        }
+
+        free(getResp);
     }
     else
     {
-        OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
-                maxPayloadSize);
         ehResult = OC_EH_ERROR;
     }
 
-    free(getResp);
-
     return ehResult;
 }
 
@@ -114,20 +121,28 @@ OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest,
     OCEntityHandlerResult ehResult;
 
     char *putResp = constructJsonResponse(ehRequest);
-    if (maxPayloadSize > strlen (putResp))
+
+    if(putResp)
     {
-        strcpy(payload, putResp);
-        ehResult = OC_EH_OK;
+        if (maxPayloadSize > strlen (putResp))
+        {
+            strcpy(payload, putResp);
+            ehResult = OC_EH_OK;
+        }
+        else
+        {
+            OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
+                    maxPayloadSize);
+            ehResult = OC_EH_ERROR;
+        }
+
+        free(putResp);
     }
     else
     {
-        OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
-                maxPayloadSize);
         ehResult = OC_EH_ERROR;
     }
 
-    free(putResp);
-
     return ehResult;
 }
 
@@ -265,7 +280,7 @@ OCEntityHandlerCb (OCEntityHandlerFlag flag,
                 response.requestHandle = entityHandlerRequest->requestHandle;
                 response.resourceHandle = entityHandlerRequest->resource;
                 response.ehResult = ehResult;
-                response.payload = (unsigned char *)payload;
+                response.payload = payload;
                 response.payloadSize = strlen(payload);
                 response.numSendVendorSpecificHeaderOptions = 0;
                 memset(response.sendVendorSpecificHeaderOptions, 0, sizeof response.sendVendorSpecificHeaderOptions);
@@ -366,3 +381,4 @@ int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState,
 
     return 0;
 }
+
index 48a46a1..d93c69d 100644 (file)
 #define TAG PCF("occlientcb")
 
 struct ClientCB *cbList = NULL;
-OCMulticastNode * mcPresenceNodes = NULL;
+static OCMulticastNode * mcPresenceNodes = NULL;
 
 OCStackResult
 AddClientCB (ClientCB** clientCB, OCCallbackData* cbData,
              CAToken_t * token, OCDoHandle *handle, OCMethod method,
-             unsigned char * requestUri, unsigned char * resourceTypeName)
+             char * requestUri, char * resourceTypeName)
 {
+    if(!clientCB || !cbData || !token || !handle || !requestUri)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
 
     ClientCB *cbNode = NULL;
 
@@ -100,7 +104,8 @@ AddClientCB (ClientCB** clientCB, OCCallbackData* cbData,
         return OC_STACK_NO_MEMORY;
 }
 
-void DeleteClientCB(ClientCB * cbNode) {
+void DeleteClientCB(ClientCB * cbNode)
+{
     if(cbNode) {
         LL_DELETE(cbList, cbNode);
         OC_LOG(INFO, TAG, PCF("deleting tokens"));
@@ -136,7 +141,7 @@ void DeleteClientCB(ClientCB * cbNode) {
     }
 }
 
-ClientCB* GetClientCB(const CAToken_t * token, OCDoHandle handle, const unsigned char * requestUri)
+ClientCB* GetClientCB(const CAToken_t * token, OCDoHandle handle, const char * requestUri)
 {
     ClientCB* out = NULL;
     if(token) {
@@ -159,7 +164,8 @@ ClientCB* GetClientCB(const CAToken_t * token, OCDoHandle handle, const unsigned
     }
     else if(requestUri) {
         LL_FOREACH(cbList, out) {
-            if(out->requestUri && strcmp((char *)out->requestUri, (char *)requestUri) == 0) {
+            if(out->requestUri && strcmp(out->requestUri, requestUri ) == 0)
+            {
                 return out;
             }
         }
@@ -215,8 +221,13 @@ void FindAndDeleteClientCB(ClientCB * cbNode) {
     }
 }
 
-OCStackResult AddMCPresenceNode(OCMulticastNode** outnode, unsigned char* uri, uint32_t nonce)
+OCStackResult AddMCPresenceNode(OCMulticastNode** outnode, char* uri, uint32_t nonce)
 {
+    if(!outnode)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+
     OCMulticastNode *node;
 
     node = (OCMulticastNode*) OCMalloc(sizeof(OCMulticastNode));
@@ -232,12 +243,12 @@ OCStackResult AddMCPresenceNode(OCMulticastNode** outnode, unsigned char* uri, u
     return OC_STACK_NO_MEMORY;
 }
 
-OCMulticastNode* GetMCPresenceNode(const unsigned char * uri) {
+OCMulticastNode* GetMCPresenceNode(const char * uri) {
     OCMulticastNode* out = NULL;
 
     if(uri) {
         LL_FOREACH(mcPresenceNodes, out) {
-            if(out->uri && strcmp((char *)out->uri, (char *)uri) == 0) {
+            if(out->uri && strcmp(out->uri, uri) == 0) {
                 return out;
             }
         }
@@ -245,3 +256,4 @@ OCMulticastNode* GetMCPresenceNode(const unsigned char * uri) {
     OC_LOG(INFO, TAG, PCF("MulticastNode Not found !!"));
     return NULL;
 }
+
index 246b263..5a8aa8a 100644 (file)
 
 static OCStackResult CheckRTParamSupport(const OCResource* resource, const char* rtPtr)
 {
+    if(!resource || !rtPtr)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+
     OCResourceType* rTPointer = resource->rsrcType;
     while (rTPointer)
     {
         if( strcmp (rTPointer->resourcetypename, rtPtr) == 0)
+        {
             return OC_STACK_OK;
+        }
 
         rTPointer = rTPointer->next;
     }
@@ -51,11 +58,18 @@ static OCStackResult CheckRTParamSupport(const OCResource* resource, const char*
 
 static OCStackResult CheckIFParamSupport(const OCResource* resource, const char* ifPtr)
 {
+    if(!resource || !ifPtr)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+
     OCResourceInterface* iFPointer = resource->rsrcInterface;
     while (iFPointer)
     {
         if( strcmp (iFPointer->name, ifPtr) == 0)
-             return OC_STACK_OK;
+        {
+            return OC_STACK_OK;
+        }
 
         iFPointer = iFPointer->next;
     }
@@ -63,10 +77,11 @@ static OCStackResult CheckIFParamSupport(const OCResource* resource, const char*
 }
 
 static OCStackResult
-ValidateQuery (const unsigned char *query, OCResourceHandle resource,
+ValidateQuery (const char *query, OCResourceHandle resource,
                              OCStackIfTypes *ifParam, char **rtParam)
 {
-    uint8_t numFields = 0, numParam;
+    uint8_t numFields = 0;
+    uint8_t numParam;
 
     //TODO: Query and URL validation is being done for virtual resource case
     // using ValidateUrlQuery function. We should be able to merge it with this
@@ -76,6 +91,11 @@ ValidateQuery (const unsigned char *query, OCResourceHandle resource,
     if (!query)
         return OC_STACK_ERROR;
 
+    if(!ifParam || !rtParam)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+
     if (!(*query))
     {
         // Query string is empty
@@ -102,16 +122,20 @@ ValidateQuery (const unsigned char *query, OCResourceHandle resource,
         while (innerToken != NULL)
         {
             numParam++;
-            if (strcmp (innerToken, OC_RSRVD_INTERFACE) == 0)
+            if (strncmp (innerToken, OC_RSRVD_INTERFACE, sizeof(OC_RSRVD_INTERFACE)) == 0)
             {
                 // Determine the value of IF parameter
                 innerToken = strtok_r (NULL, "=", &endToken);
                 ifPtr = innerToken;
-            } else if (strcmp (innerToken, OC_RSRVD_RESOURCE_TYPE) == 0) {
+            }
+            else if (strcmp (innerToken, OC_RSRVD_RESOURCE_TYPE) == 0)
+            {
                 // Determine the value of RT parameter
                 innerToken = strtok_r (NULL, "=", &endToken);
                 rtPtr = innerToken;
-            } else {
+            }
+            else
+            {
                 innerToken = strtok_r (NULL, "=", &endToken);
             }
         }
@@ -124,7 +148,7 @@ ValidateQuery (const unsigned char *query, OCResourceHandle resource,
     }
     if (numFields > NUM_PARAM_IN_QUERY)
     {
-        // M1 release supports one IF value, one RT value and no other params
+        // current release supports one IF value, one RT value and no other params
         return OC_STACK_INVALID_QUERY;
     }
 
@@ -184,7 +208,7 @@ ValidateQuery (const unsigned char *query, OCResourceHandle resource,
 
 
 static OCStackResult BuildRootResourceJSON(OCResource *resource,
-        unsigned char * bufferPtr, uint16_t *remaining)
+        char * bufferPtr, uint16_t *remaining)
 {
     OCStackResult ret = OC_STACK_ERROR;
     cJSON *resObj;
@@ -202,14 +226,14 @@ static OCStackResult BuildRootResourceJSON(OCResource *resource,
     jsonLen = strlen(jsonStr);
     if (jsonLen < *remaining)
     {
-        strcpy((char*) bufferPtr, jsonStr);
+        strncpy(bufferPtr, jsonStr, jsonLen);
         *remaining -= jsonLen;
         bufferPtr += jsonLen;
         ret = OC_STACK_OK;
     }
 
     cJSON_Delete (resObj);
-    free (jsonStr);
+    OCFree(jsonStr);
 
     return ret;
 }
@@ -219,11 +243,16 @@ static OCStackResult
 HandleLinkedListInterface(OCEntityHandlerRequest *ehRequest,
                        uint8_t filterOn, char *filterValue)
 {
+    if(!ehRequest)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+
     OCStackResult ret = OC_STACK_ERROR;
-    unsigned char jsonbuffer[MAX_RESPONSE_LENGTH] = {0};
+    char jsonbuffer[MAX_RESPONSE_LENGTH] = {};
     size_t jsonbufferLength = 0;
     uint16_t remaining = 0;
-    unsigned char * ptr = NULL;
+    char * ptr = NULL;
     OCResource * collResource = (OCResource *) ehRequest->resource;
 
     ptr = jsonbuffer;
@@ -278,7 +307,7 @@ HandleLinkedListInterface(OCEntityHandlerRequest *ehRequest,
     jsonbufferLength = strlen((const char *)jsonbuffer);
     if(ret == OC_STACK_OK && jsonbufferLength)
     {
-        OCEntityHandlerResponse response = {0};
+        OCEntityHandlerResponse response = {};
         response.ehResult = OC_EH_OK;
         response.payload = jsonbuffer;
         response.payloadSize = jsonbufferLength + 1;
@@ -295,10 +324,10 @@ HandleBatchInterface(OCEntityHandlerRequest *ehRequest)
 {
     OCStackResult stackRet = OC_STACK_ERROR;
     OCEntityHandlerResult ehResult = OC_EH_ERROR;
-    unsigned char jsonbuffer[MAX_RESPONSE_LENGTH] = {0};
+    char jsonbuffer[MAX_RESPONSE_LENGTH] = {0};
     size_t jsonbufferLength = 0;
     uint16_t remaining = 0;
-    unsigned char * ptr = NULL;
+    char * ptr = NULL;
     OCResource * collResource = (OCResource *) ehRequest->resource;
 
     ptr = jsonbuffer;
@@ -311,7 +340,7 @@ HandleBatchInterface(OCEntityHandlerRequest *ehRequest)
     jsonbufferLength = strlen((const char *)jsonbuffer);
     if(jsonbufferLength)
     {
-        OCEntityHandlerResponse response = {0};
+        OCEntityHandlerResponse response = {};
         response.ehResult = OC_EH_OK;
         response.payload = jsonbuffer;
         response.payloadSize = jsonbufferLength + 1;
@@ -361,21 +390,33 @@ HandleBatchInterface(OCEntityHandlerRequest *ehRequest)
 
 uint8_t GetNumOfResourcesInCollection (OCResource *resource)
 {
-    uint8_t num = 0;
-    for (int i = 0; i < MAX_CONTAINED_RESOURCES; i++)
+    if(resource)
     {
-        if (resource->rsrcResources[i])
+        uint8_t num = 0;
+        for (int i = 0; i < MAX_CONTAINED_RESOURCES; i++)
         {
-            num++;
+            if (resource->rsrcResources[i])
+            {
+                num++;
+            }
         }
+        return num;
+    }
+    else
+    {
+        return -1;
     }
-    return num;
 }
 
 
 OCStackResult DefaultCollectionEntityHandler (OCEntityHandlerFlag flag,
                                               OCEntityHandlerRequest *ehRequest)
 {
+    if(!ehRequest || !ehRequest->query)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+
     OCStackResult result = OC_STACK_ERROR;
     OCStackIfTypes ifQueryParam = STACK_IF_INVALID;
     char *rtQueryParam = NULL;
@@ -383,19 +424,24 @@ OCStackResult DefaultCollectionEntityHandler (OCEntityHandlerFlag flag,
     OC_LOG_V(INFO, TAG, "DefaultCollectionEntityHandler with query %s", ehRequest->query);
 
     if (flag != OC_REQUEST_FLAG)
+    {
         return OC_STACK_ERROR;
+    }
 
-    result = ValidateQuery ((const unsigned char *)ehRequest->query,
+    result = ValidateQuery (ehRequest->query,
                             ehRequest->resource, &ifQueryParam, &rtQueryParam);
 
     if (result != OC_STACK_OK)
+    {
         return result;
+    }
 
-  
-    if(!((ehRequest->method == OC_REST_GET) || 
+    if(!((ehRequest->method == OC_REST_GET) ||
         (ehRequest->method == OC_REST_PUT) ||
         (ehRequest->method == OC_REST_POST)))
+    {
         return OC_STACK_ERROR;
+    }
 
     if (ehRequest->method == OC_REST_GET)
     {
@@ -414,7 +460,8 @@ OCStackResult DefaultCollectionEntityHandler (OCEntityHandlerFlag flag,
 
             case STACK_IF_BATCH:
                 OC_LOG(INFO, TAG, PCF("STACK_IF_BATCH"));
-                ((OCServerRequest *)ehRequest->requestHandle)->ehResponseHandler = HandleAggregateResponse;
+                ((OCServerRequest *)ehRequest->requestHandle)->ehResponseHandler =
+                                                                        HandleAggregateResponse;
                 ((OCServerRequest *)ehRequest->requestHandle)->numResponses =
                         GetNumOfResourcesInCollection((OCResource *)ehRequest->resource) + 1;
                 return HandleBatchInterface(ehRequest);
@@ -424,7 +471,9 @@ OCStackResult DefaultCollectionEntityHandler (OCEntityHandlerFlag flag,
             default:
                 return OC_STACK_ERROR;
         }
-    } else if (ehRequest->method == OC_REST_PUT) {
+    }
+    else if (ehRequest->method == OC_REST_PUT)
+    {
         switch (ifQueryParam)
         {
             case STACK_IF_DEFAULT:
@@ -436,7 +485,8 @@ OCStackResult DefaultCollectionEntityHandler (OCEntityHandlerFlag flag,
                 return OC_STACK_ERROR;
 
             case STACK_IF_BATCH:
-                ((OCServerRequest *)ehRequest->requestHandle)->ehResponseHandler = HandleAggregateResponse;
+                ((OCServerRequest *)ehRequest->requestHandle)->ehResponseHandler =
+                                                                        HandleAggregateResponse;
                 ((OCServerRequest *)ehRequest->requestHandle)->numResponses =
                         GetNumOfResourcesInCollection((OCResource *)ehRequest->resource) + 1;
                 return HandleBatchInterface(ehRequest);
@@ -455,19 +505,19 @@ OCStackResult DefaultCollectionEntityHandler (OCEntityHandlerFlag flag,
     else if (ehRequest->method == OC_REST_POST)
     {
 
-        switch (ifQueryParam)
+        if(ifQueryParam == STACK_IF_GROUP)
         {
-            case STACK_IF_GROUP:
-            {
-                OC_LOG_V(INFO, TAG, "IF_COLLECTION POST with request :: \n%s\n ",
-                        ehRequest->reqJSONPayload);
-                return BuildCollectionGroupActionJSONResponse(OC_REST_POST/*flag*/,
-                        (OCResource *) ehRequest->resource, ehRequest);
-            }
-            default:
-                return OC_STACK_ERROR;
+            OC_LOG_V(INFO, TAG, "IF_COLLECTION POST with request :: \n%s\n ",
+                    ehRequest->reqJSONPayload);
+            return BuildCollectionGroupActionJSONResponse(OC_REST_POST/*flag*/,
+                    (OCResource *) ehRequest->resource, ehRequest);
+        }
+        else
+        {
+            return OC_STACK_ERROR;
         }
     }
     return result;
 }
 
+
index 0d5e9ea..ef5e42e 100644 (file)
@@ -47,6 +47,12 @@ static struct ResourceObserver * serverObsList = NULL;
 OCQualityOfService DetermineObserverQoS(OCMethod method, ResourceObserver * resourceObserver,
         OCQualityOfService appQoS)
 {
+    if(!resourceObserver)
+    {
+        OC_LOG(ERROR, TAG, "DetermineObserverQoS called with invalid resourceObserver");
+        return -1;
+    }
+
     OCQualityOfService decidedQoS = appQoS;
     if(appQoS == OC_NA_QOS)
     {
@@ -65,13 +71,13 @@ OCQualityOfService DetermineObserverQoS(OCMethod method, ResourceObserver * reso
         if(resourceObserver->forceHighQos \
                 || resourceObserver->lowQosCount >= MAX_OBSERVER_NON_COUNT)
         #endif
-            {
+        {
             resourceObserver->lowQosCount = 0;
             // at some point we have to to send CON to check on the
             // availability of observer
             OC_LOG(INFO, TAG, PCF("This time we are sending the  notification as High qos"));
             decidedQoS = OC_HIGH_QOS;
-            }
+        }
         else
         {
             (resourceObserver->lowQosCount)++;
@@ -89,11 +95,16 @@ OCStackResult SendAllObserverNotification (OCMethod method, OCResource *resPtr,
 #endif
 {
     OC_LOG(INFO, TAG, PCF("Entering SendObserverNotification"));
+    if(!resPtr)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+
     OCStackResult result = OC_STACK_ERROR;
     ResourceObserver * resourceObserver = serverObsList;
     uint8_t numObs = 0;
     OCServerRequest * request = NULL;
-    OCEntityHandlerRequest ehRequest = {0};
+    OCEntityHandlerRequest ehRequest = {};
     OCEntityHandlerResult ehResult = OC_EH_ERROR;
 
     // Find clients that are observing this resource
@@ -121,8 +132,10 @@ OCStackResult SendAllObserverNotification (OCMethod method, OCResource *resPtr,
                     {
                         result = FormOCEntityHandlerRequest(&ehRequest, (OCRequestHandle) request,
                                     request->method, (OCResourceHandle) resPtr, request->query,
-                                    request->reqJSONPayload, request->numRcvdVendorSpecificHeaderOptions,
-                                    request->rcvdVendorSpecificHeaderOptions, OC_OBSERVE_NO_OPTION, 0);
+                                    request->reqJSONPayload,
+                                    request->numRcvdVendorSpecificHeaderOptions,
+                                    request->rcvdVendorSpecificHeaderOptions,
+                                    OC_OBSERVE_NO_OPTION, 0);
                         if(result == OC_STACK_OK)
                         {
                             ehResult = resPtr->entityHandler(OC_REQUEST_FLAG, &ehRequest);
@@ -137,8 +150,8 @@ OCStackResult SendAllObserverNotification (OCMethod method, OCResource *resPtr,
             }
             else
             {
-                OCEntityHandlerResponse ehResponse = {0};
-                unsigned char presenceResBuf[MAX_RESPONSE_LENGTH] = {0};
+                OCEntityHandlerResponse ehResponse = {};
+                char presenceResBuf[MAX_RESPONSE_LENGTH] = {};
                 //This is effectively the implementation for the presence entity handler.
                 OC_LOG(DEBUG, TAG, PCF("This notification is for Presence"));
                 result = AddServerRequest(&request, 0, 0, 0, 1, OC_REST_GET,
@@ -184,15 +197,19 @@ OCStackResult SendAllObserverNotification (OCMethod method, OCResource *resPtr,
 
 OCStackResult SendListObserverNotification (OCResource * resource,
         OCObservationId  *obsIdList, uint8_t numberOfIds,
-        unsigned char *notificationJSONPayload, uint32_t maxAge,
+        const char *notificationJSONPayload, uint32_t maxAge,
         OCQualityOfService qos)
 {
+    if(!resource || !obsIdList || !notificationJSONPayload)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+
     uint8_t numIds = numberOfIds;
     ResourceObserver *observation = NULL;
     uint8_t numSentNotification = 0;
     OCServerRequest * request = NULL;
     OCStackResult result = OC_STACK_ERROR;
-    OCEntityHandlerResponse ehResponse = {0};
 
     OC_LOG(INFO, TAG, PCF("Entering SendListObserverNotification"));
     while(numIds)
@@ -218,16 +235,16 @@ OCStackResult SendListObserverNotification (OCResource * resource,
                     request->observeResult = OC_STACK_OK;
                     if(result == OC_STACK_OK)
                     {
-                        memset(&ehResponse, 0, sizeof(OCEntityHandlerResponse));
+                        OCEntityHandlerResponse ehResponse = {};
                         ehResponse.ehResult = OC_EH_OK;
-                        ehResponse.payload = (unsigned char *) OCMalloc(MAX_RESPONSE_LENGTH);
+                        ehResponse.payload = (char *) OCMalloc(MAX_RESPONSE_LENGTH);
                         if(!ehResponse.payload)
                         {
                             FindAndDeleteServerRequest(request);
                             continue;
                         }
-                        strcpy((char *)ehResponse.payload, (const char *)notificationJSONPayload);
-                        ehResponse.payloadSize = strlen((const char *)ehResponse.payload) + 1;
+                        strncpy(ehResponse.payload, notificationJSONPayload, MAX_RESPONSE_LENGTH-1);
+                        ehResponse.payloadSize = strlen(ehResponse.payload) + 1;
                         ehResponse.persistentBufferFlag = 0;
                         ehResponse.requestHandle = (OCRequestHandle) request;
                         ehResponse.resourceHandle = (OCResourceHandle) resource;
@@ -293,32 +310,37 @@ OCStackResult AddObserver (const char         *resUri,
                            CAToken_t          *token,
                            OCResource         *resHandle,
                            OCQualityOfService qos,
-                           CAAddress_t          *addressInfo,
+                           const CAAddress_t  *addressInfo,
                            CAConnectivityType_t connectivityType)
 {
     ResourceObserver *obsNode = NULL;
 
+    if(!resUri || !token || !*token)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+
     obsNode = (ResourceObserver *) OCCalloc(1, sizeof(ResourceObserver));
     if (obsNode)
     {
         obsNode->observeId = obsId;
 
-        obsNode->resUri = (unsigned char *)OCMalloc(strlen(resUri)+1);
+        obsNode->resUri = (char *)OCMalloc(strlen(resUri)+1);
         VERIFY_NON_NULL (obsNode->resUri);
         memcpy (obsNode->resUri, resUri, strlen(resUri)+1);
 
         obsNode->qos = qos;
         if(query)
         {
-            obsNode->query = (unsigned char *)OCMalloc(strlen(query)+1);
+            obsNode->query = (char *)OCMalloc(strlen(query)+1);
             VERIFY_NON_NULL (obsNode->query);
             memcpy (obsNode->query, query, strlen(query)+1);
         }
 
         obsNode->token = (CAToken_t)OCMalloc(CA_MAX_TOKEN_LEN+1);
         VERIFY_NON_NULL (obsNode->token);
-        memset(obsNode->token, 0, CA_MAX_TOKEN_LEN + 1);
         memcpy(obsNode->token, *token, CA_MAX_TOKEN_LEN);
+        obsNode->token[CA_MAX_TOKEN_LEN]='\0';
 
         obsNode->addressInfo = *addressInfo;
         obsNode->connectivityType = connectivityType;
@@ -359,7 +381,7 @@ ResourceObserver* GetObserverUsingToken (const CAToken_t * token)
 {
     ResourceObserver *out = NULL;
 
-    if(token)
+    if(token && *token)
     {
         LL_FOREACH (serverObsList, out)
         {
@@ -378,6 +400,11 @@ ResourceObserver* GetObserverUsingToken (const CAToken_t * token)
 
 OCStackResult DeleteObserverUsingToken (CAToken_t * token)
 {
+    if(!token || !*token)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+
     ResourceObserver *obsNode = NULL;
 
     obsNode = GetObserverUsingToken (token);
@@ -400,7 +427,10 @@ void DeleteObserverList()
     ResourceObserver *tmp = NULL;
     LL_FOREACH_SAFE (serverObsList, out, tmp)
     {
-        DeleteObserverUsingToken (&(out->token));
+        if(out)
+        {
+            DeleteObserverUsingToken (&(out->token));
+        }
     }
     serverObsList = NULL;
 }
@@ -411,6 +441,11 @@ CreateObserveHeaderOption (CAHeaderOption_t **caHdrOpt,
                            uint8_t numOptions,
                            uint8_t observeFlag)
 {
+    if(!caHdrOpt)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+
     CAHeaderOption_t *tmpHdrOpt = NULL;
 
     tmpHdrOpt = (CAHeaderOption_t *) OCMalloc ((numOptions+1)*sizeof(CAHeaderOption_t));
@@ -436,16 +471,24 @@ GetObserveHeaderOption (uint32_t * observationOption,
                         CAHeaderOption_t *options,
                         uint8_t * numOptions)
 {
+    if(!observationOption)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
     *observationOption = OC_OBSERVE_NO_OPTION;
-    uint8_t i = 0;
-    uint8_t c = 0;
-    for(i = 0; i < *numOptions; i++)
+
+    if(!options || !numOptions)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    for(uint8_t i = 0; i < *numOptions; i++)
     {
         if(options[i].protocolID == CA_COAP_ID &&
                 options[i].optionID == COAP_OPTION_OBSERVE)
         {
             *observationOption = options[i].optionData[0];
-            for(c = i; c < *numOptions-1; c++)
+            for(uint8_t c = i; c < *numOptions-1; c++)
             {
                 options[i].protocolID = options[i+1].protocolID;
                 options[i].optionID = options[i+1].optionID;
@@ -458,3 +501,4 @@ GetObserveHeaderOption (uint32_t * observationOption,
     }
     return OC_STACK_OK;
 }
+
index 1832397..bc440c8 100644 (file)
@@ -26,6 +26,7 @@
 #include "ocresourcehandler.h"
 #include "ocobserve.h"
 #include "occollection.h"
+#include "ocmalloc.h"
 #include "logger.h"
 #include "cJSON.h"
 
@@ -65,8 +66,8 @@ OCEntityHandlerResult defaultResourceEHandler(OCEntityHandlerFlag flag,
     return  OC_EH_OK; // Making sure that the Default EH and the Vendor EH have matching signatures
 }
 
-/* This method  will return the port at which the secure resource is hosted */
-static OCStackResult GetSecurePortInfo(CAConnectivityType_t connType, uint32_t *port)
+/* This method will retrieve the port at which the secure resource is hosted */
+static OCStackResult GetSecurePortInfo(CAConnectivityType_t connType, uint16_t *port)
 {
     CALocalConnectivity_t* info = NULL;
     uint32_t size = 0;
@@ -77,7 +78,7 @@ static OCStackResult GetSecurePortInfo(CAConnectivityType_t connType, uint32_t *
     {
         while (size--)
         {
-            if (info[size].isSecured == true && info[size].type == connType)
+            if (info[size].isSecured && info[size].type == connType)
             {
                 if (info[size].type == CA_ETHERNET ||
                     info[size].type == CA_WIFI)
@@ -90,54 +91,76 @@ static OCStackResult GetSecurePortInfo(CAConnectivityType_t connType, uint32_t *
         }
     }
 
-    free(info);
+    OCFree(info);
     return ret;
 }
 
-static OCStackResult ValidateUrlQuery (unsigned char *url, unsigned char *query,
+static OCStackResult ValidateUrlQuery (char *url, char *query,
                                 uint8_t *filterOn, char **filterValue)
 {
-    char *filterParam;
+    if(!filterOn || !filterValue)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    char *filterParam = NULL;
 
     OC_LOG(INFO, TAG, PCF("Entering ValidateUrlQuery"));
     if (!url)
+    {
         return OC_STACK_INVALID_URI;
+    }
 
     if (strcmp ((char *)url, GetVirtualResourceUri(OC_WELL_KNOWN_URI)) == 0 ||
-                strcmp ((char *)url, GetVirtualResourceUri(OC_DEVICE_URI)) == 0) {
+                strcmp ((char *)url, GetVirtualResourceUri(OC_DEVICE_URI)) == 0)
+    {
         *filterOn = STACK_RES_DISCOVERY_NOFILTER;
-        if (query && *query) {
-            char* strTokPtr;
+        if (query && *query)
+        {
+            char* strTokPtr = NULL;
             filterParam = strtok_r((char *)query, "=", &strTokPtr);
             *filterValue = strtok_r(NULL, " ", &strTokPtr);
-            if (!(*filterValue)) {
+            if (!(*filterValue))
+            {
                 return OC_STACK_INVALID_QUERY;
-            } else if (strcmp (filterParam, OC_RSRVD_INTERFACE) == 0) {
+            }
+            else if (strcmp (filterParam, OC_RSRVD_INTERFACE) == 0)
+            {
                 // Resource discovery with interface filter
                 *filterOn = STACK_RES_DISCOVERY_IF_FILTER;
-            } else if (strcmp (filterParam, OC_RSRVD_RESOURCE_TYPE) == 0) {
+            }
+            else if (strcmp (filterParam, OC_RSRVD_RESOURCE_TYPE) == 0)
+            {
                 // Resource discovery with resource type filter
                 *filterOn = STACK_RES_DISCOVERY_RT_FILTER;
-            } else if (strcmp (filterParam, OC_RSRVD_DEVICE_ID) == 0) {
+            }
+            else if (strcmp (filterParam, OC_RSRVD_DEVICE_ID) == 0)
+            {
                 //Device ID filter
                 *filterOn = STACK_DEVICE_DISCOVERY_DI_FILTER;
-            } else if (strcmp (filterParam, OC_RSRVD_DEVICE_NAME) == 0) {
+            }
+            else if (strcmp (filterParam, OC_RSRVD_DEVICE_NAME) == 0)
+            {
                 //Device Name filter
                 *filterOn = STACK_DEVICE_DISCOVERY_DN_FILTER;
-            } else {
+            }
+            else
+            {
                 // Other filter types not supported
                 return OC_STACK_INVALID_QUERY;
             }
         }
     }
     #ifdef WITH_PRESENCE
-    else if (strcmp((char *)url, GetVirtualResourceUri(OC_PRESENCE)) == 0) {
+    else if (strcmp((char *)url, GetVirtualResourceUri(OC_PRESENCE)) == 0)
+    {
         //Nothing needs to be done, except for pass a OC_PRESENCE query through as OC_STACK_OK.
         OC_LOG(INFO, TAG, PCF("OC_PRESENCE Request"));
         *filterOn = STACK_RES_DISCOVERY_NOFILTER;
     }
     #endif
-    else {
+    else
+    {
         // Other URIs not yet supported
         return OC_STACK_INVALID_URI;
     }
@@ -151,13 +174,20 @@ BuildVirtualResourceResponse(OCResource *resourcePtr, uint8_t filterOn,
                         char *filterValue, char * out, uint16_t *remaining,
                         CAConnectivityType_t connType )
 {
-    OCResourceType *resourceTypePtr;
-    OCResourceInterface *interfacePtr;
-    cJSON *resObj, *propObj, *rtArray;
-    char *jsonStr;
+    if(!resourcePtr || !out  || !remaining)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    OCResourceType *resourceTypePtr = NULL;
+    OCResourceInterface *interfacePtr = NULL;
+    cJSON *resObj = NULL;
+    cJSON *propObj = NULL;
+    cJSON *rtArray = NULL;
+    char *jsonStr = NULL;
     uint8_t encodeRes = 0;
     OCStackResult ret = OC_STACK_OK;
-    uint16_t jsonLen;
+    uint16_t jsonLen = 0;
 
     OC_LOG(INFO, TAG, PCF("Entering BuildVirtualResourceResponse"));
     resObj = cJSON_CreateObject();
@@ -165,47 +195,58 @@ BuildVirtualResourceResponse(OCResource *resourcePtr, uint8_t filterOn,
     if (resourcePtr)
     {
         encodeRes = 0;
-        if (filterOn == STACK_RES_DISCOVERY_RT_FILTER) {
+        if (filterOn == STACK_RES_DISCOVERY_RT_FILTER)
+        {
             resourceTypePtr = resourcePtr->rsrcType;
-            while (resourceTypePtr) {
-                if (strcmp (resourceTypePtr->resourcetypename, filterValue) == 0) {
+            while (resourceTypePtr)
+            {
+                if (strcmp (resourceTypePtr->resourcetypename, filterValue) == 0)
+                {
                     encodeRes = 1;
                     break;
                 }
                 resourceTypePtr = resourceTypePtr->next;
             }
-        } else if (filterOn == STACK_RES_DISCOVERY_IF_FILTER) {
+        }
+        else if (filterOn == STACK_RES_DISCOVERY_IF_FILTER)
+        {
             interfacePtr = resourcePtr->rsrcInterface;
-            while (interfacePtr) {
-                if (strcmp (interfacePtr->name, filterValue) == 0) {
+            while (interfacePtr)
+            {
+                if (strcmp (interfacePtr->name, filterValue) == 0)
+                {
                     encodeRes = 1;
                     break;
                 }
                 interfacePtr = interfacePtr->next;
             }
-        } else if (filterOn == STACK_RES_DISCOVERY_NOFILTER) {
+        }
+        else if (filterOn == STACK_RES_DISCOVERY_NOFILTER)
+        {
             encodeRes = 1;
-        } else {
+        }
+        else
+        {
             //TODO: Unsupported query filter
             return OC_STACK_INVALID_QUERY;
         }
 
-        if (encodeRes) {
+        if (encodeRes)
+        {
             // Add URIs
             cJSON_AddItemToObject (resObj, OC_RSRVD_HREF, cJSON_CreateString(resourcePtr->uri));
 
             // Add server instance id
-            const char* serverInstanceId = OCGetServerInstanceIDString();
             cJSON_AddItemToObject (resObj,
                                    OC_RSRVD_SERVER_INSTANCE_ID,
-                                   cJSON_CreateString(serverInstanceId));
-            serverInstanceId = NULL;
+                                   cJSON_CreateString(OCGetServerInstanceIDString()));
 
             cJSON_AddItemToObject (resObj, "prop", propObj = cJSON_CreateObject());
             // Add resource types
             cJSON_AddItemToObject (propObj, OC_RSRVD_RESOURCE_TYPE, rtArray = cJSON_CreateArray());
             resourceTypePtr = resourcePtr->rsrcType;
-            while (resourceTypePtr) {
+            while (resourceTypePtr)
+            {
                 cJSON_AddItemToArray (rtArray,
                                       cJSON_CreateString(resourceTypePtr->resourcetypename));
                 resourceTypePtr = resourceTypePtr->next;
@@ -213,22 +254,26 @@ BuildVirtualResourceResponse(OCResource *resourcePtr, uint8_t filterOn,
             // Add interface types
             cJSON_AddItemToObject (propObj, OC_RSRVD_INTERFACE, rtArray = cJSON_CreateArray());
             interfacePtr = resourcePtr->rsrcInterface;
-            while (interfacePtr) {
+            while (interfacePtr)
+            {
                 cJSON_AddItemToArray (rtArray, cJSON_CreateString(interfacePtr->name));
                 interfacePtr = interfacePtr->next;
             }
             // If resource is observable, set observability flag.
             // Resources that are not observable will not have the flag.
-            if (resourcePtr->resourceProperties & OC_OBSERVABLE) {
+            if (resourcePtr->resourceProperties & OC_OBSERVABLE)
+            {
                 cJSON_AddItemToObject (propObj, OC_RSRVD_OBSERVABLE,
                                        cJSON_CreateNumber(OC_RESOURCE_OBSERVABLE));
             }
             // Set secure flag for secure resources
-            if (resourcePtr->resourceProperties & OC_SECURE) {
+            if (resourcePtr->resourceProperties & OC_SECURE)
+            {
                 cJSON_AddNumberToObject (propObj, OC_RSRVD_SECURE, OC_RESOURCE_SECURE);
                 //Set the IP port also as secure resources are hosted on a different port
-                uint32_t port;
-                if (GetSecurePortInfo (connType, &port) == OC_STACK_OK) {
+                uint16_t port = 0;
+                if (GetSecurePortInfo (connType, &port) == OC_STACK_OK)
+                {
                     cJSON_AddNumberToObject (propObj, OC_RSRVD_HOSTING_PORT, port);
                 }
             }
@@ -248,7 +293,7 @@ BuildVirtualResourceResponse(OCResource *resourcePtr, uint8_t filterOn,
         ret = OC_STACK_ERROR;
     }
     cJSON_Delete (resObj);
-    free (jsonStr);
+    OCFree (jsonStr);
 
     OC_LOG(INFO, TAG, PCF("Exiting BuildVirtualResourceResponse"));
     return ret;
@@ -257,6 +302,11 @@ BuildVirtualResourceResponse(OCResource *resourcePtr, uint8_t filterOn,
 OCStackResult BuildVirtualResourceResponseForDevice(uint8_t filterOn, char *filterValue,
                                                     char *out, uint16_t *remaining)
 {
+    if(!out || !remaining)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+
     OCStackResult ret = OC_STACK_ERROR;
 
     if (savedDeviceInfo != NULL)
@@ -269,16 +319,18 @@ OCStackResult BuildVirtualResourceResponseForDevice(uint8_t filterOn, char *filt
 
         if (filterOn == STACK_DEVICE_DISCOVERY_DI_FILTER)
         {
-            if((cJSON_GetObjectItem(repObj,"di") != NULL) &&
-                    strcmp(cJSON_GetObjectItem(repObj,"di")->valuestring, filterValue) == 0)
+            if((cJSON_GetObjectItem(repObj,OC_RSRVD_DEVICE_ID) != NULL) &&
+                    strcmp(cJSON_GetObjectItem(repObj,OC_RSRVD_DEVICE_ID)->valuestring, filterValue)
+                    == 0)
             {
                 ret = OC_STACK_OK;
             }
         }
         else if (filterOn == STACK_DEVICE_DISCOVERY_DN_FILTER)
         {
-            if((cJSON_GetObjectItem(repObj,"dn") != NULL) &&
-                    strcmp(cJSON_GetObjectItem(repObj,"dn")->valuestring, filterValue) == 0)
+            if((cJSON_GetObjectItem(repObj,OC_RSRVD_DEVICE_NAME) != NULL) &&
+                    strcmp(cJSON_GetObjectItem(repObj,OC_RSRVD_DEVICE_NAME)->valuestring,
+                        filterValue) == 0)
             {
                 ret = OC_STACK_OK;
             }
@@ -311,7 +363,7 @@ OCStackResult BuildVirtualResourceResponseForDevice(uint8_t filterOn, char *filt
                     ret = OC_STACK_ERROR;
                 }
 
-                free(jsonStr);
+                OCFree(jsonStr);
             }
             else
             {
@@ -333,7 +385,6 @@ OCStackResult BuildVirtualResourceResponseForDevice(uint8_t filterOn, char *filt
     return ret;
 }
 
-//TODO ("Does it make sense to make this method as inline")
 const char * GetVirtualResourceUri( OCVirtualResources resource)
 {
     if (resource < OC_MAX_VIRTUAL_RESOURCES)
@@ -346,6 +397,11 @@ const char * GetVirtualResourceUri( OCVirtualResources resource)
 
 uint8_t IsVirtualResource(const char* resourceUri)
 {
+    if(!resourceUri)
+    {
+        return 0;
+    }
+
     for (int i = 0; i < OC_MAX_VIRTUAL_RESOURCES; i++)
     {
         if (strcmp(resourceUri, GetVirtualResourceUri((OCVirtualResources)i)) == 0)
@@ -358,6 +414,11 @@ uint8_t IsVirtualResource(const char* resourceUri)
 
 uint8_t IsCollectionResource (OCResource *resource)
 {
+    if(!resource)
+    {
+        return 0;
+    }
+
     for (int i = 0; i < MAX_CONTAINED_RESOURCES; i++)
     {
         if (resource->rsrcResources[i])
@@ -370,6 +431,11 @@ uint8_t IsCollectionResource (OCResource *resource)
 
 OCResource *FindResourceByUri(const char* resourceUri)
 {
+    if(!resourceUri)
+    {
+        return NULL;
+    }
+
     OCResource * pointer = headResource;
     while (pointer) {
         if (strcmp(resourceUri, pointer->uri) == 0) {
@@ -386,6 +452,10 @@ OCStackResult DetermineResourceHandling (OCServerRequest *request,
                                          ResourceHandling *handling,
                                          OCResource **resource)
 {
+    if(!request || !handling || !resource)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
 
     OC_LOG(INFO, TAG, PCF("Entering DetermineResourceHandling"));
 
@@ -400,7 +470,7 @@ OCStackResult DetermineResourceHandling (OCServerRequest *request,
     {
         // Resource URL not specified
         *handling = OC_RESOURCE_NOT_SPECIFIED;
-        return OC_STACK_OK;
+        return OC_STACK_NO_RESOURCE;
     }
     else
     {
@@ -424,7 +494,7 @@ OCStackResult DetermineResourceHandling (OCServerRequest *request,
         // secure resource will entertain only authorized requests
         if ((resourcePtr->resourceProperties & OC_SECURE) && (request->secured == 0))
         {
-            OC_LOG(INFO, TAG, PCF("Un-authorized request. Ignore it!"));
+            OC_LOG(ERROR, TAG, PCF("Un-authorized request. Ignoring"));
             return OC_STACK_RESOURCE_ERROR;
         }
 
@@ -435,17 +505,23 @@ OCStackResult DetermineResourceHandling (OCServerRequest *request,
             {
                 *handling = OC_RESOURCE_COLLECTION_WITH_ENTITYHANDLER;
                 return OC_STACK_OK;
-            } else {
+            }
+            else
+            {
                 *handling = OC_RESOURCE_COLLECTION_DEFAULT_ENTITYHANDLER;
                 return OC_STACK_OK;
             }
-        } else {
+        }
+        else
+        {
             // Resource not a collection
             if (resourcePtr->entityHandler != defaultResourceEHandler)
             {
                 *handling = OC_RESOURCE_NOT_COLLECTION_WITH_ENTITYHANDLER;
                 return OC_STACK_OK;
-            } else {
+            }
+            else
+            {
                 *handling = OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER;
                 return OC_STACK_OK;
             }
@@ -487,13 +563,18 @@ OCStackResult EntityHandlerCodeToOCStackCode(OCEntityHandlerResult ehResult)
 static OCStackResult
 HandleVirtualResource (OCServerRequest *request, OCResource* resource)
 {
+    if(!request || !resource)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+
     OCStackResult result = OC_STACK_ERROR;
     char *filterValue = NULL;
     uint8_t filterOn = 0;
     uint16_t remaining = 0;
-    unsigned char * ptr = NULL;
+    char * ptr = NULL;
     uint8_t firstLoopDone = 0;
-    unsigned char discoveryResBuf[MAX_RESPONSE_LENGTH] = {0};
+    char discoveryResBuf[MAX_RESPONSE_LENGTH] = {};
 
     OC_LOG(INFO, TAG, PCF("Entering HandleVirtualResource"));
 
@@ -545,7 +626,7 @@ HandleVirtualResource (OCServerRequest *request, OCResource* resource)
 
             if(strlen((const char *)discoveryResBuf) > 0)
             {
-                OCEntityHandlerResponse response = {0};
+                OCEntityHandlerResponse response = {};
 
                 response.ehResult = OC_EH_OK;
                 response.payload = discoveryResBuf;
@@ -600,15 +681,21 @@ HandleVirtualResource (OCServerRequest *request, OCResource* resource)
 static OCStackResult
 HandleDefaultDeviceEntityHandler (OCServerRequest *request)
 {
+    if(!request)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+
     OCStackResult result = OC_STACK_OK;
     OCEntityHandlerResult ehResult = OC_EH_ERROR;
-    OCEntityHandlerRequest ehRequest = {0};
+    OCEntityHandlerRequest ehRequest = {};
 
     OC_LOG(INFO, TAG, PCF("Entering HandleResourceWithDefaultDeviceEntityHandler"));
     result = FormOCEntityHandlerRequest(&ehRequest, (OCRequestHandle) request,
             request->method, (OCResourceHandle) NULL, request->query,
             request->reqJSONPayload, request->numRcvdVendorSpecificHeaderOptions,
-            request->rcvdVendorSpecificHeaderOptions, (OCObserveAction)request->observationOption, (OCObservationId)0);
+            request->rcvdVendorSpecificHeaderOptions,
+            (OCObserveAction)request->observationOption, (OCObservationId)0);
     VERIFY_SUCCESS(result, OC_STACK_OK);
 
     // At this point we know for sure that defaultDeviceHandler exists
@@ -633,12 +720,17 @@ HandleResourceWithEntityHandler (OCServerRequest *request,
                                  OCResource *resource,
                                  uint8_t collectionResource)
 {
+    if(!request || ! resource)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+
     OCStackResult result = OC_STACK_ERROR;
     OCEntityHandlerResult ehResult = OC_EH_ERROR;
     OCEntityHandlerFlag ehFlag = OC_REQUEST_FLAG;
     ResourceObserver *resObs = NULL;
 
-    OCEntityHandlerRequest ehRequest = {0};
+    OCEntityHandlerRequest ehRequest = {};
 
     OC_LOG(INFO, TAG, PCF("Entering HandleResourceWithEntityHandler"));
     result = FormOCEntityHandlerRequest(&ehRequest, (OCRequestHandle) request,
@@ -666,7 +758,7 @@ HandleResourceWithEntityHandler (OCServerRequest *request,
                 &request->addressInfo, request->connectivityType);
         if(result == OC_STACK_OK)
         {
-            OC_LOG(DEBUG, TAG, PCF("Added observer successfully"));
+            OC_LOG(INFO, TAG, PCF("Added observer successfully"));
             request->observeResult = OC_STACK_OK;
             ehFlag = (OCEntityHandlerFlag)(OC_REQUEST_FLAG | OC_OBSERVE_FLAG);
         }
@@ -674,7 +766,7 @@ HandleResourceWithEntityHandler (OCServerRequest *request,
         {
             result = OC_STACK_OK;
             request->observeResult = OC_STACK_ERROR;
-            OC_LOG(DEBUG, TAG, PCF("Observer Addition failed"));
+            OC_LOG(ERROR, TAG, PCF("Observer Addition failed"));
             ehFlag = OC_REQUEST_FLAG;
         }
 
@@ -700,14 +792,14 @@ HandleResourceWithEntityHandler (OCServerRequest *request,
 
         if(result == OC_STACK_OK)
         {
-            OC_LOG(DEBUG, TAG, PCF("Removed observer successfully"));
+            OC_LOG(INFO, TAG, PCF("Removed observer successfully"));
             request->observeResult = OC_STACK_OK;
         }
         else
         {
             result = OC_STACK_OK;
             request->observeResult = OC_STACK_ERROR;
-            OC_LOG(DEBUG, TAG, PCF("Observer Removal failed"));
+            OC_LOG(ERROR, TAG, PCF("Observer Removal failed"));
         }
     }
     else
@@ -735,8 +827,13 @@ static OCStackResult
 HandleCollectionResourceDefaultEntityHandler (OCServerRequest *request,
                                               OCResource *resource)
 {
+    if(!request || !resource)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+
     OCStackResult result = OC_STACK_ERROR;
-    OCEntityHandlerRequest ehRequest = {0};
+    OCEntityHandlerRequest ehRequest = {};
 
     result = FormOCEntityHandlerRequest(&ehRequest, (OCRequestHandle) request,
             request->method, (OCResourceHandle) resource, request->query,
@@ -820,41 +917,42 @@ OCStackResult SaveDeviceInfo(OCDeviceInfo deviceInfo)
     cJSON_AddItemToObject (savedDeviceInfo, OC_RSRVD_HREF,
             cJSON_CreateString(GetVirtualResourceUri(OC_DEVICE_URI)));
 
-    cJSON_AddItemToObject (savedDeviceInfo, "rep", repObj = cJSON_CreateObject());
+    cJSON_AddItemToObject (savedDeviceInfo, OC_RSRVD_REPRESENTATION, repObj = cJSON_CreateObject());
 
     if (deviceInfo.contentType)
     {
-        cJSON_AddItemToObject (repObj, "ct",
+        cJSON_AddItemToObject (repObj, OC_RSRVD_CONTENT_TYPE,
                 cJSON_CreateString(deviceInfo.contentType));
     }
 
     if (deviceInfo.dateOfManufacture)
     {
-        cJSON_AddItemToObject (repObj, "mndt",
+        cJSON_AddItemToObject (repObj, OC_RSRVD_MFG_DATE,
                 cJSON_CreateString(deviceInfo.dateOfManufacture));
     }
 
     if (deviceInfo.deviceName)
     {
-        cJSON_AddItemToObject (repObj, "dn",
+        cJSON_AddItemToObject (repObj, OC_RSRVD_DEVICE_NAME,
                 cJSON_CreateString(deviceInfo.deviceName));
     }
 
     if (deviceInfo.deviceUUID)
     {
-        cJSON_AddItemToObject (repObj, "di",
+        cJSON_AddItemToObject (repObj, OC_RSRVD_DEVICE_ID,
                 cJSON_CreateString(deviceInfo.deviceUUID));
     }
 
     if (deviceInfo.firmwareVersion)
     {
-        cJSON_AddItemToObject (repObj, "mnfv",
+        cJSON_AddItemToObject (repObj, OC_RSRVD_FW_VERSION,
                 cJSON_CreateString(deviceInfo.firmwareVersion));
     }
 
     if (deviceInfo.hostName)
     {
-        cJSON_AddItemToObject (repObj, "hn", cJSON_CreateString(deviceInfo.hostName));
+        cJSON_AddItemToObject (repObj, OC_RSRVD_HOST_NAME,
+                cJSON_CreateString(deviceInfo.hostName));
     }
 
     if (deviceInfo.manufacturerName)
@@ -865,7 +963,7 @@ OCStackResult SaveDeviceInfo(OCDeviceInfo deviceInfo)
             return OC_STACK_INVALID_PARAM;
         }
 
-        cJSON_AddItemToObject (repObj, "mnmn",
+        cJSON_AddItemToObject (repObj, OC_RSRVD_MFG_NAME,
                 cJSON_CreateString(deviceInfo.manufacturerName));
     }
 
@@ -877,34 +975,35 @@ OCStackResult SaveDeviceInfo(OCDeviceInfo deviceInfo)
             return OC_STACK_INVALID_PARAM;
         }
 
-        cJSON_AddItemToObject (repObj, "mnml",
+        cJSON_AddItemToObject (repObj, OC_RSRVD_MFG_URL,
                 cJSON_CreateString(deviceInfo.manufacturerUrl));
     }
 
     if (deviceInfo.modelNumber)
     {
-        cJSON_AddItemToObject (repObj, "mnmo",
+        cJSON_AddItemToObject (repObj, OC_RSRVD_MODEL_NUM,
                 cJSON_CreateString(deviceInfo.modelNumber));
     }
 
     if (deviceInfo.platformVersion)
     {
-        cJSON_AddItemToObject (repObj, "mnpv",
+        cJSON_AddItemToObject (repObj, OC_RSRVD_PLATFORM_VERSION,
                 cJSON_CreateString(deviceInfo.platformVersion));
     }
 
     if (deviceInfo.supportUrl)
     {
-        cJSON_AddItemToObject (repObj, "mnsl",
+        cJSON_AddItemToObject (repObj, OC_RSRVD_SUPPORT_URL,
                 cJSON_CreateString(deviceInfo.supportUrl));
     }
 
     if (deviceInfo.version)
     {
-        cJSON_AddItemToObject (repObj, "icv",
+        cJSON_AddItemToObject (repObj, OC_RSRVD_VERSION,
                 cJSON_CreateString(deviceInfo.version));
     }
 
     return OC_STACK_OK;
 }
 
+
index 5574826..8abdf51 100644 (file)
@@ -40,6 +40,12 @@ static struct OCServerResponse * serverResponseList = NULL;
 
 OCServerRequest * GetServerRequestUsingToken (const CAToken_t token)
 {
+    if(!token)
+    {
+        OC_LOG(ERROR, TAG, PCF("Invalid Parameter Token"));
+        return NULL;
+    }
+
     OCServerRequest * out = NULL;
     LL_FOREACH (serverRequestList, out)
     {
@@ -51,7 +57,7 @@ OCServerRequest * GetServerRequestUsingToken (const CAToken_t token)
             return out;
         }
     }
-    OC_LOG(INFO, TAG, PCF("Server Request not found!!"));
+    OC_LOG(ERROR, TAG, PCF("Server Request not found!!"));
     return NULL;
 }
 
@@ -65,7 +71,7 @@ OCServerRequest * GetServerRequestUsingHandle (const OCServerRequest * handle)
             return out;
         }
     }
-    OC_LOG(INFO, TAG, PCF("Server Request not found!!"));
+    OC_LOG(ERROR, TAG, PCF("Server Request not found!!"));
     return NULL;
 }
 
@@ -79,17 +85,17 @@ OCServerResponse * GetServerResponseUsingHandle (const OCServerRequest * handle)
             return out;
         }
     }
-    OC_LOG(INFO, TAG, PCF("Server Response not found!!"));
+    OC_LOG(ERROR, TAG, PCF("Server Response not found!!"));
     return NULL;
 }
 
 OCStackResult AddServerRequest (OCServerRequest ** request, uint16_t coapID,
         uint8_t delayedResNeeded, uint8_t secured, uint8_t notificationFlag, OCMethod method,
         uint8_t numRcvdVendorSpecificHeaderOptions, uint32_t observationOption,
-        OCQualityOfService qos, unsigned char * query,
+        OCQualityOfService qos, char * query,
         OCHeaderOption * rcvdVendorSpecificHeaderOptions,
-        unsigned char * reqJSONPayload, CAToken_t * requestToken,
-        unsigned char * resourceUrl, size_t reqTotalSize,
+        char * reqJSONPayload, CAToken_t * requestToken,
+        char * resourceUrl, size_t reqTotalSize,
         CAAddress_t *addressInfo, CAConnectivityType_t connectivityType)
 {
     OCServerRequest * serverRequest = NULL;
@@ -136,8 +142,8 @@ OCStackResult AddServerRequest (OCServerRequest ** request, uint16_t coapID,
     {
         serverRequest->requestToken = (CAToken_t)OCMalloc(CA_MAX_TOKEN_LEN+1);
         VERIFY_NON_NULL (serverRequest->requestToken);
-        memset(serverRequest->requestToken, 0, CA_MAX_TOKEN_LEN + 1);
         memcpy(serverRequest->requestToken, *requestToken, CA_MAX_TOKEN_LEN);
+        serverRequest->requestToken[CA_MAX_TOKEN_LEN]='\0';
     }
 
     if(resourceUrl)
@@ -174,9 +180,8 @@ OCStackResult AddServerResponse (OCServerResponse ** response, OCRequestHandle r
     serverResponse = (OCServerResponse *) OCCalloc(1, sizeof(OCServerResponse));
     VERIFY_NON_NULL(serverResponse);
 
-    serverResponse->payload = (unsigned char *) OCMalloc(MAX_RESPONSE_LENGTH);
+    serverResponse->payload = (char *) OCCalloc(1, MAX_RESPONSE_LENGTH);
     VERIFY_NON_NULL(serverResponse->payload);
-    memset(serverResponse->payload, 0, MAX_RESPONSE_LENGTH);
 
     serverResponse->remainingPayloadSize = MAX_RESPONSE_LENGTH;
     serverResponse->requestHandle = requestHandle;
@@ -202,8 +207,8 @@ OCStackResult FormOCEntityHandlerRequest(
         OCRequestHandle request,
         OCMethod method,
         OCResourceHandle resource,
-        unsigned char * queryBuf,
-        unsigned char * bufReqPayload,
+        char * queryBuf,
+        char * bufReqPayload,
         uint8_t numVendorOptions,
         OCHeaderOption * vendorOptions,
         OCObserveAction observeAction,
@@ -342,13 +347,12 @@ OCStackResult HandleSingleResponse(OCEntityHandlerResponse * ehResponse)
             break;
     }
 
-    responseInfo.info.token = (CAToken_t)OCMalloc(CA_MAX_TOKEN_LEN+1);
+    responseInfo.info.token = (CAToken_t)OCCalloc(1, CA_MAX_TOKEN_LEN+1);
     if (!responseInfo.info.token)
     {
         OC_LOG(FATAL, TAG, "Response Info Token is NULL");
         return result;
     }
-    memset(responseInfo.info.token, 0, CA_MAX_TOKEN_LEN + 1);
     memcpy(responseInfo.info.token, serverRequest->requestToken, CA_MAX_TOKEN_LEN);
 
     if(serverRequest->observeResult == OC_STACK_OK)
@@ -361,15 +365,10 @@ OCStackResult HandleSingleResponse(OCEntityHandlerResponse * ehResponse)
     }
 
     responseInfo.info.options = (CAHeaderOption_t *)
-                                    malloc(sizeof(CAHeaderOption_t) * responseInfo.info.numOptions);
+                                  OCMalloc(sizeof(CAHeaderOption_t) * responseInfo.info.numOptions);
 
     optionsPointer = responseInfo.info.options;
 
-    if(serverRequest->observeResult == OC_STACK_OK)
-    {
-        responseInfo.info.numOptions = ehResponse->numSendVendorSpecificHeaderOptions + 1;
-    }
-
     // TODO: This exposes CoAP specific details.  At some point, this should be
     // re-factored and handled in the CA layer.
     if(serverRequest->observeResult == OC_STACK_OK)
@@ -457,6 +456,12 @@ OCStackResult HandleAggregateResponse(OCEntityHandlerResponse * ehResponse)
     OCServerResponse * serverResponse = NULL;
     uint16_t bufferNeeded = 0;
 
+    if(!ehResponse || !ehResponse->payload)
+    {
+        OC_LOG(ERROR, TAG, PCF("HandleAggregateResponse invalid parameters"));
+        return OC_STACK_INVALID_PARAM;
+    }
+
     OC_LOG_V(INFO, TAG, "Inside HandleAggregateResponse: %s", ehResponse->payload);
 
     serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
@@ -486,7 +491,7 @@ OCStackResult HandleAggregateResponse(OCEntityHandlerResponse * ehResponse)
         }
         if(serverResponse->remainingPayloadSize >= bufferNeeded)
         {
-            OC_LOG(INFO, TAG, PCF("There is room in response buffer"));
+            OC_LOG(ERROR, TAG, PCF("There is room in response buffer"));
             // append
             strncat((char *)serverResponse->payload,
                     (char *)ehResponse->payload,
@@ -517,7 +522,7 @@ OCStackResult HandleAggregateResponse(OCEntityHandlerResponse * ehResponse)
         }
         else
         {
-            OC_LOG(INFO, TAG, PCF("No room in response buffer"));
+            OC_LOG(ERROR, TAG, PCF("No room in response buffer"));
             //Delete the request and response
             FindAndDeleteServerRequest(serverRequest);
             FindAndDeleteServerResponse(serverResponse);
@@ -527,3 +532,4 @@ OCStackResult HandleAggregateResponse(OCEntityHandlerResponse * ehResponse)
 exit:
     return stackRet;
 }
+
index c0eaf2c..47eafdd 100644 (file)
@@ -78,9 +78,9 @@ static uint8_t PresenceTimeOutSize = 0;
 static uint32_t PresenceTimeOut[] = {50, 75, 85, 95, 100};
 #endif
 
-OCMode myStackMode;
+static OCMode myStackMode;
 OCDeviceEntityHandler defaultDeviceHandler;
-OCStackResult getQueryFromUri(const char * uri, unsigned char** resourceType, char ** newURI);
+OCStackResult getQueryFromUri(const char * uri, char** resourceType, char ** newURI);
 
 //-----------------------------------------------------------------------------
 // Macros
@@ -109,11 +109,11 @@ static uint32_t GetTime(float afterSeconds)
 static OCStackResult FormOCResponse(OCResponse * * responseLoc,
                                     ClientCB * cbNode,
                                     uint32_t maxAge,
-                                    unsigned char * fullUri,
-                                    unsigned char * rcvdUri,
+                                    char * fullUri,
+                                    char * rcvdUri,
                                     CAToken_t * rcvdToken,
                                     OCClientResponse * clientResponse,
-                                    unsigned char * bufRes)
+                                    char * bufRes)
 {
     OCResponse * response = (OCResponse *) OCMalloc(sizeof(OCResponse));
     if (!response)
@@ -135,12 +135,12 @@ static OCStackResult FormOCResponse(OCResponse * * responseLoc,
 /// This method is used to create the IPv4 dev_addr structure.
 /// TODO: Remove in future. Temporary helper function.
 /// Builds a socket interface address using IP address and port number
-static int32_t OCBuildIPv4Address(uint8_t a, uint8_t b, uint8_t c, uint8_t d,
+static OCStackResult OCBuildIPv4Address(uint8_t a, uint8_t b, uint8_t c, uint8_t d,
         uint16_t port, OCDevAddr *ipAddr)
 {
     if ( !ipAddr ) {
-        OC_LOG(FATAL, TAG, "Invalid argument");
-        return 1;
+        OC_LOG(FATAL, TAG, PCF("Invalid argument"));
+        return OC_STACK_INVALID_PARAM;
     }
 
     ipAddr->addr[0] = a;
@@ -149,7 +149,7 @@ static int32_t OCBuildIPv4Address(uint8_t a, uint8_t b, uint8_t c, uint8_t d,
     ipAddr->addr[3] = d;
     *((uint16_t*)&(ipAddr->addr[4])) = port;
 
-    return 0;
+    return OC_STACK_OK;
 }
 
 //-----------------------------------------------------------------------------
@@ -162,7 +162,7 @@ OCStackResult OCStackFeedBack(CAToken_t * token, uint8_t status)
 {
     OCStackResult result = OC_STACK_ERROR;
     ResourceObserver * observer = NULL;
-    OCEntityHandlerRequest ehRequest = {0};
+    OCEntityHandlerRequest ehRequest = {};
 
     switch(status)
     {
@@ -342,7 +342,7 @@ OCStackResult CAToOCConnectivityType(CAConnectivityType_t caConType, OCConnectiv
 OCStackResult UpdateResponseAddr(OCClientResponse *response, const CARemoteEndpoint_t* endPoint)
 {
     OCStackResult ret = OC_STACK_ERROR;
-    static OCDevAddr address = {0};
+    static OCDevAddr address = {};
     char * tok = NULL;
     char * savePtr = NULL;
     char * cpAddress = (char *) OCMalloc(strlen(endPoint->addressInfo.IP.ipAddress) + 1);
@@ -386,7 +386,7 @@ exit:
 void parsePresencePayload(char* payload, uint32_t* seqNum, uint32_t* maxAge, char** resType)
 {
     char * tok = NULL;
-    char * savePtr;
+    char * savePtr = NULL;
     // The format of the payload is {"oc":[%u:%u:%s]}
     // %u : sequence number,
     // %u : max age
@@ -410,7 +410,7 @@ void parsePresencePayload(char* payload, uint32_t* seqNum, uint32_t* maxAge, cha
         }
         payload[strlen((char *)payload)] = ':';
         strcpy(*resType, tok);
-        OC_LOG_V(DEBUG, TAG, "----------------resourceTypeName %s", *resType);
+        OC_LOG_V(DEBUG, TAG, "resourceTypeName %s", *resType);
     }
     payload[strlen((char *)payload)] = ']';
 }
@@ -447,7 +447,8 @@ OCStackResult HandlePresenceResponse(const CARemoteEndpoint_t* endPoint,
         goto exit;
     }
 
-    ipAddress = (char *) OCMalloc(strlen(endPoint->addressInfo.IP.ipAddress) + 1);
+    size_t addressLen = strlen(endPoint->addressInfo.IP.ipAddress);
+    ipAddress = (char *) OCMalloc(addressLen + 1);
 
     if(NULL == ipAddress)
     {
@@ -456,14 +457,13 @@ OCStackResult HandlePresenceResponse(const CARemoteEndpoint_t* endPoint,
         goto exit;
     }
 
-    strncpy(ipAddress, endPoint->addressInfo.IP.ipAddress,
-                            strlen(endPoint->addressInfo.IP.ipAddress));
-    ipAddress[strlen(endPoint->addressInfo.IP.ipAddress)] = '\0';
+    strncpy(ipAddress, endPoint->addressInfo.IP.ipAddress, addressLen);
+    ipAddress[addressLen] = '\0';
 
     snprintf(fullUri, MAX_URI_LENGTH, "coap://%s:%u%s", ipAddress, endPoint->addressInfo.IP.port,
                 OC_PRESENCE_URI);
 
-    cbNode = GetClientCB(NULL, NULL, (unsigned char *) fullUri);
+    cbNode = GetClientCB(NULL, NULL, fullUri);
 
     if(cbNode)
     {
@@ -472,7 +472,7 @@ OCStackResult HandlePresenceResponse(const CARemoteEndpoint_t* endPoint,
     else
     {
         snprintf(fullUri, MAX_URI_LENGTH, "%s%s", OC_MULTICAST_IP, endPoint->resourceUri);
-        cbNode = GetClientCB(NULL, NULL, (unsigned char *) fullUri);
+        cbNode = GetClientCB(NULL, NULL, fullUri);
         if(cbNode)
         {
             multicastPresenceSubscribe = 1;
@@ -481,8 +481,7 @@ OCStackResult HandlePresenceResponse(const CARemoteEndpoint_t* endPoint,
 
     if(!presenceSubscribe && !multicastPresenceSubscribe)
     {
-        OC_LOG(INFO, TAG, PCF("Received a presence notification, but I do not have callback \
-                                                ------------ ignoring"));
+        OC_LOG(ERROR, TAG, PCF("Received a presence notification, but no callback, ignoring"));
         goto exit;
     }
 
@@ -511,7 +510,6 @@ OCStackResult HandlePresenceResponse(const CARemoteEndpoint_t* endPoint,
             OC_LOG(INFO, TAG, PCF("===============No presence change"));
             goto exit;
         }
-
         if(maxAge == 0)
         {
             OC_LOG(INFO, TAG, PCF("===============Stopping presence"));
@@ -528,7 +526,6 @@ OCStackResult HandlePresenceResponse(const CARemoteEndpoint_t* endPoint,
             if(!cbNode->presence)
             {
                 cbNode->presence = (OCPresence *) OCMalloc(sizeof(OCPresence));
-
                 if(!(cbNode->presence))
                 {
                     OC_LOG(ERROR, TAG, PCF("Could not allocate memory for cbNode->presence"));
@@ -583,13 +580,13 @@ OCStackResult HandlePresenceResponse(const CARemoteEndpoint_t* endPoint,
         // This is the multicast case
 
         OCMulticastNode* mcNode = NULL;
-        mcNode = GetMCPresenceNode((const unsigned char *)fullUri);
+        mcNode = GetMCPresenceNode(fullUri);
 
         if(mcNode != NULL)
         {
             if(mcNode->nonce == response.sequenceNumber)
             {
-                OC_LOG(INFO, TAG, PCF("===============No presence change (Multicast)"));
+                OC_LOG(INFO, TAG, PCF("No presence change (Multicast)"));
                 goto exit;
             }
             mcNode->nonce = response.sequenceNumber;
@@ -602,24 +599,24 @@ OCStackResult HandlePresenceResponse(const CARemoteEndpoint_t* endPoint,
         }
         else
         {
-            uint32_t uriLen = strlen((char*)fullUri);
-            unsigned char* uri = (unsigned char *) OCMalloc(uriLen + 1);
+            uint32_t uriLen = strlen(fullUri);
+            char* uri = (char *) OCMalloc(uriLen + 1);
             if(uri)
             {
                 memcpy(uri, fullUri, (uriLen + 1));
             }
             else
             {
-                OC_LOG(INFO, TAG,
-                    PCF("===============No Memory for URI to store in the presence node"));
+                OC_LOG(ERROR, TAG,
+                    PCF("No Memory for URI to store in the presence node"));
                 result = OC_STACK_NO_MEMORY;
                 goto exit;
             }
-            result = AddMCPresenceNode(&mcNode, (unsigned char*) uri, response.sequenceNumber);
+            result = AddMCPresenceNode(&mcNode, uri, response.sequenceNumber);
             if(result == OC_STACK_NO_MEMORY)
             {
-                OC_LOG(INFO, TAG,
-                    PCF("===============No Memory for Multicast Presence Node"));
+                OC_LOG(ERROR, TAG,
+                    PCF("No Memory for Multicast Presence Node"));
                 result = OC_STACK_NO_MEMORY;
                 OCFree(uri);
                 goto exit;
@@ -656,8 +653,6 @@ void HandleCAResponses(const CARemoteEndpoint_t* endPoint, const CAResponseInfo_
 {
     OC_LOG(INFO, TAG, PCF("Enter HandleCAResponses"));
 
-    OCStackApplicationResult appResult = OC_STACK_DELETE_TRANSACTION;
-
     if(NULL == endPoint)
     {
         OC_LOG(ERROR, TAG, PCF("endPoint is NULL"));
@@ -676,7 +671,7 @@ void HandleCAResponses(const CARemoteEndpoint_t* endPoint, const CAResponseInfo_
         return;
     }
 
-    ClientCB *cbNode = GetClientCB((CAToken_t *)&(responseInfo->info.token), NULL, NULL);
+    ClientCB *cbNode = GetClientCB(&(responseInfo->info.token), NULL, NULL);
 
     if (cbNode)
     {
@@ -691,7 +686,7 @@ void HandleCAResponses(const CARemoteEndpoint_t* endPoint, const CAResponseInfo_
         }
 
         response.result = CAToOCStackResult(responseInfo->result);
-        response.resJSONPayload = (unsigned char*)responseInfo->info.payload;
+        response.resJSONPayload = responseInfo->info.payload;
         response.numRcvdVendorSpecificHeaderOptions = 0;
         if(responseInfo->info.options && responseInfo->info.numOptions > 0)
         {
@@ -721,9 +716,8 @@ void HandleCAResponses(const CARemoteEndpoint_t* endPoint, const CAResponseInfo_
                  &(responseInfo->info.options[i]), sizeof(OCHeaderOption));
             }
         }
-        appResult = cbNode->callBack(cbNode->context,
-                cbNode->handle, &response);
-        if (appResult == OC_STACK_DELETE_TRANSACTION)
+        if (cbNode->callBack(cbNode->context,cbNode->handle, &response)
+                == OC_STACK_DELETE_TRANSACTION)
         {
             FindAndDeleteClientCB(cbNode);
         }
@@ -760,8 +754,8 @@ void HandleCARequests(const CARemoteEndpoint_t* endPoint, const CARequestInfo_t*
 
     OC_LOG_V(INFO, TAG, PCF("***** Endpoint URI ***** : %s\n"), (char*)endPoint->resourceUri);
 
-    char * newUri = (char *)endPoint->resourceUri;
-    unsigned char * query = NULL;
+    char * newUri = NULL;
+    char * query = NULL;
     getQueryFromUri(endPoint->resourceUri, &query, &newUri);
     OC_LOG_V(INFO, TAG, PCF("**********URI without query ****: %s\n"), newUri);
     OC_LOG_V(INFO, TAG, PCF("**********Query ****: %s\n"), query);
@@ -791,14 +785,15 @@ void HandleCARequests(const CARemoteEndpoint_t* endPoint, const CARequestInfo_t*
     //copy request payload
     if (requestInfo->info.payload)
     {
-        serverRequest.reqTotalSize = strlen(requestInfo->info.payload) + 1;
+        size_t payloadLen = strlen(requestInfo->info.payload);
+        serverRequest.reqTotalSize = payloadLen + 1;
         memcpy (&(serverRequest.reqJSONPayload), requestInfo->info.payload,
-                strlen(requestInfo->info.payload));
-        serverRequest.reqTotalSize = strlen((const char *)requestInfo->info.payload) + 1;
+                payloadLen);
     }
     else
     {
         serverRequest.reqTotalSize = 1;
+        serverRequest.reqJSONPayload[0] = '\0';
     }
 
     switch (requestInfo->method)
@@ -833,7 +828,7 @@ void HandleCARequests(const CARemoteEndpoint_t* endPoint, const CARequestInfo_t*
     OC_LOG_V(INFO, TAG, "HandleCARequests: CA token length = %d", CA_MAX_TOKEN_LEN);
     OC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token, CA_MAX_TOKEN_LEN);
 
-    serverRequest.requestToken = (CAToken_t)OCCalloc(1, CA_MAX_TOKEN_LEN+1);
+    serverRequest.requestToken = (CAToken_t)OCMalloc(CA_MAX_TOKEN_LEN+1);
     // Module Name
     if (!serverRequest.requestToken)
     {
@@ -924,7 +919,12 @@ OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
             OC_LOG(ERROR, TAG, PCF("Error adding server request"));
             return result;
         }
-        VERIFY_NON_NULL(request, ERROR, OC_STACK_NO_MEMORY);
+
+        if(!request)
+        {
+            OC_LOG(ERROR, TAG, PCF("Out of Memory"));
+            return OC_STACK_NO_MEMORY;
+        }
 
         if(!protocolRequest->reqMorePacket)
         {
@@ -933,7 +933,8 @@ OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
     }
     else
     {
-        OC_LOG(INFO, TAG, PCF("This is either a repeated Server Request or blocked Server Request"));
+        OC_LOG(INFO, TAG,
+                PCF("This is either a repeated Server Request or blocked Server Request"));
     }
 
     if(request->requestComplete)
@@ -957,19 +958,19 @@ OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
     return result;
 }
 
-int ParseIPv4Address(unsigned char * ipAddrStr, uint8_t * ipAddr, uint16_t * port)
+int ParseIPv4Address(char * ipAddrStr, uint8_t * ipAddr, uint16_t * port)
 {
     size_t index = 0;
-    unsigned char *itr, *coap;
+    char *itr, *coap;
     uint8_t dotCount = 0;
 
     ipAddr[index] = 0;
     *port = 0;
     /* search for scheme */
     itr = ipAddrStr;
-    if (!isdigit((unsigned char) *ipAddrStr))
+    if (!isdigit((char) *ipAddrStr))
     {
-        coap = (unsigned char *) OC_COAP_SCHEME;
+        coap = OC_COAP_SCHEME;
         while (*coap && tolower(*itr) == *coap)
         {
             coap++;
@@ -979,12 +980,12 @@ int ParseIPv4Address(unsigned char * ipAddrStr, uint8_t * ipAddr, uint16_t * por
     ipAddrStr = itr;
 
     while (*ipAddrStr) {
-        if (isdigit((unsigned char) *ipAddrStr))
+        if (isdigit(*ipAddrStr))
         {
             ipAddr[index] *= 10;
             ipAddr[index] += *ipAddrStr - '0';
         }
-        else if ((unsigned char) *ipAddrStr == '.')
+        else if (*ipAddrStr == '.')
         {
             index++;
             dotCount++;
@@ -1000,7 +1001,7 @@ int ParseIPv4Address(unsigned char * ipAddrStr, uint8_t * ipAddr, uint16_t * por
     {
         ipAddrStr++;
         while (*ipAddrStr){
-            if (isdigit((unsigned char) *ipAddrStr))
+            if (isdigit(*ipAddrStr))
             {
                 *port *= 10;
                 *port += *ipAddrStr - '0';
@@ -1014,8 +1015,7 @@ int ParseIPv4Address(unsigned char * ipAddrStr, uint8_t * ipAddr, uint16_t * por
     }
 
 
-    if (ipAddr[0] < 255 && ipAddr[1] < 255 && ipAddr[2] < 255 && ipAddr[3] < 255
-            && dotCount == 3)
+    if (dotCount == 3)
     {
         return 1;
     }
@@ -1044,13 +1044,13 @@ static OCResourceInterface *findResourceInterfaceAtIndex(
 static void deleteResourceType(OCResourceType *resourceType);
 static void deleteResourceInterface(OCResourceInterface *resourceInterface);
 static void deleteResourceElements(OCResource *resource);
-static int deleteResource(OCResource *resource);
+static OCStackResult deleteResource(OCResource *resource);
 static void deleteAllResources();
 static void incrementSequenceNumber(OCResource * resPtr);
 static OCStackResult verifyUriQueryLength(const char * inputUri,
         uint16_t uriLen);
 static uint8_t OCIsPacketTransferRequired(const char *request, const char *response, uint16_t size);
-OCStackResult getResourceType(const char * query, unsigned char** resourceType);
+OCStackResult getResourceType(const char * query, char** resourceType);
 static CAResult_t OCSelectNetwork();
 
 //-----------------------------------------------------------------------------
@@ -1309,7 +1309,7 @@ OCStackResult verifyUriQueryLength(const char *inputUri, uint16_t uriLen)
  *     OC_STACK_INVALID_METHOD   - invalid resource method
  *     OC_STACK_INVALID_URI      - invalid required or reference URI
  *
- * Note: IN case of CA, when using multicast, the required URI should not contain IP address.
+ * Note: when using multicast, the required URI should not contain IP address.
  *       Instead, it just contains the URI to the resource such as "/oc/core".
  */
 OCStackResult OCDoResource(OCDoHandle *handle, OCMethod method, const char *requiredUri,
@@ -1319,21 +1319,20 @@ OCStackResult OCDoResource(OCDoHandle *handle, OCMethod method, const char *requ
 {
     OCStackResult result = OC_STACK_ERROR;
     ClientCB *clientCB = NULL;
-    unsigned char * requestUri = NULL;
-    unsigned char * resourceType = NULL;
-    unsigned char * query = NULL;
+    char * requestUri = NULL;
+    char * resourceType = NULL;
+    char * query = NULL;
     char * newUri = (char *)requiredUri;
     (void) referenceUri;
     CARemoteEndpoint_t* endpoint = NULL;
     CAResult_t caResult;
     CAToken_t token = NULL;
-    CAInfo_t requestData;
-    CARequestInfo_t requestInfo;
-    CAGroupEndpoint_t grpEnd = {0};
     OCDoHandle resHandle = NULL;
+    CAInfo_t requestData ={};
+    CARequestInfo_t requestInfo ={};
+    CAGroupEndpoint_t grpEnd = {};
 
     // To track if memory is allocated for additional header options
-    uint8_t hdrOptionMemAlloc = 0;
 
     OC_LOG(INFO, TAG, PCF("Entering OCDoResource"));
 
@@ -1405,7 +1404,7 @@ OCStackResult OCDoResource(OCDoHandle *handle, OCMethod method, const char *requ
     }
 #endif // WITH_PRESENCE
 
-    requestUri = (unsigned char *) OCMalloc(uriLen + 1);
+    requestUri = (char *) OCMalloc(uriLen + 1);
     if(requestUri)
     {
         memcpy(requestUri, newUri, (uriLen + 1));
@@ -1423,8 +1422,6 @@ OCStackResult OCDoResource(OCDoHandle *handle, OCMethod method, const char *requ
         goto exit;
     }
 
-    memset(&requestData, 0, sizeof(CAInfo_t));
-    memset(&requestInfo, 0, sizeof(CARequestInfo_t));
     switch (method)
     {
         case OC_REST_GET:
@@ -1490,7 +1487,6 @@ OCStackResult OCDoResource(OCDoHandle *handle, OCMethod method, const char *requ
         {
             goto exit;
         }
-        hdrOptionMemAlloc = 1;
         requestData.numOptions = numOptions + 1;
     }
     else
@@ -1570,10 +1566,12 @@ exit:
     }
     CADestroyRemoteEndpoint(endpoint);
     OCFree(grpEnd.resourceUri);
-
-    if (hdrOptionMemAlloc)
+    if (requestData.options  && requestData.numOptions > 0)
     {
-        OCFree(requestData.options);
+        if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
+        {
+            OCFree(requestData.options);
+        }
     }
     return result;
 }
@@ -1613,13 +1611,12 @@ OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption
      */
     OCStackResult ret = OC_STACK_OK;
     CARemoteEndpoint_t* endpoint = NULL;
-    CAResult_t caResult;
-    CAInfo_t requestData;
-    CARequestInfo_t requestInfo;
-    // Track if memory is allocated for additional header options
-    uint8_t hdrOptionMemAlloc = 0;
+    CAResult_t caResult= CA_STATUS_OK;
+    CAInfo_t requestData = {};
+    CARequestInfo_t requestInfo = {};
 
-    if(!handle) {
+    if(!handle)
+    {
         return OC_STACK_INVALID_PARAM;
     }
 
@@ -1627,7 +1624,8 @@ OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption
 
     ClientCB *clientCB = GetClientCB(NULL, handle, NULL);
 
-    if(clientCB) {
+    if(clientCB)
+    {
         switch (clientCB->method)
         {
             case OC_REST_OBSERVE:
@@ -1649,9 +1647,7 @@ OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption
                 {
                     return OC_STACK_ERROR;
                 }
-                hdrOptionMemAlloc = 1;
                 requestData.numOptions = numOptions + 1;
-                memset(&requestInfo, 0, sizeof(CARequestInfo_t));
                 requestInfo.method = CA_GET;
                 requestInfo.info = requestData;
                 // send request
@@ -1674,7 +1670,7 @@ OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption
         }
     }
     CADestroyRemoteEndpoint(endpoint);
-    if (hdrOptionMemAlloc)
+    if (requestData.numOptions > 0)
     {
         OCFree(requestData.options);
     }
@@ -1691,20 +1687,21 @@ OCStackResult OCProcessPresence()
 
     OC_LOG(INFO, TAG, PCF("Entering RequestPresence"));
     ClientCB* cbNode = NULL;
-    OCDevAddr dst;
-    OCClientResponse clientResponse;
+    OCDevAddr dst = {};
+    OCClientResponse clientResponse ={};
     OCResponse * response = NULL;
     OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
 
-    LL_FOREACH(cbList, cbNode) {
+    LL_FOREACH(cbList, cbNode)
+    {
         if(OC_REST_PRESENCE == cbNode->method)
         {
             if(cbNode->presence)
             {
                 uint32_t now = GetTime(0);
-                OC_LOG_V(DEBUG, TAG, "----------------this TTL level %d",
+                OC_LOG_V(DEBUG, TAG, "this TTL level %d",
                                                         cbNode->presence->TTLlevel);
-                OC_LOG_V(DEBUG, TAG, "----------------current ticks %d", now);
+                OC_LOG_V(DEBUG, TAG, "current ticks %d", now);
 
 
                 if(cbNode->presence->TTLlevel >= (PresenceTimeOutSize + 1))
@@ -1712,14 +1709,15 @@ OCStackResult OCProcessPresence()
                     goto exit;
                 }
 
-                if(cbNode->presence->TTLlevel < PresenceTimeOutSize){
-                    OC_LOG_V(DEBUG, TAG, "----------------timeout ticks %d",
+                if(cbNode->presence->TTLlevel < PresenceTimeOutSize)
+                {
+                    OC_LOG_V(DEBUG, TAG, "timeout ticks %d",
                             cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
                 }
 
                 if(cbNode->presence->TTLlevel >= PresenceTimeOutSize)
                 {
-                    OC_LOG(DEBUG, TAG, PCF("----------------No more timeout ticks"));
+                    OC_LOG(DEBUG, TAG, PCF("No more timeout ticks"));
                     if (ParseIPv4Address( cbNode->requestUri, ipAddr, &port))
                     {
                         OCBuildIPv4Address(ipAddr[0], ipAddr[1], ipAddr[2], ipAddr[3], port,
@@ -1740,7 +1738,7 @@ OCStackResult OCProcessPresence()
                         // Increment the TTLLevel (going to a next state), so we don't keep
                         // sending presence notification to client.
                         cbNode->presence->TTLlevel++;
-                        OC_LOG_V(DEBUG, TAG, "----------------moving to TTL level %d",
+                        OC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
                                                 cbNode->presence->TTLlevel);
                     }
                     else
@@ -1758,12 +1756,12 @@ OCStackResult OCProcessPresence()
 
                 if(now >= cbNode->presence->timeOut[cbNode->presence->TTLlevel])
                 {
-                    CAResult_t caResult;
+                    CAResult_t caResult = CA_STATUS_OK;
                     CARemoteEndpoint_t* endpoint = NULL;
-                    CAInfo_t requestData;
-                    CARequestInfo_t requestInfo;
+                    CAInfo_t requestData ={};
+                    CARequestInfo_t requestInfo = {};
 
-                    OC_LOG(DEBUG, TAG, PCF("time to test server presence =========="));
+                    OC_LOG(DEBUG, TAG, PCF("time to test server presence"));
 
                     //TODO-CA : Why CA_WIFI alone?
                     caResult = CACreateRemoteEndpoint((char *)cbNode->requestUri, CA_WIFI,
@@ -1775,11 +1773,9 @@ OCStackResult OCProcessPresence()
                         goto exit;
                     }
 
-                    memset(&requestData, 0, sizeof(CAInfo_t));
                     requestData.type = CA_MSG_NONCONFIRM;
                     requestData.token = cbNode->token;
 
-                    memset(&requestInfo, 0, sizeof(CARequestInfo_t));
                     requestInfo.method = CA_GET;
                     requestInfo.info = requestData;
 
@@ -1792,7 +1788,7 @@ OCStackResult OCProcessPresence()
                     }
 
                     cbNode->presence->TTLlevel++;
-                    OC_LOG_V(DEBUG, TAG, "----------------moving to TTL level %d",
+                    OC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
                                                             cbNode->presence->TTLlevel);
                 }
             }
@@ -1856,7 +1852,7 @@ OCStackResult OCStartPresence(const uint32_t ttl)
         presenceState = OC_PRESENCE_INITIALIZED;
 
         CAAddress_t addressInfo;
-        strncpy(addressInfo.IP.ipAddress, "224.0.1.187", CA_IPADDR_SIZE);
+        strncpy(addressInfo.IP.ipAddress, OC_MULTICAST_IP, CA_IPADDR_SIZE);
         addressInfo.IP.port = 5683;
 
         //TODO make sure there is no memory leak here since another copy
@@ -1932,12 +1928,14 @@ OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo)
 {
     OC_LOG(INFO, TAG, PCF("Entering OCSetDeviceInfo"));
 
-    if(myStackMode == OC_CLIENT)
+    if(myStackMode ==  OC_SERVER || myStackMode == OC_CLIENT_SERVER)
+    {
+        return SaveDeviceInfo(deviceInfo);
+    }
+    else
     {
         return OC_STACK_ERROR;
     }
-
-    return SaveDeviceInfo(deviceInfo);
 }
 
 /**
@@ -1966,17 +1964,17 @@ OCStackResult OCCreateResource(OCResourceHandle *handle,
 
     OCResource *pointer = NULL;
     char *str = NULL;
-    size_t size;
+    size_t size = 0;
     OCStackResult result = OC_STACK_ERROR;
 
     OC_LOG(INFO, TAG, PCF("Entering OCCreateResource"));
 
     if(myStackMode == OC_CLIENT)
     {
-        return result;
+        return OC_STACK_INVALID_PARAM;
     }
     // Validate parameters
-    if(!uri || (strlen(uri) == 0))
+    if(!uri || uri[0]=='\0' || strlen(uri)>=MAX_URI_LENGTH )
     {
         OC_LOG(ERROR, TAG, PCF("URI is invalid"));
         return OC_STACK_INVALID_URI;
@@ -1988,7 +1986,8 @@ OCStackResult OCCreateResource(OCResourceHandle *handle,
         return OC_STACK_INVALID_PARAM;
     }
 
-    if(!resourceInterfaceName || strlen(resourceInterfaceName) == 0) {
+    if(!resourceInterfaceName || strlen(resourceInterfaceName) == 0)
+    {
         resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
     }
 
@@ -2118,7 +2117,13 @@ OCStackResult OCCreateResourceWithHost(OCResourceHandle *handle,
         uint8_t resourceProperties)
 {
     char *str = NULL;
-    size_t size;
+    size_t size = 0;
+
+    if(!host)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+
     OCStackResult result = OC_STACK_ERROR;
 
     result = OCCreateResource(handle, resourceTypeName, resourceInterfaceName,
@@ -2131,7 +2136,7 @@ OCStackResult OCCreateResourceWithHost(OCResourceHandle *handle,
         str = (char *) OCMalloc(size);
         if (!str)
         {
-            return OC_STACK_ERROR;
+            return OC_STACK_NO_MEMORY;
         }
         strncpy(str, host, size);
         ((OCResource *) *handle)->host = str;
@@ -2154,8 +2159,8 @@ OCStackResult OCCreateResourceWithHost(OCResourceHandle *handle,
 OCStackResult OCBindResource(
         OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
 {
-    OCResource *resource;
-    uint8_t i;
+    OCResource *resource = NULL;
+    uint8_t i = 0;
 
     OC_LOG(INFO, TAG, PCF("Entering OCBindResource"));
 
@@ -2185,17 +2190,18 @@ OCStackResult OCBindResource(
         {
             resource->rsrcResources[i] = (OCResource *) resourceHandle;
             OC_LOG(INFO, TAG, PCF("resource bound"));
+
+            #ifdef WITH_PRESENCE
+            if(presenceResource.handle)
+            {
+                ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
+                SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType);
+            }
+            #endif
             return OC_STACK_OK;
-        }
-    }
 
-    #ifdef WITH_PRESENCE
-    if(presenceResource.handle)
-    {
-        ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
-        SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType);
+        }
     }
-    #endif
 
     // Unable to add resourceHandle, so return error
     return OC_STACK_ERROR;
@@ -2213,9 +2219,10 @@ OCStackResult OCBindResource(
  *     OC_STACK_INVALID_PARAM - invalid collectionHandle
  */
 OCStackResult OCUnBindResource(
-        OCResourceHandle collectionHandle, OCResourceHandle resourceHandle) {
-    OCResource *resource;
-    uint8_t i;
+        OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
+{
+    OCResource *resource = NULL;
+    uint8_t i = 0;
 
     OC_LOG(INFO, TAG, PCF("Entering OCUnBindResource"));
 
@@ -2223,22 +2230,26 @@ OCStackResult OCUnBindResource(
     VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
     VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
     // Container cannot contain itself
-    if (collectionHandle == resourceHandle) {
+    if (collectionHandle == resourceHandle)
+    {
         OC_LOG(ERROR, TAG, PCF("removing handle equals collection handle"));
         return OC_STACK_INVALID_PARAM;
     }
 
     // Use the handle to find the resource in the resource linked list
     resource = findResource((OCResource *) collectionHandle);
-    if (!resource) {
+    if (!resource)
+    {
         OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
         return OC_STACK_INVALID_PARAM;
     }
 
     // Look for an open slot to add add the child resource.
     // If found, add it and return success
-    for (i = 0; i < MAX_CONTAINED_RESOURCES; i++) {
-        if (resourceHandle == resource->rsrcResources[i]) {
+    for (i = 0; i < MAX_CONTAINED_RESOURCES; i++)
+    {
+        if (resourceHandle == resource->rsrcResources[i])
+        {
             resource->rsrcResources[i] = (OCResource *) NULL;
             OC_LOG(INFO, TAG, PCF("resource unbound"));
 
@@ -2250,7 +2261,6 @@ OCStackResult OCUnBindResource(
                 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType);
             }
             #endif
-
             return OC_STACK_OK;
         }
     }
@@ -2266,7 +2276,7 @@ OCStackResult BindResourceTypeToResource(OCResource* resource,
 {
     OCResourceType *pointer = NULL;
     char *str = NULL;
-    size_t size;
+    size_t size = 0;
     OCStackResult result = OC_STACK_ERROR;
 
     OC_LOG(INFO, TAG, PCF("Entering BindResourceTypeToResource"));
@@ -2315,7 +2325,7 @@ OCStackResult BindResourceInterfaceToResource(OCResource* resource,
 {
     OCResourceInterface *pointer = NULL;
     char *str = NULL;
-    size_t size;
+    size_t size = 0;
     OCStackResult result = OC_STACK_ERROR;
 
     OC_LOG(INFO, TAG, PCF("Entering BindResourceInterfaceToResource"));
@@ -2370,14 +2380,16 @@ OCStackResult BindResourceInterfaceToResource(OCResource* resource,
  *     OC_STACK_ERROR - stack process error
  */
 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
-        const char *resourceTypeName) {
+        const char *resourceTypeName)
+{
 
     OCStackResult result = OC_STACK_ERROR;
-    OCResource *resource;
+    OCResource *resource = NULL;
 
     // Make sure resource exists
     resource = findResource((OCResource *) handle);
-    if (!resource) {
+    if (!resource)
+    {
         OC_LOG(ERROR, TAG, PCF("Resource not found"));
         return OC_STACK_ERROR;
     }
@@ -2408,14 +2420,16 @@ OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
  */
 
 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
-        const char *resourceInterfaceName) {
+        const char *resourceInterfaceName)
+{
 
     OCStackResult result = OC_STACK_ERROR;
-    OCResource *resource;
+    OCResource *resource = NULL;
 
     // Make sure resource exists
     resource = findResource((OCResource *) handle);
-    if (!resource) {
+    if (!resource)
+    {
         OC_LOG(ERROR, TAG, PCF("Resource not found"));
         return OC_STACK_ERROR;
     }
@@ -2444,13 +2458,15 @@ OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
  *     OC_STACK_ERROR - stack process error
 
  */
-OCStackResult OCGetNumberOfResources(uint8_t *numResources) {
+OCStackResult OCGetNumberOfResources(uint8_t *numResources)
+{
     OCResource *pointer = headResource;
 
     OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResources"));
     VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
     *numResources = 0;
-    while (pointer) {
+    while (pointer)
+    {
         *numResources = *numResources + 1;
         pointer = pointer->next;
     }
@@ -2466,15 +2482,15 @@ OCStackResult OCGetNumberOfResources(uint8_t *numResources) {
  *    Resource handle - if found
  *    NULL - if not found
  */
-OCResourceHandle OCGetResourceHandle(uint8_t index) {
+OCResourceHandle OCGetResourceHandle(uint8_t index)
+{
     OCResource *pointer = headResource;
-    uint8_t i = 0;
 
     OC_LOG(INFO, TAG, PCF("Entering OCGetResourceHandle"));
 
     // Iterate through the list
-    while ((i < index) && pointer) {
-        i++;
+    for( uint8_t i = 0; i < index && pointer; ++i)
+    {
         pointer = pointer->next;
     }
     return (OCResourceHandle) pointer;
@@ -2492,21 +2508,25 @@ OCResourceHandle OCGetResourceHandle(uint8_t index) {
  *     OC_STACK_NO_RESOURCE     - resource not found
  *     OC_STACK_INVALID_PARAM   - invalid param
  */
-OCStackResult OCDeleteResource(OCResourceHandle handle) {
+OCStackResult OCDeleteResource(OCResourceHandle handle)
+{
     OC_LOG(INFO, TAG, PCF("Entering OCDeleteResource"));
 
-    if (!handle) {
+    if (!handle)
+    {
         OC_LOG(ERROR, TAG, PCF("Invalid param"));
         return OC_STACK_INVALID_PARAM;
     }
 
     OCResource *resource = findResource((OCResource *) handle);
-    if (resource == NULL) {
+    if (resource == NULL)
+    {
         OC_LOG(ERROR, TAG, PCF("Resource not found"));
         return OC_STACK_NO_RESOURCE;
     }
 
-    if (deleteResource((OCResource *) handle) == 0) {
+    if (deleteResource((OCResource *) handle) != OC_STACK_OK)
+    {
         OC_LOG(ERROR, TAG, PCF("Error deleting resource"));
         return OC_STACK_ERROR;
     }
@@ -2522,12 +2542,14 @@ OCStackResult OCDeleteResource(OCResourceHandle handle) {
  *    URI string - if resource found
  *    NULL - resource not found
  */
-const char *OCGetResourceUri(OCResourceHandle handle) {
-    OCResource *resource;
+const char *OCGetResourceUri(OCResourceHandle handle)
+{
+    OCResource *resource = NULL;
     OC_LOG(INFO, TAG, PCF("Entering OCGetResourceUri"));
 
     resource = findResource((OCResource *) handle);
-    if (resource) {
+    if (resource)
+    {
         return resource->uri;
     }
     return (const char *) NULL;
@@ -2540,18 +2562,20 @@ const char *OCGetResourceUri(OCResourceHandle handle) {
  *
  * @param handle - handle of resource
  * @return
- *    property bitmap - if resource found
- *    NULL - resource not found
+ *    OCResourceProperty Bitmask
+ *    -1 if resource is not found
  */
-uint8_t OCGetResourceProperties(OCResourceHandle handle) {
-    OCResource *resource;
+OCResourceProperty OCGetResourceProperties(OCResourceHandle handle)
+{
+    OCResource *resource = NULL;
     OC_LOG(INFO, TAG, PCF("Entering OCGetResourceProperties"));
 
     resource = findResource((OCResource *) handle);
-    if (resource) {
+    if (resource)
+    {
         return resource->resourceProperties;
     }
-    return 0;
+    return (OCResourceProperty)-1;
 }
 
 /**
@@ -2565,9 +2589,10 @@ uint8_t OCGetResourceProperties(OCResourceHandle handle) {
  *     OC_STACK_ERROR - stack process error
  */
 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
-        uint8_t *numResourceTypes) {
-    OCResource *resource;
-    OCResourceType *pointer;
+        uint8_t *numResourceTypes)
+{
+    OCResource *resource = NULL;
+    OCResourceType *pointer = NULL;
 
     OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResourceTypes"));
     VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
@@ -2576,9 +2601,11 @@ OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
     *numResourceTypes = 0;
 
     resource = findResource((OCResource *) handle);
-    if (resource) {
+    if (resource)
+    {
         pointer = resource->rsrcType;
-        while (pointer) {
+        while (pointer)
+        {
             *numResourceTypes = *numResourceTypes + 1;
             pointer = pointer->next;
         }
@@ -2596,13 +2623,15 @@ OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
  *    resource type name - if resource found
  *    NULL - resource not found
  */
-const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index) {
-    OCResourceType *resourceType;
+const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index)
+{
+    OCResourceType *resourceType = NULL;
 
     OC_LOG(INFO, TAG, PCF("Entering OCGetResourceTypeName"));
 
     resourceType = findResourceTypeAtIndex(handle, index);
-    if (resourceType) {
+    if (resourceType)
+    {
         return resourceType->resourcetypename;
     }
     return (const char *) NULL;
@@ -2621,9 +2650,10 @@ const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index) {
  *     OC_STACK_ERROR - stack process error
  */
 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
-        uint8_t *numResourceInterfaces) {
-    OCResourceInterface *pointer;
-    OCResource *resource;
+        uint8_t *numResourceInterfaces)
+{
+    OCResourceInterface *pointer = NULL;
+    OCResource *resource = NULL;
 
     OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResourceInterfaces"));
 
@@ -2632,9 +2662,11 @@ OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
 
     *numResourceInterfaces = 0;
     resource = findResource((OCResource *) handle);
-    if (resource) {
+    if (resource)
+    {
         pointer = resource->rsrcInterface;
-        while (pointer) {
+        while (pointer)
+        {
             *numResourceInterfaces = *numResourceInterfaces + 1;
             pointer = pointer->next;
         }
@@ -2652,13 +2684,15 @@ OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
  *    resource interface name - if resource found
  *    NULL - resource not found
  */
-const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index) {
-    OCResourceInterface *resourceInterface;
+const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index)
+{
+    OCResourceInterface *resourceInterface = NULL;
 
     OC_LOG(INFO, TAG, PCF("Entering OCGetResourceInterfaceName"));
 
     resourceInterface = findResourceInterfaceAtIndex(handle, index);
-    if (resourceInterface) {
+    if (resourceInterface)
+    {
         return resourceInterface->name;
     }
     return (const char *) NULL;
@@ -2675,17 +2709,20 @@ const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index) {
  *    NULL - resource not found
  */
 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
-        uint8_t index) {
-    OCResource *resource;
+        uint8_t index)
+{
+    OCResource *resource = NULL;
 
     OC_LOG(INFO, TAG, PCF("Entering OCGetContainedResource"));
 
-    if (index >= MAX_CONTAINED_RESOURCES) {
+    if (index >= MAX_CONTAINED_RESOURCES)
+    {
         return NULL;
     }
 
     resource = findResource((OCResource *) collectionHandle);
-    if (!resource) {
+    if (!resource)
+    {
         return NULL;
     }
 
@@ -2702,18 +2739,19 @@ OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHa
  *     OC_STACK_ERROR - stack process error
  */
 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
-        OCEntityHandler entityHandler) {
-    OCResource *resource;
+        OCEntityHandler entityHandler)
+{
+    OCResource *resource = NULL;
 
     OC_LOG(INFO, TAG, PCF("Entering OCBindResourceHandler"));
 
     // Validate parameters
     VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
-    //VERIFY_NON_NULL(entityHandler, ERROR, OC_STACK_INVALID_PARAM);
 
     // Use the handle to find the resource in the resource linked list
     resource = findResource((OCResource *)handle);
-    if (!resource) {
+    if (!resource)
+    {
         OC_LOG(ERROR, TAG, PCF("Resource not found"));
         return OC_STACK_ERROR;
     }
@@ -2741,14 +2779,16 @@ OCStackResult OCBindResourceHandler(OCResourceHandle handle,
  *    entity handler - if resource found
  *    NULL - resource not found
  */
-OCEntityHandler OCGetResourceHandler(OCResourceHandle handle) {
-    OCResource *resource;
+OCEntityHandler OCGetResourceHandler(OCResourceHandle handle)
+{
+    OCResource *resource = NULL;
 
     OC_LOG(INFO, TAG, PCF("Entering OCGetResourceHandler"));
 
     // Use the handle to find the resource in the resource linked list
     resource = findResource((OCResource *)handle);
-    if (!resource) {
+    if (!resource)
+    {
         OC_LOG(ERROR, TAG, PCF("Resource not found"));
         return NULL;
     }
@@ -2841,12 +2881,13 @@ OCStackResult SendStopNotification()
  *     OC_STACK_NO_RESOURCE - invalid resource handle
  *     OC_STACK_NO_OBSERVERS - no more observers intrested in resource
  */
-OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos) {
+OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos)
+{
 
     OC_LOG(INFO, TAG, PCF("Entering OCNotifyAllObservers"));
 
     OCResource *resPtr = NULL;
-    OCStackResult result;
+    OCStackResult result = OC_STACK_ERROR;
     OCMethod method = OC_REST_NOMETHOD;
     uint32_t maxAge = 0;
 
@@ -2884,7 +2925,7 @@ OCStackResult
 OCNotifyListOfObservers (OCResourceHandle handle,
                          OCObservationId  *obsIdList,
                          uint8_t          numberOfIds,
-                         unsigned char    *notificationJSONPayload,
+                         const char       *notificationJSONPayload,
                          OCQualityOfService qos)
 {
     OC_LOG(INFO, TAG, PCF("Entering OCNotifyListOfObservers"));
@@ -3012,7 +3053,8 @@ OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
         OCResourceProperty resourceProperties, uint8_t enable)
 {
     if (resourceProperties
-            > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW)) {
+            > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW))
+    {
         OC_LOG(ERROR, TAG, PCF("Invalid property"));
         return OC_STACK_INVALID_PARAM;
     }
@@ -3031,7 +3073,8 @@ OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
 /**
  * Initialize resource data structures, variables, etc.
  */
-OCStackResult initResources() {
+OCStackResult initResources()
+{
     OCStackResult result = OC_STACK_OK;
     // Init application resource vars
     headResource = NULL;
@@ -3061,9 +3104,9 @@ OCStackResult initResources() {
  */
 void insertResource(OCResource *resource)
 {
-    if (!headResource)
-    {
-        // First resource. Head and tail are the same.
+    OCResource *pointer = NULL;
+
+    if (!headResource) {
         headResource = resource;
         tailResource = resource;
     }
@@ -3101,7 +3144,7 @@ OCResource *findResource(OCResource *resource)
 void deleteAllResources()
 {
     OCResource *pointer = headResource;
-    OCResource *temp;
+    OCResource *temp = NULL;
 
     while (pointer)
     {
@@ -3129,13 +3172,13 @@ void deleteAllResources()
  *
  * @param resource - resource to be deleted
  * @return
- *    0 - error
- *    1 - success
+ *    OC_STACK_ERROR - error
+ *    OC_STACK_OK - success
  */
-int deleteResource(OCResource *resource)
+OCStackResult deleteResource(OCResource *resource)
 {
     OCResource *prev = NULL;
-    OCResource *temp;
+    OCResource *temp = NULL;
 
     temp = headResource;
     while (temp)
@@ -3165,7 +3208,6 @@ int deleteResource(OCResource *resource)
                 }
             }
             #endif
-
             // Only resource in list.
             if (temp == headResource && temp == tailResource)
             {
@@ -3190,7 +3232,7 @@ int deleteResource(OCResource *resource)
 
             deleteResourceElements(temp);
             OCFree(temp);
-            return 1;
+            return OC_STACK_OK;
         }
         else
         {
@@ -3199,7 +3241,7 @@ int deleteResource(OCResource *resource)
         }
     }
 
-    return 0;
+    return OC_STACK_ERROR;
 }
 
 /**
@@ -3209,7 +3251,8 @@ int deleteResource(OCResource *resource)
  */
 void deleteResourceElements(OCResource *resource)
 {
-    if (!resource) {
+    if (!resource)
+    {
         return;
     }
 
@@ -3231,7 +3274,7 @@ void deleteResourceElements(OCResource *resource)
 void deleteResourceType(OCResourceType *resourceType)
 {
     OCResourceType *pointer = resourceType;
-    OCResourceType *next;
+    OCResourceType *next = NULL;
 
     while (pointer)
     {
@@ -3247,9 +3290,10 @@ void deleteResourceType(OCResourceType *resourceType)
  *
  * @param resourceInterface - specified resource interface
  */
-void deleteResourceInterface(OCResourceInterface *resourceInterface) {
+void deleteResourceInterface(OCResourceInterface *resourceInterface)
+{
     OCResourceInterface *pointer = resourceInterface;
-    OCResourceInterface *next;
+    OCResourceInterface *next = NULL;
 
     while (pointer)
     {
@@ -3266,8 +3310,9 @@ void deleteResourceInterface(OCResourceInterface *resourceInterface) {
  * @param resource - resource where resource type is to be inserted
  * @param resourceType - resource type to be inserted
  */
-void insertResourceType(OCResource *resource, OCResourceType *resourceType) {
-    OCResourceType *pointer;
+void insertResourceType(OCResource *resource, OCResourceType *resourceType)
+{
+    OCResourceType *pointer = NULL;
 
     if (resource && !resource->rsrcType)
     {
@@ -3283,7 +3328,8 @@ void insertResourceType(OCResource *resource, OCResourceType *resourceType) {
         {
             pointer = resourceType;
         }
-        while (pointer->next) {
+        while (pointer->next)
+        {
             pointer = pointer->next;
         }
         pointer->next = resourceType;
@@ -3301,10 +3347,10 @@ void insertResourceType(OCResource *resource, OCResourceType *resourceType) {
  *    resourcetype - if found
  *    NULL - not found
  */
-OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index) {
-    OCResource *resource;
-    OCResourceType *pointer;
-    uint8_t i;
+OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
+{
+    OCResource *resource = NULL;
+    OCResourceType *pointer = NULL;
 
     // Find the specified resource
     resource = findResource((OCResource *) handle);
@@ -3321,10 +3367,8 @@ OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
 
     // Iterate through the list
     pointer = resource->rsrcType;
-    i = 0;
-    while ((i < index) && pointer)
+    for(uint8_t i = 0; i< index && pointer; ++i)
     {
-        i++;
         pointer = pointer->next;
     }
     return pointer;
@@ -3368,8 +3412,7 @@ OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char *
 void insertResourceInterface(OCResource *resource,
         OCResourceInterface *resourceInterface)
 {
-    OCResourceInterface *pointer;
-
+    OCResourceInterface *pointer = NULL;
     if (!resource->rsrcInterface)
     {
         resource->rsrcInterface = resourceInterface;
@@ -3397,27 +3440,29 @@ void insertResourceInterface(OCResource *resource,
  *    NULL - not found
  */
 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
-        uint8_t index) {
-    OCResource *resource;
-    OCResourceInterface *pointer;
-    uint8_t i = 0;
+        uint8_t index)
+{
+    OCResource *resource = NULL;
+    OCResourceInterface *pointer = NULL;
 
     // Find the specified resource
     resource = findResource((OCResource *) handle);
-    if (!resource) {
+    if (!resource)
+    {
         return NULL;
     }
 
     // Make sure a resource has a resourceinterface
-    if (!resource->rsrcInterface) {
+    if (!resource->rsrcInterface)
+    {
         return NULL;
     }
 
     // Iterate through the list
     pointer = resource->rsrcInterface;
 
-    while ((i < index) && pointer) {
-        i++;
+    for (uint8_t i = 0; i < index && pointer; ++i)
+    {
         pointer = pointer->next;
     }
     return pointer;
@@ -3463,20 +3508,20 @@ uint8_t OCIsPacketTransferRequired(const char *request, const char *response, ui
 }
 
 /**
- * Retrieves a resource type based upon a query ontains only just one
+ * Retrieves a resource type based upon a query contains only just one
  * resource attribute (and that has to be of type "rt").
  *
  * @remark This API malloc's memory for the resource type. Do not malloc resourceType
  * before passing in.
  *
- * @param query - The quert part of the URI
+ * @param query - The query part of the URI
  * @param resourceType - The resource type to be populated; pass by reference.
  *
  * @return
  *  OC_STACK_INVALID_PARAM - Returns this if the resourceType parameter is invalid/NULL.
  *  OC_STACK_OK            - Success
  */
-OCStackResult getResourceType(const char * query, unsigned char** resourceType)
+OCStackResult getResourceType(const char * query, char** resourceType)
 {
     if(!query)
     {
@@ -3487,7 +3532,7 @@ OCStackResult getResourceType(const char * query, unsigned char** resourceType)
 
     if(strncmp(query, "rt=", 3) == 0)
     {
-        *resourceType = (unsigned char *) OCMalloc(strlen(query)-3);
+        *resourceType = (char *) OCMalloc(strlen(query)-3 + 1);
         if(!*resourceType)
         {
             result = OC_STACK_NO_MEMORY;
@@ -3500,7 +3545,7 @@ OCStackResult getResourceType(const char * query, unsigned char** resourceType)
     return result;
 }
 
-OCStackResult getQueryFromUri(const char * uri, unsigned char** query, char ** newURI)
+OCStackResult getQueryFromUri(const char * uri, char** query, char ** newURI)
 {
     if(!uri)
     {
@@ -3517,21 +3562,21 @@ OCStackResult getQueryFromUri(const char * uri, unsigned char** query, char ** n
         goto exit;
     }
     strcpy(tempURI, uri);
-    char* strTokPtr;
-    leftToken = strtok_r((char *)tempURI, "?", &strTokPtr);
+    char* strTokPtr = NULL;
+    leftToken = strtok_r(tempURI, "?", &strTokPtr);
 
     //TODO-CA: This could be simplified. Clean up required.
     while(leftToken != NULL)
     {
         if(strncmp(leftToken, "rt=", 3) == 0 || strncmp(leftToken, "if=", 3) == 0)
         {
-            *query = (unsigned char *) OCMalloc(strlen(leftToken) + 1);
+            *query = (char *) OCMalloc(strlen(leftToken) + 1);
             if(!*query)
             {
                 OCFree(tempURI);
                 goto exit;
             }
-            strcpy((char *)*query, ((const char *)&leftToken[0]));
+            strcpy(*query, &leftToken[0]);
             break;
         }
         leftToken = strtok_r(NULL, "?", &strTokPtr);
@@ -3549,7 +3594,6 @@ const ServerID OCGetServerInstanceID(void)
 {
     static bool generated = false;
     static ServerID sid;
-
     if(generated)
     {
         return sid;
@@ -3567,8 +3611,8 @@ const char* OCGetServerInstanceIDString(void)
     // This will change as the representation gets switched
     // to another value
     static char buffer[11];
-    int n = sprintf(buffer, "%u", OCGetServerInstanceID());
-    if (n < 0)
+
+    if (snprintf(buffer, sizeof(buffer),"%u", OCGetServerInstanceID()) < 0)
     {
         buffer[0]='\0';
     }
@@ -3580,8 +3624,9 @@ const char* OCGetServerInstanceIDString(void)
 int32_t OCDevAddrToIPv4Addr(OCDevAddr *ipAddr, uint8_t *a, uint8_t *b,
         uint8_t *c, uint8_t *d )
 {
-    if ( !ipAddr || !a || !b || !c || !d ) {
-        OC_LOG(FATAL, TAG, "Invalid argument");
+    if ( !ipAddr || !a || !b || !c || !d )
+    {
+        OC_LOG(FATAL, TAG, PCF("Invalid argument"));
         return OC_STACK_INVALID_PARAM;
     }
 
@@ -3597,8 +3642,9 @@ int32_t OCDevAddrToIPv4Addr(OCDevAddr *ipAddr, uint8_t *a, uint8_t *b,
 /// Retrieve the IPv4 address embedded inside OCDev address data structure
 int32_t OCDevAddrToPort(OCDevAddr *ipAddr, uint16_t *port)
 {
-    if ( !ipAddr || !port ) {
-        OC_LOG(FATAL, TAG, "Invalid argument");
+    if ( !ipAddr || !port )
+    {
+        OC_LOG(FATAL, TAG, PCF("Invalid argument"));
         return OC_STACK_INVALID_PARAM;
     }
 
index 2d5bde6..85d17aa 100644 (file)
@@ -42,16 +42,13 @@ typedef struct aggregatehandleinfo
     OCResource *collResource;
 
     struct aggregatehandleinfo *next;
-} ClientRequstInfo;
+} ClientRequestInfo;
 
-// unsigned int nHandleIdx = 0;
-// ClientRequstInfo g_AggregateResponseHandle[10];
+static ClientRequestInfo *clientRequestList = NULL;
 
-ClientRequstInfo *clientRequstList = NULL;
-
-void AddClientRequestInfo(ClientRequstInfo **head, ClientRequstInfo* add)
+void AddClientRequestInfo(ClientRequestInfo **head, ClientRequestInfo* add)
 {
-    ClientRequstInfo *tmp = NULL;
+    ClientRequestInfo *tmp = NULL;
 
     if (*head != NULL)
     {
@@ -69,9 +66,9 @@ void AddClientRequestInfo(ClientRequstInfo **head, ClientRequstInfo* add)
     }
 }
 
-ClientRequstInfo* GetClientRequestInfo(ClientRequstInfo *head, OCDoHandle handle)
+ClientRequestInfo* GetClientRequestInfo(ClientRequestInfo *head, OCDoHandle handle)
 {
-    ClientRequstInfo *tmp = NULL;
+    ClientRequestInfo *tmp = NULL;
 
     tmp = head;
 
@@ -79,7 +76,6 @@ ClientRequstInfo* GetClientRequestInfo(ClientRequstInfo *head, OCDoHandle handle
     {
         while (tmp)
         {
-//            printf("%p :: %p\n", tmp->required, handle);
             if (tmp->required == handle)
             {
                 break;
@@ -93,9 +89,9 @@ ClientRequstInfo* GetClientRequestInfo(ClientRequstInfo *head, OCDoHandle handle
     return NULL;
 }
 
-void RemoveClientRequestInfo(ClientRequstInfo **head, ClientRequstInfo* del)
+void RemoveClientRequestInfo(ClientRequestInfo **head, ClientRequestInfo* del)
 {
-    ClientRequstInfo *tmp = NULL;
+    ClientRequestInfo *tmp = NULL;
 
     if (*head == del)
     {
@@ -175,9 +171,9 @@ void AddActionSet(OCActionSet **head, OCActionSet* node)
 
 void DeleteCapability(OCCapability *del)
 {
-    free(del->capability);
+    OCFree(del->capability);
     del->capability = NULL;
-    free(del->status);
+    OCFree(del->status);
     del->status = NULL;
 }
 
@@ -322,8 +318,14 @@ OCStackResult ExtractKeyValueFromRequest(char *request, char **key, char **value
     OCStackResult result = OC_STACK_OK;
     size_t length = 0;
 
+    if(strlen(request) <= strlen(OIC_ACTION_PREFIX))
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+
     char* pRequest = (char *)request + strlen(OIC_ACTION_PREFIX);
-    char* iterToken, *iterTokenPtr;
+    char* iterToken = NULL;
+    char* iterTokenPtr = NULL;
 
     iterToken = (char *) strtok_r(pRequest, ":", &iterTokenPtr);
     length = strlen(iterToken) + 1;
@@ -359,10 +361,14 @@ OCStackResult BuildActionSetFromString(OCActionSet **set, char* actiondesc)
     OCStackResult result = OC_STACK_OK;
 
     char *iterToken = NULL, *iterTokenPtr = NULL;
-    char *descIterToken = NULL, *descIterTokenPtr = NULL;
-    char *attrIterToken = NULL, *attrIterTokenPtr = NULL;
-    char *desc = NULL, *attr = NULL;
-    char *key = NULL, *value = NULL;
+    char *descIterToken = NULL;
+    char *descIterTokenPtr = NULL;
+    char *attrIterToken = NULL;
+    char *attrIterTokenPtr = NULL;
+    char *desc = NULL;
+    char *attr = NULL;
+    char *key = NULL;
+    char *value = NULL;
 
     OCAction *action = NULL;
     OCCapability *capa = NULL;
@@ -406,7 +412,7 @@ OCStackResult BuildActionSetFromString(OCActionSet **set, char* actiondesc)
             VARIFY_PARAM_NULL(attrIterToken, result, exit)
             strncpy(value, attrIterToken, strlen(attrIterToken) + 1);
 
-            if(strcmp(key, "uri") == 0)
+            if(strncmp(key, "uri", sizeof("uri") - 1) == 0)
             {
                 OC_LOG(INFO, TAG, PCF("Build OCAction Instance."));
 
@@ -464,17 +470,13 @@ exit:
 OCStackResult BuildStringFromActionSet(OCActionSet* actionset, char** desc)
 {
     char temp[1024] = { 0 };
-    int remaining = 1023;
+    uint16_t remaining = sizeof(temp) - 1;
 
-    // OCActionSet *as = resource->actionsetHead;
-    // while(as != NULL)
-    // {
-    // printf("\n\n\nAction Set Name :: %s\n", actionset->actionsetName);
     OCAction *action = actionset->head;
 
     if (remaining >= strlen(actionset->actionsetName) + 1)
     {
-        strcat(temp, actionset->actionsetName);
+        strncat(temp, actionset->actionsetName, sizeof(temp));
         remaining -= strlen(actionset->actionsetName);
         strcat(temp, "*");
         remaining--;
@@ -486,7 +488,7 @@ OCStackResult BuildStringFromActionSet(OCActionSet* actionset, char** desc)
 
     while (action != NULL)
     {
-        printf("\tURI :: %s\n", action->resourceUri);
+        OC_LOG_V(INFO, TAG, "\tURI :: %s\n", action->resourceUri);
         strcat(temp, "uri=");
         remaining -= strlen("uri=");
         strcat(temp, action->resourceUri);
@@ -497,7 +499,7 @@ OCStackResult BuildStringFromActionSet(OCActionSet* actionset, char** desc)
         OCCapability *capas = action->head;
         while (capas != NULL)
         {
-            printf("\t\t%s = %s\n", capas->capability, capas->status);
+            OC_LOG_V(INFO, TAG, "\t\t%s = %s\n", capas->capability, capas->status);
             strcat(temp, capas->capability);
             remaining -= strlen(capas->capability);
             strcat(temp, "=");
@@ -519,12 +521,14 @@ OCStackResult BuildStringFromActionSet(OCActionSet* actionset, char** desc)
             remaining--;
         }
     }
-    //     as = as->next;
-    // }
 
     *desc = (char *) OCMalloc(1024 - remaining);
+    if(!*desc)
+    {
+        return OC_STACK_NO_MEMORY;
+    }
+
     strcpy(*desc, temp);
-    // printf("\t\tPlain Text = %s(%i)\n", *desc, 1024 - remaining);
 
     return OC_STACK_OK;
 }
@@ -532,27 +536,26 @@ OCStackResult BuildStringFromActionSet(OCActionSet* actionset, char** desc)
 OCStackApplicationResult ActionSetCB(void* context, OCDoHandle handle,
         OCClientResponse* clientResponse)
 {
-    printf("\n\n\tcallback is called\n\n");
+    OC_LOG(INFO, TAG, PCF("\n\n\tcallback is called\n\n"));
 
-    ClientRequstInfo *info = GetClientRequestInfo(clientRequstList, handle);
+    ClientRequestInfo *info = GetClientRequestInfo(clientRequestList, handle);
 
     if (info)
     {
-        int idx;
+        uint32_t idx = 0;
 
-        unsigned char *responseJson;
-        responseJson = (unsigned char *) OCMalloc(
-                (unsigned int) (strlen((char *) clientResponse->resJSONPayload) + 1));
+        char *responseJson = (char *) OCMalloc(
+                (unsigned int) (strlen( clientResponse->resJSONPayload) + 1));
 
         // We need the body of response.
         // Copy the body from the response
-        strcpy((char *) responseJson, ((char *) clientResponse->resJSONPayload
-                + OC_JSON_PREFIX_LEN));
+        strncpy((char *) responseJson, (clientResponse->resJSONPayload
+                + OC_JSON_PREFIX_LEN), strlen(clientResponse->resJSONPayload) + 1);
         idx = strlen((char *) responseJson) - OC_JSON_SUFFIX_LEN;
         // And insert NULL at the end of body.
         (responseJson[idx]) = 0;
 
-        OCEntityHandlerResponse response = { };
+        OCEntityHandlerResponse response = { };
         response.ehResult = OC_EH_OK;
         response.payload = responseJson;
         response.payloadSize = (unsigned int) strlen((char *) responseJson) + 1;
@@ -562,30 +565,25 @@ OCStackApplicationResult ActionSetCB(void* context, OCDoHandle handle,
 
         OCDoResponse(&response);
 
-        RemoveClientRequestInfo(&clientRequstList, info);
+        RemoveClientRequestInfo(&clientRequestList, info);
         OCFree(responseJson);
     }
 
-    // g_AggregateResponseHandle
-
     return OC_STACK_KEEP_TRANSACTION;
 }
 
 void ActionSetCD(void *context)
 {
-    // printf("\n\t\tCD is called\n");
-
-    // free( context );
 }
 
-OCStackResult BuildActionJSON(OCAction* action, unsigned char* bufferPtr, uint16_t *remaining)
+OCStackResult BuildActionJSON(OCAction* action, char* bufferPtr, uint16_t *remaining)
 {
     OCStackResult ret = OC_STACK_ERROR;
-    cJSON *json;
-    cJSON *body;
+    cJSON *json = NULL;
+    cJSON *body = NULL;
 
-    char *jsonStr;
-    uint16_t jsonLen;
+    char *jsonStr = NULL;
+    uint16_t jsonLen = 0;
 
     OC_LOG(INFO, TAG, PCF("Entering BuildActionJSON"));
     json = cJSON_CreateObject();
@@ -611,29 +609,29 @@ OCStackResult BuildActionJSON(OCAction* action, unsigned char* bufferPtr, uint16
     }
 
     cJSON_Delete(json);
-    free(jsonStr);
+    OCFree(jsonStr);
 
     return ret;
 }
 
-unsigned int GetNumOfTargetResource(OCAction *actionset)
+uint32_t GetNumOfTargetResource(OCAction *actionset)
 {
-    int numOfREsource = 0;
+    uint32_t numOfResource = 0;
 
     OCAction *pointerAction = actionset;
 
     while (pointerAction != NULL)
     {
-        numOfREsource++;
+        numOfResource++;
         pointerAction = pointerAction->next;
     }
 
-    return numOfREsource;
+    return numOfResource;
 }
 
-OCStackResult SendAction(OCDoHandle *handle, const char *targetUri, const unsigned char *action)
+OCStackResult SendAction(OCDoHandle *handle, const char *targetUri, const char *action)
 {
-    OCCallbackData cbdata = { 0 };
+    OCCallbackData cbdata = {  };
     cbdata.cb = &ActionSetCB;
     cbdata.cd = &ActionSetCD;
     cbdata.context = (void *) 0x99;
@@ -649,190 +647,187 @@ OCStackResult BuildCollectionGroupActionJSONResponse(OCMethod method/*OCEntityHa
     OCStackResult stackRet = OC_STACK_ERROR;
 
     OC_LOG(INFO, TAG, PCF("Group Action is requested."));
-    // if (stackRet == OC_STACK_OK)
-    {
-        char *doWhat = NULL;
-        char *details = NULL;
-
-        size_t bufferLength = 0;
-        unsigned char buffer[MAX_RESPONSE_LENGTH] = { 0 };
-        unsigned char *bufferPtr = NULL;
+    char *doWhat = NULL;
+    char *details = NULL;
 
-        bufferPtr = buffer;
+    size_t bufferLength = 0;
+    char buffer[MAX_RESPONSE_LENGTH] = { 0 };
+    char *bufferPtr = NULL;
 
-        OCResource * collResource = (OCResource *) ehRequest->resource;
+    bufferPtr = buffer;
 
-        char *jsonResponse;
+    OCResource * collResource = (OCResource *) ehRequest->resource;
 
-        ExtractKeyValueFromRequest((char *)ehRequest->reqJSONPayload, &doWhat, &details);
+    char *jsonResponse;
 
-        cJSON *json;
-        cJSON *format;
+    ExtractKeyValueFromRequest((char *)ehRequest->reqJSONPayload, &doWhat, &details);
 
+    cJSON *json;
+    cJSON *format;
 
-        if (method == OC_REST_PUT)
-        {
-            json = cJSON_CreateObject();
-            cJSON_AddStringToObject(json, "href", resource->uri);
-            cJSON_AddItemToObject(json, "rep", format = cJSON_CreateObject());
 
-            OC_LOG(INFO, TAG, PCF("Group Action[PUT]."));
+    if (method == OC_REST_PUT)
+    {
+        json = cJSON_CreateObject();
+        cJSON_AddStringToObject(json, "href", resource->uri);
+        cJSON_AddItemToObject(json, "rep", format = cJSON_CreateObject());
 
-            if(strcmp(doWhat, "ActionSet") == 0)
-            {
-                OCActionSet *actionSet;
-                BuildActionSetFromString(&actionSet, details);
+        OC_LOG(INFO, TAG, PCF("Group Action[PUT]."));
 
-                if(actionSet != NULL)
-                {
-                    AddActionSet(&resource->actionsetHead, actionSet);
-                    stackRet = OC_STACK_OK;
-                }
-                else
-                {
-                    stackRet = OC_STACK_ERROR;
-                }
+        if(strcmp(doWhat, "ActionSet") == 0)
+        {
+            OCActionSet *actionSet;
+            BuildActionSetFromString(&actionSet, details);
 
+            if(actionSet != NULL)
+            {
+                AddActionSet(&resource->actionsetHead, actionSet);
+                stackRet = OC_STACK_OK;
             }
-            else if (strcmp(doWhat, "DelActionSet") == 0)
+            else
             {
-                if (FindAndDeleteActionSet(&resource, details) == OC_STACK_OK)
-                {
-                    stackRet = OC_STACK_OK;
-                }
-                else
-                {
-                    stackRet = OC_STACK_ERROR;
-                }
+                stackRet = OC_STACK_ERROR;
             }
 
-            jsonResponse = cJSON_Print(json);
-            cJSON_Delete(json);
-
-            strcat((char *) bufferPtr, jsonResponse);
-
-            bufferLength = strlen((const char *) buffer);
-            if (bufferLength > 0)
+        }
+        else if (strncmp(doWhat, "DelActionSet", sizeof("DelActionSet")) == 0)
+        {
+            if (FindAndDeleteActionSet(&resource, details) == OC_STACK_OK)
             {
-                OCEntityHandlerResponse response = { 0 };
-                response.ehResult = OC_EH_OK;
-                response.payload = buffer;
-                response.payloadSize = bufferLength + 1;
-                response.persistentBufferFlag = 0;
-                response.requestHandle = (OCRequestHandle) ehRequest->requestHandle;
-                response.resourceHandle = (OCResourceHandle) collResource;
-                stackRet = OCDoResponse(&response);
+                stackRet = OC_STACK_OK;
+            }
+            else
+            {
+                stackRet = OC_STACK_ERROR;
             }
-
-            stackRet = OC_STACK_OK;
         }
 
-        if (method == OC_REST_POST)
+        jsonResponse = cJSON_Print(json);
+        cJSON_Delete(json);
+
+        strcat((char *) bufferPtr, jsonResponse);
+
+        bufferLength = strlen((const char *) buffer);
+        if (bufferLength > 0)
         {
-            OC_LOG(INFO, TAG, PCF("Group Action[POST]."));
+            OCEntityHandlerResponse response = { 0 };
+            response.ehResult = OC_EH_OK;
+            response.payload = buffer;
+            response.payloadSize = bufferLength + 1;
+            response.persistentBufferFlag = 0;
+            response.requestHandle = (OCRequestHandle) ehRequest->requestHandle;
+            response.resourceHandle = (OCResourceHandle) collResource;
+            stackRet = OCDoResponse(&response);
+        }
 
-            OCActionSet *actionset = NULL;
+        stackRet = OC_STACK_OK;
+    }
 
-            json = cJSON_CreateObject();
-            cJSON_AddStringToObject(json, "href", resource->uri);
+    if (method == OC_REST_POST)
+    {
+        OC_LOG(INFO, TAG, PCF("Group Action[POST]."));
 
-            if (strcmp(doWhat, "DoAction") == 0)
-            {
-                if (GetActionSet(details, resource->actionsetHead, &actionset) != OC_STACK_OK)
-                {
-                    OC_LOG(INFO, TAG, PCF("ERROR"));
-                    stackRet = OC_STACK_ERROR;
-                }
+        OCActionSet *actionset = NULL;
 
-                if (actionset == NULL)
-                {
-                    OC_LOG(INFO, TAG, PCF("ERROR"));
-                    stackRet = OC_STACK_ERROR;
-                }
-                else
-                {
+        json = cJSON_CreateObject();
+        cJSON_AddStringToObject(json, "href", resource->uri);
 
-                    OCAction *pointerAction = actionset->head;
+        if (strcmp(doWhat, "DoAction") == 0)
+        {
+            if (GetActionSet(details, resource->actionsetHead, &actionset) != OC_STACK_OK)
+            {
+                OC_LOG(INFO, TAG, PCF("ERROR"));
+                stackRet = OC_STACK_ERROR;
+            }
 
-                    unsigned int num = GetNumOfTargetResource(pointerAction);
+            if (actionset == NULL)
+            {
+                OC_LOG(INFO, TAG, PCF("ERROR"));
+                stackRet = OC_STACK_ERROR;
+            }
+            else
+            {
 
-                    ((OCServerRequest *) ehRequest->requestHandle)->ehResponseHandler =
-                            HandleAggregateResponse;
-                    ((OCServerRequest *) ehRequest->requestHandle)->numResponses = num + 1;
+                OCAction *pointerAction = actionset->head;
 
-                    while (pointerAction != NULL)
-                    {
-                        unsigned char actionDesc[MAX_RESPONSE_LENGTH] = { 0 };
-                        unsigned char* actionDescPtr = actionDesc;
-                        uint16_t remaining = MAX_RESPONSE_LENGTH;
+                uint32_t num = GetNumOfTargetResource(pointerAction);
 
-                        strncpy((char *) actionDescPtr, (const char *) OC_JSON_PREFIX,
-                            strlen((const char *) OC_JSON_PREFIX) + 1);
-                        BuildActionJSON(pointerAction, actionDescPtr, &remaining);
-                        strncat((char *) actionDescPtr, (const char *) OC_JSON_SUFFIX,
-                            strlen((const char *) OC_JSON_SUFFIX));
+                ((OCServerRequest *) ehRequest->requestHandle)->ehResponseHandler =
+                        HandleAggregateResponse;
+                ((OCServerRequest *) ehRequest->requestHandle)->numResponses = num + 1;
 
-                        ClientRequstInfo *info = (ClientRequstInfo *) OCMalloc(
-                                sizeof(ClientRequstInfo));
-                        memset(info, 0, sizeof(ClientRequstInfo));
+                while (pointerAction != NULL)
+                {
+                    char actionDesc[MAX_RESPONSE_LENGTH] = { 0 };
+                    char* actionDescPtr = actionDesc;
+                    uint16_t remaining = MAX_RESPONSE_LENGTH;
 
-                        info->collResource = resource;
-                        info->ehRequest = (OCServerRequest *) ehRequest->requestHandle;
+                    strncpy((char *) actionDescPtr, (const char *) OC_JSON_PREFIX,
+                        strlen((const char *) OC_JSON_PREFIX) + 1);
+                    BuildActionJSON(pointerAction, actionDescPtr, &remaining);
+                    strncat((char *) actionDescPtr, (const char *) OC_JSON_SUFFIX,
+                        strlen((const char *) OC_JSON_SUFFIX));
 
-                        SendAction(&info->required, pointerAction->resourceUri, actionDescPtr);
+                    ClientRequestInfo *info = (ClientRequestInfo *) OCMalloc(
+                            sizeof(ClientRequestInfo));
+                    memset(info, 0, sizeof(ClientRequestInfo));
 
-                        AddClientRequestInfo(&clientRequstList, info);
+                    info->collResource = resource;
+                    info->ehRequest = (OCServerRequest *) ehRequest->requestHandle;
 
-                        pointerAction = pointerAction->next;
-                    }
+                    SendAction(&info->required, pointerAction->resourceUri, actionDescPtr);
 
+                    AddClientRequestInfo(&clientRequestList, info);
 
-                    stackRet = OC_STACK_OK;
+                    pointerAction = pointerAction->next;
                 }
+
+
+                stackRet = OC_STACK_OK;
             }
-            else if (strcmp(doWhat, "GetActionSet") == 0)
+        }
+        else if (strcmp(doWhat, "GetActionSet") == 0)
+        {
+            char *plainText = NULL;
+            OCActionSet *actionset = NULL;
+
+            cJSON_AddItemToObject(json, "rep", format = cJSON_CreateObject());
+            GetActionSet(details, resource->actionsetHead, &actionset);
+            if (actionset != NULL)
             {
-                char *plainText = NULL;
-                OCActionSet *actionset = NULL;
+                BuildStringFromActionSet(actionset, &plainText);
 
-                cJSON_AddItemToObject(json, "rep", format = cJSON_CreateObject());
-                GetActionSet(details, resource->actionsetHead, &actionset);
-                if (actionset != NULL)
+                if (plainText != NULL)
                 {
-                    BuildStringFromActionSet(actionset, &plainText);
-
-                    if (plainText != NULL)
-                    {
-                        cJSON_AddStringToObject(format, "ActionSet", plainText);
-                    }
-
-                    stackRet = OC_STACK_OK;
+                    cJSON_AddStringToObject(format, "ActionSet", plainText);
                 }
+
+                stackRet = OC_STACK_OK;
             }
+        }
 
-            jsonResponse = cJSON_Print(json);
-            cJSON_Delete(json);
+        jsonResponse = cJSON_Print(json);
+        cJSON_Delete(json);
 
-            strcat((char *) bufferPtr, jsonResponse);
+        strcat((char *) bufferPtr, jsonResponse);
 
-            bufferLength = strlen((const char *) buffer);
-            if (bufferLength > 0)
-            {
-                OCEntityHandlerResponse response =
-                { 0 };
-                response.ehResult = OC_EH_OK;
-                response.payload = buffer;
-                response.payloadSize = bufferLength + 1;
-                response.persistentBufferFlag = 0;
-                response.requestHandle = (OCRequestHandle) ehRequest->requestHandle;
-                response.resourceHandle = (OCResourceHandle) collResource;
-                stackRet = OCDoResponse(&response);
-            }
+        bufferLength = strlen((const char *) buffer);
+        if (bufferLength > 0)
+        {
+            OCEntityHandlerResponse response = {};
+            response.ehResult = OC_EH_OK;
+            response.payload = buffer;
+            response.payloadSize = bufferLength + 1;
+            response.persistentBufferFlag = 0;
+            response.requestHandle = (OCRequestHandle) ehRequest->requestHandle;
+            response.resourceHandle = (OCResourceHandle) collResource;
+            stackRet = OCDoResponse(&response);
         }
-
-        OCFree(doWhat);
-        OCFree(details);
     }
 
+    OCFree(doWhat);
+    OCFree(details);
+
     return stackRet;
 }
+
index 4db2ba0..7da8c21 100644 (file)
@@ -22,7 +22,7 @@ ocstack.c.  It is not a system or end-to-end test.
 Unit Test Requirements:
 
 1. Install Google Test on a Linux build machine
-2. Create a file called "local.properties" in the 
+2. Create a file called "local.properties" in the
    root/csdk/stack/test.  local.properties is used
    by the makefile and specifies the path to the
    Google Test directory on the build machine.
@@ -31,7 +31,7 @@ Unit Test Requirements:
 
    local.properties should contain GTEST_DIR.
    For example:
-   
+
 
    GTEST_DIR := /home/johndoe/utils/gtest-1.7.0
 
@@ -40,7 +40,7 @@ Unit Test Requirements:
    If no interface is available, the unit tests will FAIL.
 4. To run the unit test, first build the C OCStack.
    At the time of this writing this was done by running
-   
+
    root/csdk/make deepclean
    root/csdk/make BUILD=release    *default
    root/csdk/make BUILD=debug
@@ -54,3 +54,4 @@ Unit Test Requirements:
    root/csdk/stack/test/release/stacktests
    root/csdk/stack/test/debug/stacktests
 
+
index 87aa8a0..fe38e51 100644 (file)
@@ -1,3 +1,23 @@
+#******************************************************************
+#
+# Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
 Import('env')
 import os
 import os.path
index 0a75156..66aa0c0 100644 (file)
@@ -23,3 +23,4 @@ LOCAL_SRC_FILES += ocstack.c
 LOCAL_SRC_FILES += stacktests.cpp
 
 
+
index 2345e08..3f51a4f 100644 (file)
@@ -32,3 +32,4 @@ PROGMEM
 "warning: only initialized variables can be placed into program memory area"
 This appears to be a known gcc bug - https://gcc.gnu.org/bugzilla/show_bug.cgi?id=34734
 
+