Merge branch 'master' into cloud-interface
authorJee Hyeok Kim <jihyeok13.kim@samsung.com>
Mon, 19 Sep 2016 04:19:41 +0000 (13:19 +0900)
committerJee Hyeok Kim <jihyeok13.kim@samsung.com>
Mon, 19 Sep 2016 06:11:21 +0000 (15:11 +0900)
Change-Id: I9af09877a796742be84589e70c7e3dec522422f4
Signed-off-by: Jee Hyeok Kim <jihyeok13.kim@samsung.com>
442 files changed:
.gitignore
android/android_api/SConscript
android/android_api/base/build.gradle
android/android_api/base/jni/Android.mk
android/android_api/base/jni/JniCaInterface.c
android/android_api/base/jni/JniCaInterface.h
android/android_api/base/jni/JniDisplayPinListener.cpp
android/android_api/base/jni/JniDisplayPinListener.h
android/android_api/base/jni/JniOcPlatform.cpp
android/android_api/base/jni/JniOcProvisioning.cpp
android/android_api/base/jni/JniOcProvisioning.h
android/android_api/base/jni/JniOcRepresentation.h
android/android_api/base/jni/JniOcSecureResource.cpp
android/android_api/base/jni/JniOcSecureResource.h
android/android_api/base/jni/JniOcStack.cpp
android/android_api/base/jni/JniOcStack.h
android/android_api/base/jni/JniOnResourceFoundListener.cpp
android/android_api/base/jni/JniProvisionResultListner.cpp
android/android_api/base/jni/JniProvisionResultListner.h
android/android_api/base/src/main/java/org/iotivity/base/EncodingType.java [new file with mode: 0644]
android/android_api/base/src/main/java/org/iotivity/base/OcProvisioning.java
android/android_api/base/src/main/java/org/iotivity/base/OcSecureResource.java
android/examples/provisioningclient/src/main/assets/rootca.crt [new file with mode: 0644]
android/examples/provisioningclient/src/main/java/org/iotivity/base/examples/provisioningclient/ProvisioningClient.java
android/examples/provisioningclient/src/main/java/org/iotivity/base/examples/provisioningclient/StringConstants.java
android/examples/simplebase/src/main/java/org/iotivity/base/examples/CloudFragment.java
android/examples/simplebase/src/main/java/org/iotivity/base/examples/Common.java
android/examples/simplebase/src/main/java/org/iotivity/base/examples/DrawerFragment.java
android/examples/simplebase/src/main/res/layout/fragment_cloud.xml
android/examples/simplebase/src/main/res/layout/input.xml [moved from android/examples/simplebase/src/main/res/layout/tcp_input.xml with 72% similarity]
android/examples/simplebase/src/main/res/values/strings.xml
auto_build.py
build_common/SConscript
build_common/android/SConscript
build_common/windows/SConscript
cloud/account/src/main/java/org/iotivity/cloud/accountserver/AccountServer.java
cloud/interface/src/main/java/org/iotivity/cloud/ciserver/DeviceServerSystem.java
cloud/messagequeue/README
cloud/messagequeue/server.properties
cloud/stack/src/main/java/org/iotivity/cloud/base/connector/CoapClient.java
cloud/stack/src/main/java/org/iotivity/cloud/base/connector/ConnectorPool.java
cloud/stack/src/main/java/org/iotivity/cloud/base/device/CoapDevice.java
extlibs/gtest/SConscript
extlibs/hippomocks.scons
extlibs/libcoap/SConscript [new file with mode: 0644]
extlibs/libstrophe/SConscript
extlibs/timer/timer.c
extlibs/timer/timer.h
extlibs/tinydtls/dtls.c
extlibs/tinydtls/tests/dtls-client.c
extlibs/tinydtls/tests/dtls-server.c
extlibs/tinydtls/tinydtls.h
extlibs/wksxmppxep/SConscript
gbsbuild.sh
iotivity.pc.in
plugins/src/SConscript
plugins/src/pluginlist.c
plugins/zigbee_wrapper/telegesis_wrapper/include/twsocketlist.h
resource/SConscript
resource/c_common/SConscript
resource/c_common/ocrandom/src/ocrandom.c
resource/c_common/ocrandom/test/SConscript
resource/c_common/ocrandom/test/android/randomtest.cpp [deleted file]
resource/c_common/ocrandom/test/randomtest.cpp [moved from resource/c_common/ocrandom/test/linux/randomtest.cpp with 82% similarity]
resource/c_common/octhread/include/octhread.h [new file with mode: 0644]
resource/c_common/octhread/src/noop/octhread.c [moved from resource/csdk/connectivity/common/src/camutex_noop.c with 56% similarity]
resource/c_common/octhread/src/posix/octhread.c [moved from resource/csdk/connectivity/common/src/camutex_pthreads.c with 71% similarity]
resource/c_common/octhread/src/windows/octhread.c [new file with mode: 0644]
resource/c_common/oic_malloc/test/SConscript
resource/c_common/oic_malloc/test/linux/oic_malloc_tests.cpp
resource/c_common/oic_string/include/oic_string.h
resource/c_common/oic_string/src/oic_string.c
resource/c_common/oic_string/test/SConscript
resource/c_common/oic_string/test/linux/oic_string_tests.cpp
resource/c_common/oic_time/src/oic_time.c
resource/c_common/oic_time/test/SConscript
resource/c_common/windows/SConscript
resource/c_common/windows/src/getopt.c
resource/csdk/SConscript
resource/csdk/connectivity/api/cacommon.h
resource/csdk/connectivity/api/cainterface.h
resource/csdk/connectivity/api/casecurityinterface.h
resource/csdk/connectivity/build/SConscript
resource/csdk/connectivity/build/tizen/gbsbuild.sh
resource/csdk/connectivity/build/tizen/packaging/com.oic.ca.spec
resource/csdk/connectivity/common/SConscript
resource/csdk/connectivity/common/inc/camutex.h [deleted file]
resource/csdk/connectivity/common/src/cathreadpool_pthreads.c
resource/csdk/connectivity/inc/ca_adapter_net_tls.h
resource/csdk/connectivity/inc/caadapternetdtls.h
resource/csdk/connectivity/inc/caadapterutils.h
resource/csdk/connectivity/inc/cablockwisetransfer.h
resource/csdk/connectivity/inc/camessagehandler.h
resource/csdk/connectivity/inc/caprotocolmessage.h
resource/csdk/connectivity/inc/caqueueingthread.h
resource/csdk/connectivity/inc/caretransmission.h
resource/csdk/connectivity/inc/catcpadapter.h
resource/csdk/connectivity/inc/catcpinterface.h
resource/csdk/connectivity/lib/libcoap-4.1.1/SConscript [deleted file]
resource/csdk/connectivity/lib/libcoap-4.1.1/async.c
resource/csdk/connectivity/lib/libcoap-4.1.1/block.c
resource/csdk/connectivity/lib/libcoap-4.1.1/coap_list.c
resource/csdk/connectivity/lib/libcoap-4.1.1/debug.c
resource/csdk/connectivity/lib/libcoap-4.1.1/encode.c
resource/csdk/connectivity/lib/libcoap-4.1.1/hashkey.c
resource/csdk/connectivity/lib/libcoap-4.1.1/include/coap/address.h [moved from resource/csdk/connectivity/lib/libcoap-4.1.1/address.h with 100% similarity]
resource/csdk/connectivity/lib/libcoap-4.1.1/include/coap/async.h [moved from resource/csdk/connectivity/lib/libcoap-4.1.1/async.h with 100% similarity]
resource/csdk/connectivity/lib/libcoap-4.1.1/include/coap/bits.h [moved from resource/csdk/connectivity/lib/libcoap-4.1.1/bits.h with 100% similarity]
resource/csdk/connectivity/lib/libcoap-4.1.1/include/coap/block.h [moved from resource/csdk/connectivity/lib/libcoap-4.1.1/block.h with 100% similarity]
resource/csdk/connectivity/lib/libcoap-4.1.1/include/coap/coap.h [moved from resource/csdk/connectivity/lib/libcoap-4.1.1/coap.h with 100% similarity]
resource/csdk/connectivity/lib/libcoap-4.1.1/include/coap/coap_list.h [moved from resource/csdk/connectivity/lib/libcoap-4.1.1/coap_list.h with 100% similarity]
resource/csdk/connectivity/lib/libcoap-4.1.1/include/coap/coap_time.h [moved from resource/csdk/connectivity/lib/libcoap-4.1.1/coap_time.h with 100% similarity]
resource/csdk/connectivity/lib/libcoap-4.1.1/include/coap/config.h [moved from resource/csdk/connectivity/lib/libcoap-4.1.1/config.h with 96% similarity]
resource/csdk/connectivity/lib/libcoap-4.1.1/include/coap/debug.h [moved from resource/csdk/connectivity/lib/libcoap-4.1.1/debug.h with 100% similarity]
resource/csdk/connectivity/lib/libcoap-4.1.1/include/coap/encode.h [moved from resource/csdk/connectivity/lib/libcoap-4.1.1/encode.h with 100% similarity]
resource/csdk/connectivity/lib/libcoap-4.1.1/include/coap/hashkey.h [moved from resource/csdk/connectivity/lib/libcoap-4.1.1/hashkey.h with 100% similarity]
resource/csdk/connectivity/lib/libcoap-4.1.1/include/coap/mem.h [moved from resource/csdk/connectivity/lib/libcoap-4.1.1/mem.h with 100% similarity]
resource/csdk/connectivity/lib/libcoap-4.1.1/include/coap/net.h [moved from resource/csdk/connectivity/lib/libcoap-4.1.1/net.h with 100% similarity]
resource/csdk/connectivity/lib/libcoap-4.1.1/include/coap/option.h [moved from resource/csdk/connectivity/lib/libcoap-4.1.1/option.h with 90% similarity]
resource/csdk/connectivity/lib/libcoap-4.1.1/include/coap/pdu.h [moved from resource/csdk/connectivity/lib/libcoap-4.1.1/pdu.h with 59% similarity]
resource/csdk/connectivity/lib/libcoap-4.1.1/include/coap/prng.h [moved from resource/csdk/connectivity/lib/libcoap-4.1.1/prng.h with 100% similarity]
resource/csdk/connectivity/lib/libcoap-4.1.1/include/coap/resource.h [moved from resource/csdk/connectivity/lib/libcoap-4.1.1/resource.h with 100% similarity]
resource/csdk/connectivity/lib/libcoap-4.1.1/include/coap/str.h [moved from resource/csdk/connectivity/lib/libcoap-4.1.1/str.h with 100% similarity]
resource/csdk/connectivity/lib/libcoap-4.1.1/include/coap/subscribe.h [moved from resource/csdk/connectivity/lib/libcoap-4.1.1/subscribe.h with 100% similarity]
resource/csdk/connectivity/lib/libcoap-4.1.1/include/coap/t_list.h [moved from resource/csdk/connectivity/lib/libcoap-4.1.1/t_list.h with 100% similarity]
resource/csdk/connectivity/lib/libcoap-4.1.1/include/coap/uri.h [moved from resource/csdk/connectivity/lib/libcoap-4.1.1/uri.h with 100% similarity]
resource/csdk/connectivity/lib/libcoap-4.1.1/include/coap/uthash.h [moved from resource/csdk/connectivity/lib/libcoap-4.1.1/uthash.h with 100% similarity]
resource/csdk/connectivity/lib/libcoap-4.1.1/include/coap/utlist.h [moved from resource/csdk/connectivity/lib/libcoap-4.1.1/utlist.h with 100% similarity]
resource/csdk/connectivity/lib/libcoap-4.1.1/net.c
resource/csdk/connectivity/lib/libcoap-4.1.1/option.c
resource/csdk/connectivity/lib/libcoap-4.1.1/pdu.c
resource/csdk/connectivity/lib/libcoap-4.1.1/resource.c
resource/csdk/connectivity/lib/libcoap-4.1.1/str.c
resource/csdk/connectivity/lib/libcoap-4.1.1/subscribe.c
resource/csdk/connectivity/lib/libcoap-4.1.1/uri.c
resource/csdk/connectivity/src/SConscript
resource/csdk/connectivity/src/adapter_util/ca_adapter_net_tls.c
resource/csdk/connectivity/src/adapter_util/caadapternetdtls.c
resource/csdk/connectivity/src/adapter_util/caadapterutils.c
resource/csdk/connectivity/src/adapter_util/cafragmentation.c
resource/csdk/connectivity/src/bt_edr_adapter/android/caedrclient.c
resource/csdk/connectivity/src/bt_edr_adapter/android/caedrnwmonitor.c
resource/csdk/connectivity/src/bt_edr_adapter/android/caedrserver.c
resource/csdk/connectivity/src/bt_edr_adapter/caedradapter.c
resource/csdk/connectivity/src/bt_edr_adapter/tizen/caedrclient.c
resource/csdk/connectivity/src/bt_edr_adapter/tizen/caedrserver.c
resource/csdk/connectivity/src/bt_le_adapter/android/caleclient.c
resource/csdk/connectivity/src/bt_le_adapter/android/calenwmonitor.c
resource/csdk/connectivity/src/bt_le_adapter/android/caleserver.c
resource/csdk/connectivity/src/bt_le_adapter/arduino/cableserver.cpp
resource/csdk/connectivity/src/bt_le_adapter/caleadapter.c
resource/csdk/connectivity/src/bt_le_adapter/linux/caleinterface.c
resource/csdk/connectivity/src/bt_le_adapter/linux/central.c
resource/csdk/connectivity/src/bt_le_adapter/linux/characteristic.c
resource/csdk/connectivity/src/bt_le_adapter/linux/client.c
resource/csdk/connectivity/src/bt_le_adapter/linux/context.h
resource/csdk/connectivity/src/bt_le_adapter/linux/peripheral.c
resource/csdk/connectivity/src/bt_le_adapter/linux/peripheral.h
resource/csdk/connectivity/src/bt_le_adapter/linux/recv.c
resource/csdk/connectivity/src/bt_le_adapter/linux/utils.c
resource/csdk/connectivity/src/bt_le_adapter/tizen/caleclient.c
resource/csdk/connectivity/src/bt_le_adapter/tizen/calenwmonitor.c
resource/csdk/connectivity/src/bt_le_adapter/tizen/caleserver.c
resource/csdk/connectivity/src/cablockwisetransfer.c
resource/csdk/connectivity/src/caconnectivitymanager.c
resource/csdk/connectivity/src/camessagehandler.c
resource/csdk/connectivity/src/caprotocolmessage.c
resource/csdk/connectivity/src/caqueueingthread.c
resource/csdk/connectivity/src/caretransmission.c
resource/csdk/connectivity/src/ip_adapter/android/caipnwmonitor.c
resource/csdk/connectivity/src/ip_adapter/caipadapter.c
resource/csdk/connectivity/src/ip_adapter/caipserver.c
resource/csdk/connectivity/src/ip_adapter/linux/caipnwmonitor.c
resource/csdk/connectivity/src/ip_adapter/tizen/caipnwmonitor.c
resource/csdk/connectivity/src/nfc_adapter/android/canfcserver.c
resource/csdk/connectivity/src/nfc_adapter/canfcadapter.c
resource/csdk/connectivity/src/ra_adapter/caraadapter.c
resource/csdk/connectivity/src/tcp_adapter/arduino/catcpserver_eth.cpp
resource/csdk/connectivity/src/tcp_adapter/catcpadapter.c
resource/csdk/connectivity/src/tcp_adapter/catcpserver.c
resource/csdk/connectivity/test/SConscript
resource/csdk/connectivity/test/cablocktransfertest.cpp
resource/csdk/connectivity/test/caprotocolmessagetest.cpp
resource/csdk/connectivity/test/catests.cpp
resource/csdk/connectivity/test/octhread_tests.cpp [moved from resource/csdk/connectivity/test/camutex_tests.cpp with 82% similarity]
resource/csdk/connectivity/util/src/camanager/android/caleautoconnector.c
resource/csdk/connectivity/util/src/camanager/android/camanagerdevice.c
resource/csdk/connectivity/util/src/camanager/android/camanagerdevice.h
resource/csdk/logger/include/logger.h
resource/csdk/logger/src/logger.c
resource/csdk/octbstack_product.def
resource/csdk/octbstack_product_secured.def [new file with mode: 0644]
resource/csdk/routing/src/routingmanager.c
resource/csdk/security/SConscript
resource/csdk/security/include/internal/aclresource.h
resource/csdk/security/include/internal/credresource.h
resource/csdk/security/include/internal/crlresource.h
resource/csdk/security/include/internal/doxmresource.h [changed mode: 0755->0644]
resource/csdk/security/include/internal/srmresourcestrings.h
resource/csdk/security/include/pkix_interface.h [new file with mode: 0644]
resource/csdk/security/include/securevirtualresourcetypes.h
resource/csdk/security/include/srmutility.h
resource/csdk/security/provisioning/SConscript
resource/csdk/security/provisioning/ck_manager/include/ckm_info.h
resource/csdk/security/provisioning/ck_manager/sample/SConscript
resource/csdk/security/provisioning/include/cloud/occloudprovisioning.h [new file with mode: 0644]
resource/csdk/security/provisioning/include/cloud/utils.h [new file with mode: 0644]
resource/csdk/security/provisioning/include/internal/secureresourceprovider.h
resource/csdk/security/provisioning/include/pmutility.h
resource/csdk/security/provisioning/sample/README-cloud.txt [new file with mode: 0644]
resource/csdk/security/provisioning/sample/SConscript
resource/csdk/security/provisioning/sample/cloud.dat [new file with mode: 0644]
resource/csdk/security/provisioning/sample/cloud.json [new file with mode: 0644]
resource/csdk/security/provisioning/sample/cloud/cloudAuth.c [new file with mode: 0644]
resource/csdk/security/provisioning/sample/cloud/cloudAuth.h [new file with mode: 0644]
resource/csdk/security/provisioning/sample/cloud/cloudCommon.h [new file with mode: 0644]
resource/csdk/security/provisioning/sample/cloud/cloudDiscovery.c [new file with mode: 0644]
resource/csdk/security/provisioning/sample/cloud/cloudDiscovery.h [new file with mode: 0644]
resource/csdk/security/provisioning/sample/cloud/cloudWrapper.c [new file with mode: 0644]
resource/csdk/security/provisioning/sample/cloud/cloudWrapper.h [new file with mode: 0644]
resource/csdk/security/provisioning/sample/cloudClient.c [new file with mode: 0644]
resource/csdk/security/provisioning/sample/provisioningclient.c
resource/csdk/security/provisioning/sample/rootca.crt [new file with mode: 0644]
resource/csdk/security/provisioning/sample/sampleserver_justworks.cpp
resource/csdk/security/provisioning/sample/sampleserver_randompin.cpp
resource/csdk/security/provisioning/src/cloud/aclgroup.c [new file with mode: 0644]
resource/csdk/security/provisioning/src/cloud/aclid.c [new file with mode: 0644]
resource/csdk/security/provisioning/src/cloud/aclinvite.c [new file with mode: 0644]
resource/csdk/security/provisioning/src/cloud/crl.c [new file with mode: 0644]
resource/csdk/security/provisioning/src/cloud/csr.c [new file with mode: 0644]
resource/csdk/security/provisioning/src/cloud/utils.c [new file with mode: 0644]
resource/csdk/security/provisioning/src/ownershiptransfermanager.c
resource/csdk/security/provisioning/src/pmutility.c
resource/csdk/security/provisioning/src/secureresourceprovider.c
resource/csdk/security/provisioning/unittest/SConscript
resource/csdk/security/provisioning/unittest/provisioningdatabasemanager.cpp
resource/csdk/security/src/aclresource.c
resource/csdk/security/src/amsmgr.c
resource/csdk/security/src/credresource.c
resource/csdk/security/src/crlresource.c
resource/csdk/security/src/directpairing.c
resource/csdk/security/src/doxmresource.c
resource/csdk/security/src/dpairingresource.c
resource/csdk/security/src/iotvticalendar.c
resource/csdk/security/src/pconfresource.c
resource/csdk/security/src/pkix_interface.c [new file with mode: 0644]
resource/csdk/security/src/psinterface.c
resource/csdk/security/src/resourcemanager.c
resource/csdk/security/src/secureresourcemanager.c
resource/csdk/security/src/srmresourcestrings.c
resource/csdk/security/src/verresource.c
resource/csdk/security/tool/SConscript
resource/csdk/security/unittest/SConscript
resource/csdk/security/unittest/aclresourcetest.cpp
resource/csdk/security/unittest/pstatresource.cpp
resource/csdk/security/unittest/securityresourcemanager.cpp
resource/csdk/stack/include/internal/ocstackinternal.h
resource/csdk/stack/include/ocpayload.h
resource/csdk/stack/include/ocstack.h
resource/csdk/stack/include/ocstackconfig.h
resource/csdk/stack/include/octypes.h
resource/csdk/stack/include/payload_logging.h
resource/csdk/stack/samples/linux/SimpleClientServer/SConscript
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/occlientcoll.cpp
resource/csdk/stack/samples/linux/SimpleClientServer/occlientslow.cpp
resource/csdk/stack/samples/linux/SimpleClientServer/ocserver.cpp
resource/csdk/stack/samples/linux/SimpleClientServer/ocserverbasicops.cpp
resource/csdk/stack/samples/linux/SimpleClientServer/ocservercoll.cpp
resource/csdk/stack/samples/linux/SimpleClientServer/ocserverslow.cpp
resource/csdk/stack/samples/linux/secure/ocamsservice.cpp
resource/csdk/stack/samples/linux/secure/occlientbasicops.cpp
resource/csdk/stack/samples/linux/secure/occlientdirectpairing.cpp
resource/csdk/stack/samples/linux/secure/ocserverbasicops.cpp
resource/csdk/stack/samples/tizen/SimpleClientServer/SConscript
resource/csdk/stack/samples/tizen/SimpleClientServer/packaging/com.oic.ri.sample.spec
resource/csdk/stack/samples/tizen/SimpleClientServer/scons/SConscript
resource/csdk/stack/samples/tizen/build/SConscript
resource/csdk/stack/samples/tizen/build/gbsbuild.sh
resource/csdk/stack/samples/tizen/build/packaging/com.oic.ri.spec
resource/csdk/stack/samples/tizen/build/scons/SConscript
resource/csdk/stack/src/occlientcb.c
resource/csdk/stack/src/ocobserve.c
resource/csdk/stack/src/ocpayload.c
resource/csdk/stack/src/ocpayloadconvert.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/src/oickeepalive.c
resource/csdk/stack/src/oicresourcedirectory.c
resource/csdk/stack/src/rdpayload.c
resource/csdk/stack/test/SConscript
resource/docs/c-doc/Doxyfile
resource/examples/lightserver.cpp
resource/examples/presenceserver.cpp
resource/examples/simpleclient.cpp
resource/examples/simpleclientHQ.cpp
resource/examples/simpleserver.cpp
resource/examples/simpleserverHQ.cpp
resource/examples/threadingsample.cpp
resource/include/AttributeValue.h
resource/include/OCRepresentation.h
resource/provisioning/SConscript
resource/provisioning/examples/SConscript
resource/src/InProcClientWrapper.cpp
resource/src/OCAccountManager.cpp
resource/src/OCApi.cpp
resource/src/OCRepresentation.cpp
resource/src/OCResource.cpp
resource/src/SConscript
resource/unit_tests.scons
resource/unittests/OCRepresentationEncodingTest.cpp
resource/unittests/OCRepresentationTest.cpp
resource/unittests/OCResourceResponseTest.cpp
resource/unittests/SConscript
run.bat
scons_script_how_to.txt
service/SConscript
service/coap-http-proxy/SConscript [new file with mode: 0644]
service/coap-http-proxy/include/CoapHttpHandler.h [new file with mode: 0644]
service/coap-http-proxy/include/CoapHttpMap.h [new file with mode: 0644]
service/coap-http-proxy/include/CoapHttpParser.h [new file with mode: 0644]
service/coap-http-proxy/samples/SConscript [new file with mode: 0644]
service/coap-http-proxy/samples/proxy_main.c [new file with mode: 0644]
service/coap-http-proxy/src/CoapHttpHandler.c [new file with mode: 0644]
service/coap-http-proxy/src/CoapHttpMap.c [new file with mode: 0644]
service/coap-http-proxy/src/CoapHttpParser.c [new file with mode: 0644]
service/easy-setup/mediator/richsdk/SConscript
service/easy-setup/mediator/richsdk/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/CloudProp.java [changed mode: 0644->0755]
service/easy-setup/mediator/richsdk/android/EasySetupCore/src/main/java/org/iotivity/service/easysetup/mediator/DeviceProp.java [changed mode: 0644->0755]
service/easy-setup/mediator/richsdk/android/EasySetupCore/src/main/jni/JniEasySetup.cpp
service/easy-setup/mediator/richsdk/android/SConscript
service/easy-setup/mediator/richsdk/inc/ESRichCommon.h
service/easy-setup/mediator/richsdk/src/EnrolleeSecurity.cpp
service/easy-setup/mediator/richsdk/src/EnrolleeSecurity.h [changed mode: 0644->0755]
service/easy-setup/mediator/richsdk/src/RemoteEnrollee.cpp
service/easy-setup/sampleapp/enrollee/tizen-sdb/EnrolleeSample/build/SConscript
service/easy-setup/sampleapp/enrollee/tizen-sdb/EnrolleeSample/build/tizen/SConscript
service/easy-setup/sampleapp/enrollee/tizen-sdb/EnrolleeSample/build/tizen/gbsbuild.sh
service/easy-setup/sampleapp/enrollee/tizen-sdb/EnrolleeSample/packaging/com.oic.es.sample.spec
service/easy-setup/sampleapp/mediator/android/EasySetup/app/src/main/assets/oic_svr_db_client.dat [changed mode: 0644->0755]
service/easy-setup/sampleapp/mediator/android/EasySetup/app/src/main/java/org/iotivity/service/easysetup/EasysetupActivity.java
service/easy-setup/sampleapp/mediator/android/SConscript
service/easy-setup/sampleapp/mediator/linux/richsdk_sample/mediator_cpp.cpp
service/easy-setup/sampleapp/mediator/linux/richsdk_sample/oic_svr_db_client.dat [changed mode: 0644->0755]
service/notification/SConscript
service/notification/android/SConscript [changed mode: 0644->0755]
service/notification/android/notification-service/src/main/java/org/iotivity/service/ns/consumer/ConsumerService.java
service/notification/android/notification-service/src/main/java/org/iotivity/service/ns/consumer/Provider.java
service/notification/android/notification-service/src/main/java/org/iotivity/service/ns/provider/Consumer.java
service/notification/android/notification-service/src/main/java/org/iotivity/service/ns/provider/ProviderService.java
service/notification/android/notification-service/src/main/jni/consumer/JniNotificationConsumer.cpp
service/notification/android/notification-service/src/main/jni/consumer/JniNotificationConsumer.h
service/notification/android/notification-service/src/main/jni/provider/JniNotificationProvider.cpp
service/notification/android/notification-service/src/main/jni/provider/JniNotificationProvider.h
service/notification/cpp-wrapper/SConscript
service/notification/cpp-wrapper/common/NSMessage.cpp
service/notification/cpp-wrapper/common/NSMessage.h
service/notification/cpp-wrapper/common/NSSyncInfo.cpp
service/notification/cpp-wrapper/common/NSTopicsList.cpp
service/notification/cpp-wrapper/common/NSTopicsList.h
service/notification/cpp-wrapper/common/NSUtils.h
service/notification/cpp-wrapper/consumer/SConscript
service/notification/cpp-wrapper/consumer/inc/NSConsumerService.h
service/notification/cpp-wrapper/consumer/inc/NSProvider.h
service/notification/cpp-wrapper/consumer/src/NSConsumerService.cpp
service/notification/cpp-wrapper/consumer/src/NSProvider.cpp
service/notification/cpp-wrapper/examples/linux/notificationserviceconsumer.cpp
service/notification/cpp-wrapper/examples/linux/notificationserviceprovider.cpp
service/notification/cpp-wrapper/provider/SConscript
service/notification/cpp-wrapper/provider/inc/NSConsumer.h
service/notification/cpp-wrapper/provider/inc/NSProviderService.h
service/notification/cpp-wrapper/provider/src/NSConsumer.cpp
service/notification/cpp-wrapper/provider/src/NSProviderService.cpp
service/notification/cpp-wrapper/unittest/NSConsumerServiceTest.cpp
service/notification/cpp-wrapper/unittest/NSProviderServiceSimulator.h
service/notification/cpp-wrapper/unittest/NSProviderServiceTest.cpp
service/notification/cpp-wrapper/unittest/SConscript
service/notification/examples/android/NotiConsumerExample/app/build.gradle
service/notification/examples/android/NotiConsumerExample/app/src/main/java/com/sec/noticonsumerexample/ConsumerProxy.java
service/notification/examples/android/NotiConsumerExample/app/src/main/java/com/sec/noticonsumerexample/MainActivity.java
service/notification/examples/android/NotiConsumerExample/app/src/main/res/layout/activity_main.xml
service/notification/examples/android/NotiConsumerExample/iotivity-armeabi-notification-service-debug/iotivity-armeabi-notification-service-debug.aar [deleted file]
service/notification/examples/android/NotiConsumerExample/iotivity-armeabi-notification-service-release/build.gradle [moved from service/notification/examples/android/NotiConsumerExample/iotivity-armeabi-notification-service-debug/build.gradle with 84% similarity]
service/notification/examples/android/NotiConsumerExample/iotivity-base-armeabi-debug/build.gradle [deleted file]
service/notification/examples/android/NotiConsumerExample/iotivity-base-armeabi-debug/iotivity-base-armeabi-debug.aar [deleted file]
service/notification/examples/android/NotiConsumerExample/iotivity-base-armeabi-release/build.gradle [new file with mode: 0755]
service/notification/examples/android/NotiConsumerExample/settings.gradle
service/notification/examples/android/NotiProviderExample/app/src/main/java/com/sec/notiproviderexample/MainActivity.java
service/notification/examples/android/NotiProviderExample/app/src/main/java/com/sec/notiproviderexample/ProviderProxy.java
service/notification/examples/linux/SConscript
service/notification/examples/linux/notificationconsumer.c
service/notification/examples/linux/notificationprovider.c
service/notification/include/NSCommon.h
service/notification/include/NSConsumerInterface.h
service/notification/include/NSProviderInterface.h
service/notification/src/common/NSConstants.h
service/notification/src/common/NSStructs.h
service/notification/src/consumer/NSConsumerCommon.c
service/notification/src/consumer/NSConsumerCommon.h
service/notification/src/consumer/NSConsumerCommunication.c
service/notification/src/consumer/NSConsumerDiscovery.c
service/notification/src/consumer/NSConsumerInterface.c
service/notification/src/consumer/NSConsumerInternalTaskController.c
service/notification/src/consumer/NSConsumerInternalTaskController.h
service/notification/src/consumer/NSConsumerMemoryCache.c
service/notification/src/consumer/NSConsumerMemoryCache.h
service/notification/src/consumer/NSConsumerNetworkEventListener.c
service/notification/src/consumer/NSConsumerScheduler.c
service/notification/src/provider/NSProviderCallbackResponse.c
service/notification/src/provider/NSProviderDiscovery.c
service/notification/src/provider/NSProviderInterface.c
service/notification/src/provider/NSProviderListener.c
service/notification/src/provider/NSProviderMemoryCache.c
service/notification/src/provider/NSProviderMemoryCache.h
service/notification/src/provider/NSProviderNotification.c
service/notification/src/provider/NSProviderNotification.h
service/notification/src/provider/NSProviderResource.c
service/notification/src/provider/NSProviderResource.h
service/notification/src/provider/NSProviderSubscription.c
service/notification/src/provider/NSProviderSubscription.h
service/notification/src/provider/NSProviderSystem.c
service/notification/src/provider/NSProviderSystem.h
service/notification/src/provider/NSProviderTopic.c
service/notification/src/provider/NSProviderTopic.h
service/notification/unittest/NSConsumerSimulator.h
service/notification/unittest/NSConsumerTest.cpp
service/notification/unittest/NSProviderSimulator.h
service/notification/unittest/NSProviderTest.cpp
service/notification/unittest/SConscript
service/resource-container/src/Configuration.cpp
service/resource-container/unittests/ResourceContainerTest.cpp
service/resource-container/unittests/ResourceContainerTestSimulator.h
service/resource-encapsulation/examples/android/RESampleClientApp/app/build.gradle
service/resource-encapsulation/examples/android/RESampleServerApp/app/build.gradle
service/resource-encapsulation/examples/linux/SampleResourceServer.cpp [changed mode: 0755->0644]
service/resource-encapsulation/src/resourceBroker/src/ResourceBroker.cpp
service/resource-encapsulation/src/serverBuilder/unittests/RCSResourceObjectTest.cpp
tools/tizen/iotivity.spec

index 62afd32..03d48b2 100644 (file)
@@ -37,6 +37,9 @@ resource/csdk/stack/samples/linux/SimpleClientServer/release/
 
 resource/csdk/connectivity/build/out/
 
+# Ignore autogenerated files
+resource/c_common/iotivity_config.h
+
 resource/oc_logger/bin/
 resource/oc_logger/lib/
 resource/oc_logger/samples/linux/release/
@@ -92,6 +95,7 @@ platform
 iotivity.pc
 
 # Ignore downloaded dependencies
+extlibs/libcoap/libcoap
 extlibs/gtest/gtest-*
 extlibs/hippomocks-master/
 extlibs/master.zip
index 75da41e..895ebb6 100644 (file)
@@ -16,6 +16,11 @@ if env.get('WITH_CLOUD'):
 else:
        ANDROID_CLOUD=0
 
+if env.get('WITH_TCP'):
+       ANDROID_TCP=1
+else:
+       ANDROID_TCP=0
+
 ANDROID_MQ = env.get('WITH_MQ')
 ANDROID_MQ_SUB = 0
 ANDROID_MQ_PUB = 0
@@ -83,11 +88,11 @@ def ensure_libs(target, source, env):
 
 # build android_api
 jdk_env = Environment(ENV=os.environ)
-jdk_env['BUILDERS']['Gradle'] = Builder(action = env.get('ANDROID_GRADLE') + ' build -b' + os.getcwd()+'/build.gradle -PWITH_TRANSPORT_EDR=%s -PWITH_TRANSPORT_BLE=%s -PWITH_TRANSPORT_NFC=%s -PTARGET_ARCH=%s -PRELEASE=%s -PSECURED=%s -DSECURE=%s -PWITH_CLOUD=%s -PRD_MODE=%s -PWITH_MQ_PUB=%s -PWITH_MQ_SUB=%s -PWITH_MQ_BROKER=%s --stacktrace' %(ANDROID_TRANSPORT_EDR, ANDROID_TRANSPORT_BLE, ANDROID_TRANSPORT_NFC, ANDROID_TARGET_ARCH, ANDROID_RELEASE, ANDROID_SECURED, ANDROID_SECURED, ANDROID_CLOUD, ANDROID_RD_MODE, ANDROID_MQ_PUB, ANDROID_MQ_SUB, ANDROID_MQ_BROKER), emitter = ensure_libs)
+jdk_env['BUILDERS']['Gradle'] = Builder(action = env.get('ANDROID_GRADLE') + ' build -b' + os.getcwd()+'/build.gradle -PWITH_TRANSPORT_EDR=%s -PWITH_TRANSPORT_BLE=%s -PWITH_TRANSPORT_NFC=%s -PTARGET_ARCH=%s -PRELEASE=%s -PSECURED=%s -DSECURE=%s -PWITH_CLOUD=%s -PRD_MODE=%s -PWITH_MQ_PUB=%s -PWITH_MQ_SUB=%s -PWITH_MQ_BROKER=%s -PWITH_TCP=%s --stacktrace' %(ANDROID_TRANSPORT_EDR, ANDROID_TRANSPORT_BLE, ANDROID_TRANSPORT_NFC, ANDROID_TARGET_ARCH, ANDROID_RELEASE, ANDROID_SECURED, ANDROID_SECURED, ANDROID_CLOUD, ANDROID_RD_MODE, ANDROID_MQ_PUB, ANDROID_MQ_SUB, ANDROID_MQ_BROKER, ANDROID_TCP), emitter = ensure_libs)
 jdk_env['BUILD_DIR'] = env.get('BUILD_DIR')
 cmdBuildApi=jdk_env.Gradle(target="base/objs", source="base/src/main/java/org/iotivity/base/OcResource.java")
 
-jdk_env['BUILDERS']['Gradle'] = Builder(action = env.get('ANDROID_GRADLE') + ' build -b' + 'android/examples/build.gradle -DWITH_TRANSPORT_EDR=%s -DWITH_TRANSPORT_BLE=%s -DWITH_TRANSPORT_NFC=%s -PTARGET_ARCH=%s -PRELEASE=%s -PSECURED=%s -DSECURE=%s -PWITH_CLOUD=%s -PRD_MODE=%s -PWITH_MQ_PUB=%s -PWITH_MQ_SUB=%s -PWITH_MQ_BROKER=%s --stacktrace' %(ANDROID_TRANSPORT_EDR, ANDROID_TRANSPORT_BLE, ANDROID_TRANSPORT_NFC, ANDROID_TARGET_ARCH, ANDROID_RELEASE, ANDROID_SECURED, ANDROID_SECURED, ANDROID_CLOUD, ANDROID_RD_MODE, ANDROID_MQ_PUB, ANDROID_MQ_SUB, ANDROID_MQ_BROKER))
+jdk_env['BUILDERS']['Gradle'] = Builder(action = env.get('ANDROID_GRADLE') + ' build -b' + 'android/examples/build.gradle -DWITH_TRANSPORT_EDR=%s -DWITH_TRANSPORT_BLE=%s -DWITH_TRANSPORT_NFC=%s -PTARGET_ARCH=%s -PRELEASE=%s -PSECURED=%s -DSECURE=%s -PWITH_CLOUD=%s -PRD_MODE=%s -PWITH_MQ_PUB=%s -PWITH_MQ_SUB=%s -PWITH_MQ_BROKER=%s -PWITH_TCP=%s --stacktrace' %(ANDROID_TRANSPORT_EDR, ANDROID_TRANSPORT_BLE, ANDROID_TRANSPORT_NFC, ANDROID_TARGET_ARCH, ANDROID_RELEASE, ANDROID_SECURED, ANDROID_SECURED, ANDROID_CLOUD, ANDROID_RD_MODE, ANDROID_MQ_PUB, ANDROID_MQ_SUB, ANDROID_MQ_BROKER, ANDROID_TCP))
 cmdBuildExamples=jdk_env.Gradle(target="../examples/devicediscoveryclient/apk", source="../examples/devicediscoveryclient/src/main/java/org/iotivity/base/examples/DeviceDiscoveryClient.java")
 
 # android examples require android api to be built before being invoked
index 4ea654c..855418d 100755 (executable)
@@ -41,8 +41,9 @@ android {
         minSdkVersion 21\r
         targetSdkVersion 21\r
         versionCode 1\r
-        versionName "1.1.1"\r
+        versionName "1.2.0"\r
         buildConfigField 'int', 'SECURED', SECURED\r
+        buildConfigField 'int', 'WITH_TCP', WITH_TCP\r
         buildConfigField 'int', 'WITH_CLOUD', WITH_CLOUD\r
         buildConfigField "int", 'WITH_MQ_PUB', WITH_MQ_PUB\r
         buildConfigField "int", 'WITH_MQ_SUB', WITH_MQ_SUB\r
@@ -119,7 +120,7 @@ task buildNative(type: Exec) {
         //for windows use 'ndk-build.cmd'\r
         //def ndkBuild = new File(System.env.ANDROID_NDK_HOME, 'ndk-build.cmd')\r
         def ndkBuild = new File(System.env.ANDROID_NDK_HOME, 'ndk-build')
-        commandLine ndkBuild, "APP_ABI=$TARGET_ARCH", "APP_OPTIM=$RELEASE", "SECURE=$SECURED", "WITH_CLOUD=$WITH_CLOUD", "RD_MODE=$RD_MODE", "WITH_MQ_PUB=$WITH_MQ_PUB", "WITH_MQ_SUB=$WITH_MQ_SUB", "WITH_MQ_BROKER=$WITH_MQ_BROKER"
+        commandLine ndkBuild, "APP_ABI=$TARGET_ARCH", "APP_OPTIM=$RELEASE", "SECURE=$SECURED", "WITH_CLOUD=$WITH_CLOUD", "RD_MODE=$RD_MODE", "WITH_MQ_PUB=$WITH_MQ_PUB", "WITH_MQ_SUB=$WITH_MQ_SUB", "WITH_MQ_BROKER=$WITH_MQ_BROKER", "WITH_TCP=$WITH_TCP"\r
     } else {\r
         println '##################'\r
         println 'Skipping NDK build'\r
index b59283b..d0426e0 100644 (file)
@@ -2,6 +2,7 @@ LOCAL_PATH := $(call my-dir)
 TARGET_ARCH_ABI := $(APP_ABI)\r
 SECURED := $(SECURE)\r
 WITH_CLOUD := $(WITH_CLOUD)\r
+WITH_TCP := $(WITH_TCP)\r
 WITH_MQ_PUB := $(WITH_MQ_PUB)\r
 WITH_MQ_SUB := $(WITH_MQ_SUB)\r
 WITH_MQ_BROKER := $(WITH_MQ_BROKER)\r
@@ -52,6 +53,7 @@ LOCAL_SRC_FILES := JniCaInterface.c
 LOCAL_STATIC_LIBRARIES := libandroid-ca\r
 LOCAL_LDLIBS := -llog\r
 LOCAL_C_INCLUDES += $(OIC_SRC_PATH)/csdk/connectivity/api\r
+LOCAL_C_INCLUDES += $(OIC_SRC_PATH)/c_common\r
 include $(BUILD_SHARED_LIBRARY)\r
 \r
 include $(CLEAR_VARS)\r
@@ -63,6 +65,11 @@ ifeq ($(WITH_CLOUD), 1)
     LOCAL_CPPFLAGS += -DWITH_CLOUD\r
 endif\r
 \r
+ifeq ($(WITH_TCP), 1)\r
+    LOCAL_CPPFLAGS += -DWITH_TCP\r
+    LOCAL_CPPFLAGS += -D__WITH_TLS__\r
+endif\r
+\r
 MQ_FLAG = 0\r
 ifeq ($(WITH_MQ_PUB), 1)\r
 LOCAL_CFLAGS += -DWITH_MQ -DMQ_PUBLISHER\r
@@ -156,5 +163,6 @@ LOCAL_C_INCLUDES += $(OIC_SRC_PATH)/csdk/security/provisioning/include/internal
 LOCAL_C_INCLUDES += $(OIC_SRC_PATH)/csdk/security/include\r
 LOCAL_C_INCLUDES += $(OIC_SRC_PATH)/csdk/security/include/internal\r
 LOCAL_C_INCLUDES += $(OIC_SRC_PATH)/csdk/connectivity/api\r
+LOCAL_C_INCLUDES += $(OIC_SRC_PATH)/csdk/connectivity/inc/pkix\r
 LOCAL_C_INCLUDES += $(OIC_SRC_PATH)/csdk/connectivity/lib/libcoap-4.1.1\r
 include $(BUILD_SHARED_LIBRARY)\r
index 1e20461..2e7eb47 100644 (file)
@@ -1,25 +1,22 @@
-/*
-* //******************************************************************
-* //
-* // Copyright 2015 Intel Corporation.
-* //
-* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-* //
-* // 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.
-* //
-* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-*/
-
+//******************************************************************
+//
+// Copyright 2015 Intel Corporation.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 #include <jni.h>
 #include <android/log.h>
 #include <stdio.h>
@@ -247,12 +244,6 @@ Java_org_iotivity_ca_CaInterface_caManagerTerminate(JNIEnv *env, jclass clazz)
         (*env)->DeleteGlobalRef(env, g_jni_cls_enum);
         g_jni_cls_enum = NULL;
     }
-
-    if (g_jni_mid_enum)
-    {
-        (*env)->DeleteGlobalRef(env, g_jni_mid_enum);
-        g_jni_mid_enum = NULL;
-    }
 }
 
 JNIEXPORT void JNICALL
@@ -261,6 +252,11 @@ Java_org_iotivity_ca_CaInterface_caManagerSetAutoConnectionDeviceInfo(JNIEnv *en
                                                                       jstring jaddress)
 {
     LOGI("CaManager_setAutoConnectionDeviceInfo");
+    if (!jaddress)
+    {
+        LOGE("jaddress is null");
+        return;
+    }
 
     const char* address = (*env)->GetStringUTFChars(env, jaddress, NULL);
     if (!address)
@@ -280,6 +276,11 @@ Java_org_iotivity_ca_CaInterface_caManagerUnsetAutoConnectionDeviceInfo(JNIEnv *
                                                                         jstring jaddress)
 {
     LOGI("CaManager_unsetAutoConnectionDeviceInfo");
+    if (!jaddress)
+    {
+        LOGE("jaddress is null");
+        return;
+    }
 
     const char* address = (*env)->GetStringUTFChars(env, jaddress, NULL);
     if (!address)
index 2e8ba5b..264c03d 100644 (file)
@@ -1,24 +1,23 @@
-/*
-* //******************************************************************
-* //
-* // Copyright 2015 Intel Corporation.
-* //
-* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-* //
-* // 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.
-* //
-* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-*/
+//******************************************************************
+//
+// Copyright 2015 Intel Corporation.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
 #include <jni.h>
 // THIS FILE IS SUBJECT TO CHANGE DUE TO THE ONGOING DEVELOPMENT OF THE CA FOR ANDROID
 // DO NOT REVIEW THIS FILE
index 1705bdf..c5decf0 100644 (file)
@@ -1,24 +1,22 @@
-/*
-* //******************************************************************
-* //
-* // Copyright 2015 Samsung Electronics 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.
-* //
-* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-*/
+//******************************************************************
+//
+// Copyright 2015 Samsung Electronics 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 #include "JniDisplayPinListener.h"
 #include "oic_string.h"
 #include "oic_malloc.h"
index 67c9752..b4fdf9f 100644 (file)
@@ -1,24 +1,22 @@
-/*
-* //******************************************************************
-* //
-* // Copyright 2015 Samsung Electronics 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.
-* //
-* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-*/
+//******************************************************************
+//
+// Copyright 2015 Samsung Electronics 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 #include <jni.h>
 #include "JniOcStack.h"
 #include "OCProvisioningManager.h"
index da0aea3..5f0faa5 100644 (file)
@@ -1627,10 +1627,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_registerDeviceInfo0(
     }
 
     OCDeviceInfo deviceInfo;
+    memset(&deviceInfo, 0, sizeof(deviceInfo));
     try
     {
         DuplicateString(&deviceInfo.deviceName, env->GetStringUTFChars(jDeviceName, nullptr));
-        deviceInfo.types = NULL;
 
         jsize len = env->GetArrayLength(jDeviceTypes);
         for (jsize i = 0; i < len; ++i)
index 52d5bc9..5d8db50 100644 (file)
@@ -93,7 +93,7 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcProvisioning_ownershipTransferCB
             }
             else
             {
-                result = OC_STACK_ERROR;
+                result = OC_STACK_INVALID_CALLBACK;
             }
         }
 
@@ -267,7 +267,7 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcProvisioning_setDisplayPinListen
 
     if (!jListener)
     {
-        ThrowOcException(OC_STACK_INVALID_PARAM, "displayPinListener can't be null");
+        ThrowOcException(OC_STACK_INVALID_CALLBACK, "displayPinListener can't be null");
         return;
     }
     delete jniDisplayPinListener;
@@ -288,3 +288,39 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcProvisioning_setDisplayPinListen
         ThrowOcException(OC_STACK_ERROR, e.reason().c_str());
     }
 }
+/*
+ * Class:     org_iotivity_base_OcProvisioning
+ * Method:    saveTrustCertChain1
+ * Signature: (Lorg/iotivity/base/OcProvisioning/provisionTrustCertChain1;)V
+ */
+    JNIEXPORT jint JNICALL Java_org_iotivity_base_OcProvisioning_saveTrustCertChain1
+(JNIEnv *env, jobject thiz, jbyteArray trustCertChain, jint encodingType)
+{
+    LOGD("OcProvisioning_saveTrustCertChain1");
+#if defined(__WITH_X509__) || defined(__WITH_TLS__)
+    jbyte* trustCertChainBytes = env->GetByteArrayElements(trustCertChain, 0);
+    jsize arrayLength = env->GetArrayLength(trustCertChain);
+    uint16_t credId;
+    unsigned char* trustedCertChar = new unsigned char[arrayLength];
+    try
+    {
+        env->GetByteArrayRegion (trustCertChain, 0, arrayLength, reinterpret_cast<jbyte*>(trustedCertChar));
+        OCStackResult result = OCSecure::saveTrustCertChain((uint8_t*)trustedCertChar, arrayLength,
+                (OicEncodingType_t)encodingType, &credId);
+        if (OC_STACK_OK != result)
+        {
+            ThrowOcException(result, "OcProvisioning_saveTrustCertChain1");
+            return -1;
+        }
+    }
+    catch (OCException& e)
+    {
+        LOGE("%s", e.reason().c_str());
+        ThrowOcException(e.code(), e.reason().c_str());
+    }
+    return (jint)credId;
+#else
+    ThrowOcException(OC_STACK_INVALID_PARAM, "WITH_TLS not enabled");
+    return -1;
+#endif // __WITH_X509__ || __WITH_TLS__
+}
index 05d3bf6..290744e 100644 (file)
@@ -85,7 +85,13 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcProvisioning_setDisplayPinListen
  */
 JNIEXPORT jobjectArray JNICALL Java_org_iotivity_base_OcProvisioning_getDeviceStatusList1
   (JNIEnv *, jclass, jint);
-
+/*
+ * Class:     org_iotivity_base_OcProvisioning
+ * Method:    saveTrustCertChain1
+ * Signature: ()I
+ */
+JNIEXPORT jint JNICALL Java_org_iotivity_base_OcProvisioning_saveTrustCertChain1
+    (JNIEnv *, jobject, jbyteArray, jint);
 #ifdef __cplusplus
 }
 #endif
index e9acd35..dc85747 100644 (file)
@@ -154,6 +154,103 @@ struct JObjectConverter : boost::static_visitor < jobject >
         }
         return strArr;
     }
+    // OCByteString and arrays:
+    jobject operator()(const OCByteString &val) const
+    {
+        jbyteArray jByteArray = env->NewByteArray(val.len);
+        if (!jByteArray)
+        {
+            return nullptr;
+        }
+        env->SetByteArrayRegion(jByteArray, 0, val.len, reinterpret_cast<const jbyte *>(val.bytes));
+        if (env->ExceptionCheck())
+        {
+            env->DeleteLocalRef(jByteArray);
+            return nullptr;
+        }
+        return jByteArray;
+    }
+    jobject operator()(const std::vector<OCByteString> &val) const
+    {
+        jsize lenOuter = static_cast<jsize>(val.size());
+        jobjectArray jOuterArr = env->NewObjectArray(lenOuter, g_cls_byte1DArray, nullptr);
+        if (!jOuterArr)
+        {
+            return nullptr;
+        }
+        for (jsize i = 0; i < lenOuter; ++i)
+        {
+            jbyteArray jByteArray = (jbyteArray) operator()(val[i]);
+            if (!jByteArray)
+            {
+                env->DeleteLocalRef(jOuterArr);
+                return nullptr;
+            }
+            env->SetObjectArrayElement(jOuterArr, i, static_cast<jobject>(jByteArray));
+            if (env->ExceptionCheck())
+            {
+                env->DeleteLocalRef(jByteArray);
+                env->DeleteLocalRef(jOuterArr);
+                return nullptr;
+            }
+            env->DeleteLocalRef(jByteArray);
+        }
+        return jOuterArr;
+    }
+    jobject operator()(const std::vector<std::vector<OCByteString>> &val) const
+    {
+        jsize lenOuter = static_cast<jsize>(val.size());
+        jobjectArray jOuterArr = env->NewObjectArray(lenOuter, g_cls_byte2DArray, nullptr);
+        if (!jOuterArr)
+        {
+            return nullptr;
+        }
+        for (jsize i = 0; i < lenOuter; ++i)
+        {
+            jobjectArray jMiddleArr = (jobjectArray) operator()(val[i]);
+            if (!jMiddleArr)
+            {
+                env->DeleteLocalRef(jOuterArr);
+                return nullptr;
+            }
+            env->SetObjectArrayElement(jOuterArr, i, jMiddleArr);
+            if (env->ExceptionCheck())
+            {
+                env->DeleteLocalRef(jMiddleArr);
+                env->DeleteLocalRef(jOuterArr);
+                return nullptr;
+            }
+            env->DeleteLocalRef(jMiddleArr);
+        }
+        return jOuterArr;
+     }
+     jobject operator()(const std::vector<std::vector<std::vector<OCByteString>>> &val) const
+     {
+        jsize lenOuter = static_cast<jsize>(val.size());
+        jobjectArray jOuterArr = env->NewObjectArray(lenOuter, g_cls_byte3DArray, nullptr);
+        if (!jOuterArr)
+        {
+            return nullptr;
+        }
+        for (jsize i = 0; i < lenOuter; ++i)
+        {
+            jobjectArray jMiddleArr = (jobjectArray) operator()(val[i]);
+            if (!jMiddleArr)
+            {
+                env->DeleteLocalRef(jOuterArr);
+                return nullptr;
+            }
+            env->SetObjectArrayElement(jOuterArr, i, jMiddleArr);
+            if (env->ExceptionCheck())
+            {
+                env->DeleteLocalRef(jMiddleArr);
+                env->DeleteLocalRef(jOuterArr);
+                return nullptr;
+            }
+            env->DeleteLocalRef(jMiddleArr);
+        }
+        return jOuterArr;
+    }
     jobject operator()(const std::vector<OC::OCRepresentation>& val) const
     {
         jsize len = static_cast<jsize>(val.size());
index def409c..b01059e 100644 (file)
@@ -209,6 +209,22 @@ OCStackResult JniOcSecureResource::provisionCredentials(JNIEnv* env, jint type,
             resultCallback);
 }
 
+#if defined(__WITH_TLS__)
+OCStackResult JniOcSecureResource::provisionTrustCertChain(JNIEnv* env, jint type, jint credId,
+        jobject jListener)
+{
+    JniProvisionResultListner *resultListener = AddProvisionResultListener(env, jListener);
+
+    ResultCallBack resultCallback = [resultListener](PMResultList_t *result, int hasError)
+    {
+        resultListener->ProvisionResultCallback(result, hasError, ListenerFunc::PROVISIONTRUSTCERTCHAIN);
+    };
+
+    return m_sharedSecureResource->provisionTrustCertChain((OicSecCredType_t)type, credId,
+            resultCallback);
+}
+#endif
+
 OCStackResult JniOcSecureResource::provisionACL(JNIEnv* env, jobject _acl, jobject jListener)
 {
     OCStackResult ret;
@@ -327,7 +343,10 @@ OCStackResult JniOcSecureResource::provisionPairwiseDevices(JNIEnv* env, jint ty
         jobject _acl1, jobject _device2, jobject _acl2, jobject jListener)
 {
     OCStackResult ret;
-
+    if(!jListener)
+    {
+        return OC_STACK_INVALID_CALLBACK;
+    }
     JniProvisionResultListner *resultListener = AddProvisionResultListener(env, jListener);
     JniOcSecureResource *device2 = JniOcSecureResource::getJniOcSecureResourcePtr(env, _device2);
     if (!device2)
@@ -402,13 +421,14 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcSecureResource_doOwnershipTransf
     LOGD("OcSecureResource_doOwnershipTransfer");
     if (!jListener)
     {
-        ThrowOcException(OC_STACK_INVALID_PARAM, "provisionResultListener cannot be null");
+        ThrowOcException(OC_STACK_INVALID_CALLBACK, "provisionResultListener cannot be null");
         return;
     }
 
     JniOcSecureResource *secureResource = JniOcSecureResource::getJniOcSecureResourcePtr(env, thiz);
     if (!secureResource)
     {
+        ThrowOcException(OC_STACK_ERROR, "getJniOcSecureResourcePtr failed");
         return;
     }
 
@@ -445,13 +465,14 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcSecureResource_removeDevice
 
     if (!jListener)
     {
-        ThrowOcException(OC_STACK_INVALID_PARAM, "provisionResultListener cannot be null");
+        ThrowOcException(OC_STACK_INVALID_CALLBACK, "provisionResultListener cannot be null");
         return;
     }
 
     JniOcSecureResource *secureResource = JniOcSecureResource::getJniOcSecureResourcePtr(env, thiz);
     if (!secureResource)
     {
+        ThrowOcException(OC_STACK_ERROR, "getJniOcSecureResourcePtr failed");
         return;
     }
 
@@ -480,15 +501,21 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcSecureResource_unlinkDevices
 (JNIEnv *env, jobject thiz, jobject device2, jobject jListener)
 {
     LOGD("OcSecureResource_unlinkDevices");
-    if (!jListener || !device2)
+    if (!jListener)
     {
-        ThrowOcException(OC_STACK_INVALID_PARAM, "provisionResultListener or device2 cannot be null");
+        ThrowOcException(OC_STACK_INVALID_CALLBACK, "provisionResultListener cannot be null");
+        return;
+    }
+    if (!device2)
+    {
+        ThrowOcException(OC_STACK_INVALID_PARAM, "device2 cannot be null");
         return;
     }
 
     JniOcSecureResource *secureResource = JniOcSecureResource::getJniOcSecureResourcePtr(env, thiz);
     if (!secureResource)
     {
+        ThrowOcException(OC_STACK_ERROR, "getJniOcSecureResourcePtr failed");
         return;
     }
 
@@ -513,19 +540,25 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcSecureResource_unlinkDevices
  * Method:    provisionCredentials1
  * Signature: (Lorg/iotivity/base/OcSecureResource/provisionCredentials;)V
  */
-JNIEXPORT void JNICALL Java_org_iotivity_base_OcSecureResource_provisionCredentials1
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcSecureResource_provisionCredentials1
 (JNIEnv *env, jobject thiz, jint type, jint keySize, jobject device2, jobject jListener)
 {
     LOGD("OcSecureResource_provisionCredentials");
-    if (!jListener || !device2)
+    if (!jListener)
     {
-        ThrowOcException(OC_STACK_INVALID_PARAM, "provisionResultListener or device2 cannot be null");
+        ThrowOcException(OC_STACK_INVALID_CALLBACK, "provisionResultListener cannot be null");
+        return;
+    }
+    if (!device2)
+    {
+        ThrowOcException(OC_STACK_INVALID_PARAM, "device2 cannot be null");
         return;
     }
 
     JniOcSecureResource *secureResource = JniOcSecureResource::getJniOcSecureResourcePtr(env, thiz);
     if (!secureResource)
     {
+        ThrowOcException(OC_STACK_ERROR, "getJniOcSecureResourcePtr failed");
         return;
     }
 
@@ -548,6 +581,49 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcSecureResource_provisionCredenti
 
 /*
  * Class:     org_iotivity_base_OcSecureResource
+ * Method:    provisionTrustCertChain1
+ * Signature: (Lorg/iotivity/base/OcSecureResource/provisionTrustCertChain1;)V
+ */
+    JNIEXPORT void JNICALL Java_org_iotivity_base_OcSecureResource_provisionTrustCertChain1
+(JNIEnv *env, jobject thiz, jint type, jint credId, jobject jListener)
+{
+    LOGD("OcSecureResource_provisionTrustCertChain1");
+#if defined(__WITH_X509__) || defined(__WITH_TLS__)
+    if (!jListener)
+    {
+        ThrowOcException(OC_STACK_INVALID_PARAM, "provisionTrustCertChainListener cannot be null");
+        return;
+    }
+
+    JniOcSecureResource *secureResource = JniOcSecureResource::getJniOcSecureResourcePtr(env, thiz);
+    if (!secureResource)
+    {
+        return;
+    }
+
+    try
+    {
+        OCStackResult result = secureResource->provisionTrustCertChain(env, type, credId,
+                jListener);
+        if (OC_STACK_OK != result)
+        {
+            ThrowOcException(result, "OcSecureResource_provisionTrustCertChain1");
+            return;
+        }
+    }
+    catch (OCException& e)
+    {
+        LOGE("%s", e.reason().c_str());
+        ThrowOcException(e.code(), e.reason().c_str());
+    }
+#else
+    ThrowOcException(OC_STACK_INVALID_PARAM, "WITH_TLS not enabled");
+    return;
+#endif // __WITH_X509__ || __WITH_TLS__
+}
+
+/*
+ * Class:     org_iotivity_base_OcSecureResource
  * Method:    provisionACL
  * Signature: (Lorg/iotivity/base/OcSecureResource/provisionACL;)V
  */
@@ -555,15 +631,21 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcSecureResource_provisionACL
 (JNIEnv *env, jobject thiz, jobject acl, jobject jListener)
 {
     LOGD("OcSecureResource_provisionACL");
-    if (!jListener || !acl)
+    if (!jListener)
     {
-        ThrowOcException(OC_STACK_INVALID_PARAM, "provisionResultListener or acl cannot be null");
+        ThrowOcException(OC_STACK_INVALID_CALLBACK, "provisionResultListener cannot be null");
+        return;
+    }
+    if (!acl)
+    {
+        ThrowOcException(OC_STACK_INVALID_PARAM, "acl cannot be null");
         return;
     }
 
     JniOcSecureResource *secureResource = JniOcSecureResource::getJniOcSecureResourcePtr(env, thiz);
     if (!secureResource)
     {
+        ThrowOcException(OC_STACK_ERROR, "getJniOcSecureResourcePtr failed");
         return;
     }
 
@@ -593,15 +675,21 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcSecureResource_provisionPairwise
         jobject acl2, jobject jListener)
 {
     LOGD("OcSecureResource_provisionPairwiseDevices");
-    if (!jListener || !device2)
+    if (!jListener)
     {
-        ThrowOcException(OC_STACK_INVALID_PARAM, "Invalid Parameters");
+        ThrowOcException(OC_STACK_INVALID_CALLBACK, "Invalid Callback");
+        return;
+    }
+    if (!device2)
+    {
+        ThrowOcException(OC_STACK_INVALID_PARAM, "device2 cannot be null");
         return;
     }
 
     JniOcSecureResource *secureResource = JniOcSecureResource::getJniOcSecureResourcePtr(env, thiz);
     if (!secureResource)
     {
+        ThrowOcException(OC_STACK_ERROR, "getJniOcSecureResourcePtr failed");
         return;
     }
 
@@ -632,7 +720,12 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcSecureResource_provisionDirectPa
     jint jedp, jobject jListener)
 {
     LOGD("OcSecureResource_provisionDirectPairing");
-    if (!jListener || !pdacls || !jpin || ! jprmType)
+    if (!jListener)
+    {
+        ThrowOcException(OC_STACK_INVALID_CALLBACK, "Invalid Callback");
+        return;
+    }
+    if (!pdacls || !jpin || ! jprmType)
     {
         ThrowOcException(OC_STACK_INVALID_PARAM, "Invalid Parameters");
         return;
@@ -642,6 +735,7 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcSecureResource_provisionDirectPa
     JniOcSecureResource *secureResource = JniOcSecureResource::getJniOcSecureResourcePtr(env, thiz);
     if (!secureResource)
     {
+        ThrowOcException(OC_STACK_ERROR, "getJniOcSecureResourcePtr failed");
         return;
     }
 
@@ -685,6 +779,7 @@ JNIEXPORT jobject JNICALL Java_org_iotivity_base_OcSecureResource_getLinkedDevic
     JniOcSecureResource *secureResource = JniOcSecureResource::getJniOcSecureResourcePtr(env, thiz);
     if (!secureResource)
     {
+        ThrowOcException(OC_STACK_ERROR, "getJniOcSecureResourcePtr failed");
         return nullptr;
     }
 
@@ -718,6 +813,7 @@ JNIEXPORT jstring JNICALL Java_org_iotivity_base_OcSecureResource_getIpAddr
     JniOcSecureResource *secureResource = JniOcSecureResource::getJniOcSecureResourcePtr(env, thiz);
     if (!secureResource)
     {
+        LOGD("getJniOcSecureResourcePtr failed");
         return nullptr;
     }
 
@@ -736,6 +832,7 @@ JNIEXPORT jstring JNICALL Java_org_iotivity_base_OcSecureResource_getDeviceID
     JniOcSecureResource *secureResource = JniOcSecureResource::getJniOcSecureResourcePtr(env, thiz);
     if (!secureResource)
     {
+        LOGD("getJniOcSecureResourcePtr failed");
         return nullptr;
     }
 
@@ -754,6 +851,7 @@ JNIEXPORT jint JNICALL Java_org_iotivity_base_OcSecureResource_deviceStatus
     JniOcSecureResource *secureResource = JniOcSecureResource::getJniOcSecureResourcePtr(env, thiz);
     if (!secureResource)
     {
+        LOGD("getJniOcSecureResourcePtr failed");
         return -1;
     }
 
@@ -772,6 +870,7 @@ JNIEXPORT jint JNICALL Java_org_iotivity_base_OcSecureResource_ownedStatus
     JniOcSecureResource *secureResource = JniOcSecureResource::getJniOcSecureResourcePtr(env, thiz);
     if (!secureResource)
     {
+        LOGD("getJniOcSecureResourcePtr failed");
         return -1;
     }
 
index d071e96..213f20d 100644 (file)
@@ -53,6 +53,8 @@ class JniOcSecureResource
                 jobject acl1, jobject device2, jobject acl2, jobject jListener);
         OCStackResult provisionCredentials(JNIEnv* env, jint type, jint keySize,
                 jobject device2, jobject jListener);
+        OCStackResult provisionTrustCertChain(JNIEnv* env, jint type, jint credId,
+                jobject jListener);
         OCStackResult unlinkDevices(JNIEnv* env, jobject device2, jobject jListener);
         OCStackResult removeDevice(JNIEnv* env, jint timeout, jobject jListener);
         OCStackResult provisionDirectPairing(JNIEnv* env, jobjectArray jpdacls,jobject jListener,
@@ -99,7 +101,15 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcSecureResource_unlinkDevices
  * Signature: (IILjava/lang/Object;Lorg/iotivity/base/OcSecureResource/ProvisionCredentialsListener;)V
  */
 JNIEXPORT void JNICALL Java_org_iotivity_base_OcSecureResource_provisionCredentials1
-  (JNIEnv *, jobject, jint, jint, jobject, jobject);
+    (JNIEnv *, jobject, jint, jint, jobject, jobject);
+
+/*
+ * Class:     org_iotivity_base_OcSecureResource
+ * Method:    provisionTrustCertChain1
+ * Signature: (Lorg/iotivity/base/OcSecureResource/ProvisionTrustCertChainListener;)V
+ */
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcSecureResource_provisionTrustCertChain1
+    (JNIEnv *, jobject, jint, jint, jobject);
 
 /*
  * Class:     org_iotivity_base_OcSecureResource
@@ -107,7 +117,7 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcSecureResource_provisionCredenti
  * Signature: (Ljava/lang/Object;Lorg/iotivity/base/OcSecureResource/ProvisionAclListener;)V
  */
 JNIEXPORT void JNICALL Java_org_iotivity_base_OcSecureResource_provisionACL
-  (JNIEnv *, jobject, jobject, jobject);
+    (JNIEnv *, jobject, jobject, jobject);
 
 /*
  * Class:     org_iotivity_base_OcSecureResource
index 06de766..36468fb 100644 (file)
@@ -39,6 +39,9 @@
 
 JavaVM* g_jvm = nullptr;
 
+jclass g_cls_byte1DArray = nullptr;
+jclass g_cls_byte2DArray = nullptr;
+jclass g_cls_byte3DArray = nullptr;
 jclass g_cls_Integer = nullptr;
 jclass g_cls_int1DArray = nullptr;
 jclass g_cls_int2DArray = nullptr;
@@ -193,6 +196,22 @@ JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* reserved)
 
     jclass clazz = nullptr;
 
+    //byte
+    clazz = env->FindClass("[B");
+    VERIFY_VARIABLE_NULL(clazz);
+    g_cls_byte1DArray = (jclass)env->NewGlobalRef(clazz);
+    env->DeleteLocalRef(clazz);
+
+    clazz = env->FindClass("[[B");
+    VERIFY_VARIABLE_NULL(clazz);
+    g_cls_byte2DArray = (jclass)env->NewGlobalRef(clazz);
+    env->DeleteLocalRef(clazz);
+
+    clazz = env->FindClass("[[[B");
+    VERIFY_VARIABLE_NULL(clazz);
+    g_cls_byte3DArray = (jclass)env->NewGlobalRef(clazz);
+    env->DeleteLocalRef(clazz);
+
     //Integer
     clazz = env->FindClass("java/lang/Integer");
     VERIFY_VARIABLE_NULL(clazz);
@@ -638,6 +657,9 @@ JNIEXPORT void JNICALL JNI_OnUnload(JavaVM *vm, void *reserved)
         env->DeleteGlobalRef(g_cls_OcSecureResource);
         env->DeleteGlobalRef(g_cls_OcProvisionResult);
         env->DeleteGlobalRef(g_cls_OcDirectPairDevice);
+        env->DeleteGlobalRef(g_cls_byte1DArray);
+        env->DeleteGlobalRef(g_cls_byte2DArray);
+        env->DeleteGlobalRef(g_cls_byte3DArray);
 #ifdef WITH_CLOUD
         env->DeleteGlobalRef(g_cls_OcAccountManager);
 #endif
index 600f0ab..d7cd718 100644 (file)
@@ -48,6 +48,9 @@ void throwOcException(JNIEnv* env, jobject ex);
 
 extern JavaVM* g_jvm;
 
+extern jclass g_cls_byte1DArray;
+extern jclass g_cls_byte2DArray;
+extern jclass g_cls_byte3DArray;
 extern jclass g_cls_Integer;
 extern jclass g_cls_int1DArray;
 extern jclass g_cls_int2DArray;
index c1a04b1..cbbbbb0 100644 (file)
@@ -66,16 +66,19 @@ void JniOnResourceFoundListener::foundResourceCallback(std::shared_ptr<OC::OCRes
         {
             g_jvm->DetachCurrentThread();
         }
+        return;
     }
 
     jobject jResource = env->NewObject(g_cls_OcResource, g_mid_OcResource_ctor);
     if (!jResource)
     {
+        env->DeleteLocalRef(jListener);
         checkExAndRemoveListener(env);
         if (JNI_EDETACHED == ret)
         {
             g_jvm->DetachCurrentThread();
         }
+        return;
     }
 
     JniOcResource *jniOcResource = new JniOcResource(resource);
@@ -83,44 +86,61 @@ void JniOnResourceFoundListener::foundResourceCallback(std::shared_ptr<OC::OCRes
     if (env->ExceptionCheck())
     {
         delete jniOcResource;
+        env->DeleteLocalRef(jResource);
+        env->DeleteLocalRef(jListener);
         checkExAndRemoveListener(env);
         if (JNI_EDETACHED == ret)
         {
             g_jvm->DetachCurrentThread();
         }
+        return;
     }
     jclass clsL = env->GetObjectClass(jListener);
     if (!clsL)
     {
         delete jniOcResource;
+        env->DeleteLocalRef(jResource);
+        env->DeleteLocalRef(jListener);
         checkExAndRemoveListener(env);
         if (JNI_EDETACHED == ret)
         {
             g_jvm->DetachCurrentThread();
         }
+        return;
     }
     jmethodID midL = env->GetMethodID(clsL, "onResourceFound", "(Lorg/iotivity/base/OcResource;)V");
     if (!midL)
     {
         delete jniOcResource;
+        env->DeleteLocalRef(clsL);
+        env->DeleteLocalRef(jResource);
+        env->DeleteLocalRef(jListener);
         checkExAndRemoveListener(env);
         if (JNI_EDETACHED == ret)
         {
             g_jvm->DetachCurrentThread();
         }
+        return;
     }
     env->CallVoidMethod(jListener, midL, jResource);
     if (env->ExceptionCheck())
     {
         LOGE("Java exception is thrown");
         delete jniOcResource;
+        env->DeleteLocalRef(clsL);
+        env->DeleteLocalRef(jResource);
+        env->DeleteLocalRef(jListener);
         checkExAndRemoveListener(env);
         if (JNI_EDETACHED == ret)
         {
             g_jvm->DetachCurrentThread();
         }
+        return;
     }
 
+    env->DeleteLocalRef(clsL);
+    env->DeleteLocalRef(jResource);
+    env->DeleteLocalRef(jListener);
     if (JNI_EDETACHED == ret)
     {
         g_jvm->DetachCurrentThread();
index 066a677..a25f015 100644 (file)
@@ -112,6 +112,11 @@ void JniProvisionResultListner::ProvisionResultCallback(PMResultList_t *result,
             calledFunc = "provisionCredentialsListener";
         }
         break;
+        case ListenerFunc::PROVISIONTRUSTCERTCHAIN:
+        {
+            calledFunc = "provisionTrustCertChainListener";
+        }
+        break;
         case ListenerFunc::UNLINKDEVICES:
         {
             calledFunc = "unlinkDevicesListener";
index 8bf5242..59a0945 100644 (file)
@@ -33,6 +33,7 @@ enum class ListenerFunc
     OWNERSHIPTRANSFER = 1,
     PROVISIONACL,
     PROVISIONCREDENTIALS,
+    PROVISIONTRUSTCERTCHAIN,
     UNLINKDEVICES,
     REMOVEDEVICE,
     PROVISIONPAIRWISEDEVICES,
diff --git a/android/android_api/base/src/main/java/org/iotivity/base/EncodingType.java b/android/android_api/base/src/main/java/org/iotivity/base/EncodingType.java
new file mode 100644 (file)
index 0000000..944eadb
--- /dev/null
@@ -0,0 +1,42 @@
+/*
+ *******************************************************************
+ *
+ * Copyright 2016 Samsung Electronics 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.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ */
+
+package org.iotivity.base;
+
+public enum EncodingType {
+
+    OIC_ENCODING_UNKNOW (0),
+                        OIC_ENCODING_RAW (1),
+                        OIC_ENCODING_BASE64 (2),
+                        OIC_ENCODING_PEM (3),
+                        OIC_ENCODING_DER (4);
+
+    private int value;
+
+    private EncodingType(int value) {
+        this.value = value;
+    }
+
+    public int getValue() {
+        return this.value;
+    }
+}
index 33eef2d..8cb282b 100644 (file)
@@ -112,4 +112,17 @@ public class OcProvisioning {
         return Arrays.asList(OcProvisioning.getDeviceStatusList1(timeout));
     }
     private static native OcSecureResource[] getDeviceStatusList1(int timeout) throws OcException;
+
+    /**
+     *  Method to save the Trust certificate chain to SVR.
+     *
+     *  @param byte[]            trustCertChain
+     *  @param EncodingType                          encodingType
+     *  @throws OcException
+     */
+    public static int saveTrustCertChain(byte[] trustCertChain, EncodingType encodingType) throws OcException {
+        return saveTrustCertChain1(trustCertChain,encodingType.getValue());
+    }
+    private static native int saveTrustCertChain1(byte[] trustCertChain, int encodingType)
+        throws OcException;
 }
index f69b548..0a6d096 100644 (file)
@@ -90,6 +90,30 @@ public class OcSecureResource {
         throws OcException;
 
     /**
+     *  Method to provision the Trust certificate chain to secured device.
+     *
+     *  @param EnumSet<CredType>            OR'ed Cred Types
+     *  @param int                          credId
+     *  @param ProvisionTrustCertChainListener Callback function, which will be called after
+     *                                      proviosion trust certificate chain.
+     *  @throws OcException
+     */
+    public void provisionTrustCertChain(EnumSet<CredType> credTypeSet, int credId,
+            ProvisionTrustCertChainListener provisionTrustCertChainListener) throws OcException {
+        int credTypeInt = 0;
+
+        for (CredType credType : CredType.values()) {
+            if (credTypeSet.contains(credType))
+                credTypeInt |= credType.getValue();
+        }
+        this.provisionTrustCertChain1(credTypeInt, credId,
+                provisionTrustCertChainListener);
+    }
+    private native void provisionTrustCertChain1(int credType, int credId,
+            ProvisionTrustCertChainListener provisionTrustCertChainListener)
+        throws OcException;
+
+    /**
      *  Method send ACL information to resource.
      *
      *  @param jobject                      Acl
@@ -210,6 +234,16 @@ public class OcSecureResource {
                 int hasError);
     }
 
+       /**
+     * provisionTrustCertChainListener can be registered with ProvisionTrustCertChainListener
+     * call.
+     * Listener notified asynchronously.
+     */
+    public interface ProvisionTrustCertChainListener {
+        public void provisionTrustCertChainListener(List<ProvisionResult> provisionResultList,
+                int hasError);
+    }
+       
     /**
      * provisionAclListener can be registered with provisionAclListener
      * call.
diff --git a/android/examples/provisioningclient/src/main/assets/rootca.crt b/android/examples/provisioningclient/src/main/assets/rootca.crt
new file mode 100644 (file)
index 0000000..54ec780
--- /dev/null
@@ -0,0 +1,19 @@
+-----BEGIN CERTIFICATE-----
+MIIC/jCCAeYCAQEwDQYJKoZIhvcNAQELBQAwRTELMAkGA1UEBhMCQVUxEzARBgNV
+BAgMClNvbWUtU3RhdGUxITAfBgNVBAoMGEludGVybmV0IFdpZGdpdHMgUHR5IEx0
+ZDAeFw0xNjA2MjgwNTMzNThaFw0yNjA2MjYwNTMzNThaMEUxCzAJBgNVBAYTAkFV
+MRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBXaWRnaXRz
+IFB0eSBMdGQwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC1HHkfMG9c
+BJ7ZeCIBKe7pSjpptvi+hzpdV72W7szpWDlTQdUaRxKL9aoNxbyuF5OL8xAQ9s28
+IqIxdPW7X3JAmkLigzMCo2xtXHz/OyvomU6fhibneQw5De+iUoD68zdG+/k1NcAW
+xx+VEAMw4fvZvYSVEQ1aKFnjtrQ8o6Zfe5+MRTvBq+G0+jwZWJEoKbpxIPpNWPGx
+AV17tEpe+lg27jEYDYG1QUiL2TG80ZjQQL95OjETYf8EIxoqrKHvHCvDin0zdd+E
+qPN0Y+Rhkl3PYoxWm7d8z0p1mD7lcwOMvy1KgEgtJ7SHy0D2SIW/KaDox/kRPC1P
+ksFeAS2B0Z9zAgMBAAEwDQYJKoZIhvcNAQELBQADggEBAAtHjimMywXn893Ifu1v
+tNnL9ITMpQhsHAlg1QBVEyjGZLIjUgMhsWljVwTC1PdBrO7V0ElYbeV+LKYGwDk6
+fjBJogCLgZiUw18F8TjHC/qDsoWEsm1iB4KcTZkk0nm/2vidHK0TMLzCohR71/vN
+KS2rtiQDYGKe9EzjNSO3GlCWkVTYtJNhALa/BfDza5keRkwmldJYhlx4rQH5yVRn
+t5k87vjX0h7m8MzIwiAb2s/b9XBlM1FuFx3FxcVjBl7KtUAU7twU8v5LenjWDSH1
+D1jnKiZUUspgovhosPRqmxGNXldaX1E+RJmxdtqUVg4co/zjAbTY7C+7ZYIZBo46
+Ll0=
+-----END CERTIFICATE-----
index b834101..dbd6a18 100644 (file)
@@ -16,6 +16,7 @@ import android.widget.LinearLayout;
 import android.widget.TextView;
 
 import org.iotivity.base.CredType;
+import org.iotivity.base.EncodingType;
 import org.iotivity.base.DeviceStatus;
 import org.iotivity.base.KeySize;
 import org.iotivity.base.ModeType;
@@ -50,6 +51,7 @@ OcSecureResource.DoOwnershipTransferListener, OcSecureResource.ProvisionPairwise
 
     private static final String TAG = "Provisioning Client: ";
     private static final int BUFFER_SIZE = 1024;
+    private int credId=0;
     int unownedDevCount = StringConstants.NUMBER_ZERO;
     OcProvisioning.PinCallbackListener pinCallbackListener =
         new OcProvisioning.PinCallbackListener() {
@@ -96,7 +98,7 @@ OcSecureResource.DoOwnershipTransferListener, OcSecureResource.ProvisionPairwise
                         logMessage("Error: ACL Provision failed !!");
                     } else {
                         logMessage("ACL Provision Done !!");
-                        new DeviceRevocationAsyncTask().execute();
+                        provisionCertChain();
                     }
                 }
         };
@@ -114,6 +116,22 @@ OcSecureResource.DoOwnershipTransferListener, OcSecureResource.ProvisionPairwise
                     }
                 }
         };
+
+    OcSecureResource.ProvisionTrustCertChainListener provisionTrustCertListener =
+        new OcSecureResource.ProvisionTrustCertChainListener() {
+            @Override
+                public void provisionTrustCertChainListener(List<ProvisionResult> provisionResults,
+                        int hasError) {
+                    Log.d(TAG, "Inside provisionTrustCertChainListener ");
+                    if (hasError == StringConstants.ERROR_CODE) {
+                        logMessage("Error: Provision TrustCertChain failed !!");
+                    } else {
+                        logMessage("Provision TrustCertChain Done !!");
+                        new DeviceRevocationAsyncTask().execute();
+                    }
+                }
+        };
+
     OcSecureResource.UnlinkDevicesListener unlinkDevicesListener =
         new OcSecureResource.UnlinkDevicesListener() {
             @Override
@@ -163,6 +181,7 @@ OcSecureResource.DoOwnershipTransferListener, OcSecureResource.ProvisionPairwise
                 editor.commit();
             }
             initOICStack();
+            saveCertChain();
         }
 
     /**
@@ -313,6 +332,59 @@ OcSecureResource.DoOwnershipTransferListener, OcSecureResource.ProvisionPairwise
                 doDPProvisioning();
             }
         }
+    /**
+     * get cert from asset folder & save trusted cert chain
+     */
+    private void saveCertChain() {
+        InputStream inputStream = null;
+        try {
+
+            inputStream = getAssets().open(StringConstants.CRT_FILE);
+            byte[] fileBytes = new byte[inputStream.available()+1];
+            inputStream.read(fileBytes);
+            fileBytes[inputStream.available()]=0x00;
+            credId = OcProvisioning.saveTrustCertChain(fileBytes,
+                    EncodingType.OIC_ENCODING_PEM);
+            logMessage(TAG + "saveTrustCertChain return credId = " + credId);
+        } catch (IOException e) {
+            logMessage(TAG + "Cert file not exist in Assets" + e.getMessage());
+            Log.e(TAG, e.getMessage());
+        } catch (OcException e) {
+            logMessage(TAG + "saveTrustCertChain failed " + e.getMessage());
+            Log.e(TAG, e.getMessage());
+        } finally {
+            if (inputStream != null) {
+                try {
+                    inputStream.close();
+                } catch (IOException e) {
+                    Log.e(TAG, e.getMessage());
+                }
+            }
+
+        }
+    }
+
+    /**
+     * Provision cert chain
+     */
+    private void provisionCertChain() {
+
+        if (ownedDeviceList.size() > 0) {
+            try {
+                OcSecureResource ocSecureResource = ownedDeviceList.get(0);
+                logMessage(TAG + "Initiate provision cert chain credId = "
+                        + credId);
+                ocSecureResource.provisionTrustCertChain(
+                        EnumSet.of(CredType.SIGNED_ASYMMETRIC_KEY), credId,
+                        provisionTrustCertListener);
+            } catch (OcException e) {
+                logMessage(TAG + "Provision cert chain error: "
+                        + e.getMessage());
+                Log.e(TAG, e.getMessage());
+            }
+        }
+
+    }
 
     /**
      * Copy svr db CBOR dat file from assets folder to app data files dir
index ec99616..2ae1017 100644 (file)
@@ -30,6 +30,7 @@ public interface StringConstants {
     public static final String DEFAULT_PERIOD =  "12-12-16";
     public static final int DEFAULT_PERMISSION = 31;
     public static final String OIC_CLIENT_CBOR_DB_FILE =  "oic_svr_db_client.dat";
+       public static final String CRT_FILE =  "rootca.crt";
     public static final String MESSAGE = "message";
     public static final String OIC_SQL_DB_FILE =  "Pdm.db";
     public static final int  CREDENTIAL_TYPE=1;
index 783812d..aa4cc2f 100644 (file)
@@ -34,6 +34,7 @@ import android.view.LayoutInflater;
 import android.view.View;
 import android.view.ViewGroup;
 import android.widget.Button;
+import android.widget.CheckBox;
 import android.widget.CompoundButton;
 import android.widget.EditText;
 import android.widget.LinearLayout;
@@ -73,8 +74,7 @@ import java.util.regex.Pattern;
  */
 public class CloudFragment extends Fragment implements
         View.OnClickListener, CompoundButton.OnCheckedChangeListener,
-        OcAccountManager.OnPostListener, OcAccountManager.OnGetListener,
-        OcAccountManager.OnDeleteListener, OcResource.OnObserveListener,
+        OcResource.OnObserveListener,
         OcResource.OnMQTopicFoundListener, OcResource.OnMQTopicCreatedListener,
         OcResource.OnMQTopicSubscribeListener {
 
@@ -86,21 +86,18 @@ public class CloudFragment extends Fragment implements
                     "\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)" +
                     "\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)" +
                     "\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9])" +
-                    "\\:([0-9]{1,5}))");
+                    ":([0-9]{1,5}))");
 
     private Activity mActivity;
     private Context mContext;
 
     private QualityOfService mQos = QualityOfService.LOW;
+    private boolean mSecured = false;
 
     private LinearLayout mAccountLayout;
     private LinearLayout mRDLayout;
     private LinearLayout mMQLayout;
 
-    private Switch mAccountSwitch;
-    private Switch mRDSwitch;
-    private Switch mMQSwitch;
-
     private TextView mAccountText;
     private TextView mRDText;
     private TextView mMQText;
@@ -108,49 +105,28 @@ public class CloudFragment extends Fragment implements
     private TextView mActionLog;
     private TextView mResultLog;
 
-    private Button mSetIPButton;
-    private Button mSignUpButton;
-    private Button mSignInButton;
-    private Button mSignOutButton;
-    private Button mCreateGroupButton;
-    private Button mInviteButton;
-    private Button mLeaveGroupButton;
-    private Button mRdPubButton;
-    private Button mRdDelButton;
-    private Button mDevicePresenceButton;
-    private Button mMqBrokerButton;
-    private Button mCreateTopicButton;
-    private Button mSubTopicButton;
-    private Button mUnsubTopicButton;
-    private Button mPubToicButton;
-
     private OcAccountManager mAccountManager;
-    private String mAccesstoken;
-    private String mRefreshtoken;
+    private String mAccessToken;
+    private String mRefreshToken;
     private String mUserUuid;
-    private String mAuthCode;
     private String mGroupId;
     private String mGroupMasterId;
-    private String mInviterUuid;
     private String mInviterUserId;
     private String mInviteeUuid;
-    private String mInviteeUserId;
-
-    private int mRequestCode;
     private final int REQUEST_LOGIN = 1;
 
+    private OcResourceHandle localLightResourceHandle = null;
+    private List<OcResourceHandle> mResourceHandleList = new LinkedList<>();
+    private OcPresenceHandle mOcPresenceHandle = null;
+    private Button mDevicePresenceButton;
+
     private OcResource MQbrokerResource = null;
     private OcResource currentTopicResource = null;
     private boolean switchingFlag = true;
-    private int subFlag = -1;
     private int roomNum = 1;
     private String defaultTopicFullName = Common.MQ_DEFAULT_TOPIC_URI;
-    private int cancelSubScribe = 0xffffff;
 
-    private OcResourceHandle localLightResourceHandle = null;
-    private List<OcResourceHandle> mResourceHandleList = new LinkedList<>();
-    private OcPresenceHandle mOcPresenceHandle;
-    //variables related observer
+    // variables related observer
     private int maxSequenceNumber = 0xFFFFFF;
 
     @Override
@@ -186,20 +162,18 @@ public class CloudFragment extends Fragment implements
     }
 
     private void signIn() {
-        mRequestCode = 1;
         try {
             msg("signIn");
-            mAccountManager.signIn(mUserUuid, mAccesstoken, onSignIn);
+            mAccountManager.signIn(mUserUuid, mAccessToken, onSignIn);
         } catch (OcException e) {
             e.printStackTrace();
         }
     }
 
     private void signOut() {
-        mRequestCode = 2;
         try {
             msg("signOut");
-            mAccountManager.signOut(this);
+            mAccountManager.signOut(onSignOut);
         } catch (OcException e) {
             e.printStackTrace();
         }
@@ -215,20 +189,18 @@ public class CloudFragment extends Fragment implements
     }
 
     private void inviteUser() {
-        if (mGroupId == null){
+        if (mGroupId == null) {
             msg("there is no any group");
-        }
-        else {
+        } else {
             showInviteUser();
         }
     }
 
     private void leaveGroup() {
         try {
-            if (mGroupId == null){
+            if (mGroupId == null) {
                 msg("there is no any group");
-            }
-            else {
+            } else {
                 msg("leaveGroup");
                 mAccountManager.leaveGroup(mGroupId, onLeaveGroup);
             }
@@ -242,87 +214,34 @@ public class CloudFragment extends Fragment implements
     public void onActivityResult(int requestCode, int resultCode, Intent data) {
         super.onActivityResult(requestCode, resultCode, data);
         if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_LOGIN) {
-            mAuthCode = data.getStringExtra("authCode");
-            msg("\tauthCode: " + mAuthCode);
+            String authCode = data.getStringExtra("authCode");
+            msg("\tauthCode: " + authCode);
 
             try {
                 msg("Sign Up");
-                mAccountManager.signUp("github", mAuthCode, onSignUp);
+                mAccountManager.signUp("github", authCode, onSignUp);
             } catch (OcException e) {
                 e.printStackTrace();
             }
         }
     }
 
-    @Override
-    public void onPostCompleted(List<OcHeaderOption> list, OcRepresentation ocRepresentation) {
-        try {
-            if (mRequestCode == 1) {
-                msg("\tSign In Success");
-                int expiresIn = ocRepresentation.getValue("expiresin");
-                msg("\texpiresin: " + expiresIn);
-            } else if (mRequestCode == 2) {
-                msg("\tSign Out Success");
-            } else if (mRequestCode == 3) {
-                msg("\tRefresh AccessToken Success");
-
-                mAccesstoken = ocRepresentation.getValue("accesstoken");
-                mRefreshtoken = ocRepresentation.getValue("refreshtoken");
-                msg("\tuserID: " + mUserUuid);
-                msg("\taccessToken: " + mAccesstoken);
-                msg("\trefreshtoken: " + mRefreshtoken);
-            }
-        } catch (OcException e) {
-            e.printStackTrace();
-        }
-    }
-
-    @Override
-    public void onPostFailed(Throwable throwable) {
-        msg("onPostFailed");
-        if (throwable instanceof OcException) {
-            OcException ocEx = (OcException) throwable;
-            Log.e(TAG, ocEx.toString());
-        }
-    }
-
-    @Override
-    public void onGetCompleted(List<OcHeaderOption> list, OcRepresentation ocRepresentation) {
-
-    }
-
-    @Override
-    public void onGetFailed(Throwable throwable) {
-
-    }
-
-    @Override
-    public void onDeleteCompleted(List<OcHeaderOption> list) {
-
-    }
-
-    @Override
-    public void onDeleteFailed(Throwable throwable) {
-
-    }
-
     OcAccountManager.OnPostListener onSignUp = new OcAccountManager.OnPostListener() {
         @Override
         public synchronized void onPostCompleted(List<OcHeaderOption> list,
                                                  OcRepresentation ocRepresentation) {
             msg("signUp was successful");
             try {
-                mUserUuid        = ocRepresentation.getValue("uid");
-                mAccesstoken     = ocRepresentation.getValue("accesstoken");
-                mRefreshtoken    = ocRepresentation.getValue("refreshtoken");
+                mUserUuid = ocRepresentation.getValue("uid");
+                mAccessToken = ocRepresentation.getValue("accesstoken");
+                mRefreshToken = ocRepresentation.getValue("refreshtoken");
                 String tokenType = ocRepresentation.getValue("tokentype");
                 msg("\tuserID: " + mUserUuid);
-                msg("\taccessToken: " + mAccesstoken);
-                msg("\trefreshToken: " + mRefreshtoken);
+                msg("\taccessToken: " + mAccessToken);
+                msg("\trefreshToken: " + mRefreshToken);
                 msg("\ttokenType: " + tokenType);
 
-                if (ocRepresentation.hasAttribute("expiresin"))
-                {
+                if (ocRepresentation.hasAttribute("expiresin")) {
                     int expiresIn = ocRepresentation.getValue("expiresin");
                     msg("\texpiresIn: " + expiresIn);
                 }
@@ -352,7 +271,7 @@ public class CloudFragment extends Fragment implements
                 msg("observeInvitation");
                 mAccountManager.observeInvitation(onObserveInvitation);
                 msg("getGroupList");
-                mAccountManager.getGroupList(onGetGrouptList);
+                mAccountManager.getGroupList(onGetGroupList);
             } catch (OcException e) {
                 Log.e(TAG, e.toString());
             }
@@ -370,7 +289,26 @@ public class CloudFragment extends Fragment implements
         }
     };
 
-    OcAccountManager.OnGetListener onGetGrouptList = new OcAccountManager.OnGetListener() {
+    OcAccountManager.OnPostListener onSignOut = new OcAccountManager.OnPostListener() {
+        @Override
+        public synchronized void onPostCompleted(List<OcHeaderOption> list,
+                                                 OcRepresentation ocRepresentation) {
+            msg("signOut was successful");
+        }
+
+        @Override
+        public synchronized void onPostFailed(Throwable throwable) {
+            msg("Failed to signOut");
+            if (throwable instanceof OcException) {
+                OcException ocEx = (OcException) throwable;
+                Log.e(TAG, ocEx.toString());
+                ErrorCode errCode = ocEx.getErrorCode();
+                msg("Error code: " + errCode);
+            }
+        }
+    };
+
+    OcAccountManager.OnGetListener onGetGroupList = new OcAccountManager.OnGetListener() {
         @Override
         public void onGetCompleted(List<OcHeaderOption> list, OcRepresentation ocRepresentation) {
             msg("getGroupList was successful");
@@ -379,8 +317,7 @@ public class CloudFragment extends Fragment implements
                 if (gidlist == null) {
                     msg("\tgroup list is empty");
                     mGroupId = null;
-                }
-                else{
+                } else {
                     msg("\tgroup list");
                     for (String group : gidlist) {
                         msg("\t\t" + group);
@@ -405,78 +342,84 @@ public class CloudFragment extends Fragment implements
         }
     };
 
-    OcAccountManager.OnObserveListener onObserveInvitation = new OcAccountManager.OnObserveListener() {
-        @Override
-        public void onObserveCompleted(List<OcHeaderOption> list, OcRepresentation ocRepresentation, int i) {
-            msg("observeInvitation was successful");
-            try {
-                if (this.REGISTER == i) {
-                    msg("REGISTER was successful");
+    OcAccountManager.OnObserveListener onObserveInvitation =
+            new OcAccountManager.OnObserveListener() {
+                @Override
+                public void onObserveCompleted(List<OcHeaderOption> list,
+                                               OcRepresentation ocRepresentation, int i) {
+                    msg("observeInvitation was successful");
+                    try {
+                        if (REGISTER == i) {
+                            msg("REGISTER was successful");
+
+                            OcRepresentation[] sendInvitationList =
+                                    ocRepresentation.getValue("invite");
+                            if (sendInvitationList != null) {
+                                msg("\tList of invitation that I sent");
+                                for (OcRepresentation invitation : sendInvitationList) {
+                                    String gid = invitation.getValue("gid");
+                                    String mid = invitation.getValue("mid");
+                                    msg("\t\t-GroupID : " + gid);
+                                    msg("\t\t InviteeID : " + mid);
+                                }
+                            }
 
-                    OcRepresentation[] sendInvitationList = ocRepresentation.getValue("invite");
-                    if (sendInvitationList != null) {
-                        msg("\tList of invitation that I sent");
-                        for (OcRepresentation invitation : sendInvitationList) {
-                            String gid = invitation.getValue("gid");
-                            String mid = invitation.getValue("mid");
-                            msg("\t\t-GroupID : " + gid);
-                            msg("\t\t InviteeID : " + mid);
-                        }
-                    }
+                            OcRepresentation[] receiveInvitationList =
+                                    ocRepresentation.getValue("invited");
+                            if (receiveInvitationList != null) {
+                                msg("\tList of invitation that I received");
+                                for (OcRepresentation invitation : receiveInvitationList) {
+                                    String gid = invitation.getValue("gid");
+                                    String mid = invitation.getValue("mid");
+                                    msg("\t\t-GroupID : " + gid);
+                                    msg("\t\t InviterID : " + mid);
+                                }
+                            }
+                        } else if (DEREGISTER == i) {
+                            msg("DEREGISTER was successful");
+                        } else {
+                            OcRepresentation[] sendInvitationList =
+                                    ocRepresentation.getValue("invite");
+                            if (sendInvitationList != null) {
+                                msg("\tList of invitation that I sent");
+                                for (OcRepresentation invitation : sendInvitationList) {
+                                    String gid = invitation.getValue("gid");
+                                    String mid = invitation.getValue("mid");
+                                    msg("\t\t-GroupID : " + gid);
+                                    msg("\t\t InviteeID : " + mid);
+                                }
+                            }
 
-                    OcRepresentation[] receivInvitationList = ocRepresentation.getValue("invited");
-                    if (receivInvitationList != null) {
-                        msg("\tList of invitation that I received");
-                        for (OcRepresentation invitation : receivInvitationList) {
-                            String gid = invitation.getValue("gid");
-                            String mid = invitation.getValue("mid");
-                            msg("\t\t-GroupID : " + gid);
-                            msg("\t\t InviterID : " + mid);
-                        }
-                    }
-                } else if (this.DEREGISTER == i) {
-                    msg("DEREGISTER was successful");
-                } else {
-                    OcRepresentation[] sendInvitationList = ocRepresentation.getValue("invite");
-                    if (sendInvitationList != null) {
-                        msg("\tList of invitation that I sent");
-                        for (OcRepresentation invitation : sendInvitationList) {
-                            String gid = invitation.getValue("gid");
-                            String mid = invitation.getValue("mid");
-                            msg("\t\t-GroupID : " + gid);
-                            msg("\t\t InviteeID : " + mid);
+                            OcRepresentation[] receivInvitationList =
+                                    ocRepresentation.getValue("invited");
+                            if (receivInvitationList != null) {
+                                msg("\tList of invitation that I received");
+                                for (OcRepresentation invitation : receivInvitationList) {
+                                    mGroupId = invitation.getValue("gid");
+                                    mGroupMasterId = invitation.getValue("mid");
+                                    msg("\t\t-GroupID : " + mGroupId);
+                                    msg("\t\t InviterID : " + mGroupMasterId);
+                                }
+                                msg("searchUser");
+                                mAccountManager.searchUser(mGroupMasterId, onSearchUserForInvitee);
+                            }
                         }
+                    } catch (OcException e) {
+                        e.printStackTrace();
                     }
+                }
 
-                    OcRepresentation[] receivInvitationList = ocRepresentation.getValue("invited");
-                    if (receivInvitationList != null) {
-                        msg("\tList of invitation that I received");
-                        for (OcRepresentation invitation : receivInvitationList) {
-                            mGroupId = invitation.getValue("gid");
-                            mGroupMasterId = invitation.getValue("mid");
-                            msg("\t\t-GroupID : " + mGroupId);
-                            msg("\t\t InviterID : " + mGroupMasterId);
-                        }
-                        msg("searchUser");
-                        mAccountManager.searchUser(mGroupMasterId, onSearchUserForInvitee);
+                @Override
+                public void onObserveFailed(Throwable throwable) {
+                    msg("Failed to observeInvitation");
+                    if (throwable instanceof OcException) {
+                        OcException ocEx = (OcException) throwable;
+                        Log.e(TAG, ocEx.toString());
+                        ErrorCode errCode = ocEx.getErrorCode();
+                        msg("Error code: " + errCode);
                     }
                 }
-            } catch (OcException e) {
-                e.printStackTrace();
-            }
-        }
-
-        @Override
-        public void onObserveFailed(Throwable throwable) {
-            msg("Failed to observeInvitation");
-            if (throwable instanceof OcException) {
-                OcException ocEx = (OcException) throwable;
-                Log.e(TAG, ocEx.toString());
-                ErrorCode errCode = ocEx.getErrorCode();
-                msg("Error code: " + errCode);
-            }
-        }
-    };
+            };
 
     OcAccountManager.OnGetListener onSearchUserForInvitee = new OcAccountManager.OnGetListener() {
         @Override
@@ -486,7 +429,9 @@ public class CloudFragment extends Fragment implements
             try {
                 OcRepresentation[] userList = ocRepresentation.getValue("ulist");
                 for (OcRepresentation user : userList) {
-                    mInviterUuid = user.getValue("uid");
+                    String inviterUuid = user.getValue("uid");
+                    Log.d(TAG, "inviterUuid : " + inviterUuid);
+
                     OcRepresentation userInfo = user.getValue("uinfo");
                     mInviterUserId = userInfo.getValue("userid");
                 }
@@ -544,7 +489,7 @@ public class CloudFragment extends Fragment implements
         public void onDeleteCompleted(List<OcHeaderOption> list) {
             msg("deleteInvitation was successful");
             try {
-                mAccountManager.getGroupList(onGetGrouptList);
+                mAccountManager.getGroupList(onGetGroupList);
             } catch (OcException e) {
                 e.printStackTrace();
             }
@@ -566,7 +511,8 @@ public class CloudFragment extends Fragment implements
                 for (OcRepresentation user : userList) {
                     mInviteeUuid = user.getValue("uid");
                     OcRepresentation userInfo = user.getValue("uinfo");
-                    mInviteeUserId = userInfo.getValue("userid");
+                    String inviteeUserId = userInfo.getValue("userid");
+                    Log.d(TAG, "inviteeUserId : " + inviteeUserId);
                 }
                 msg("sendInvitation");
                 mAccountManager.sendInvitation(mGroupId, mInviteeUuid, onSendInvitation);
@@ -617,12 +563,13 @@ public class CloudFragment extends Fragment implements
 
     OcAccountManager.OnObserveListener onObserveGroup = new OcAccountManager.OnObserveListener() {
         @Override
-        public void onObserveCompleted(List<OcHeaderOption> list, OcRepresentation ocRepresentation, int i) {
+        public void onObserveCompleted(List<OcHeaderOption> list,
+                                       OcRepresentation ocRepresentation, int i) {
             msg("observeGroup was successful");
             try {
-                if (this.REGISTER == i) {
+                if (REGISTER == i) {
                     msg("REGISTER was successful");
-                } else if (this.DEREGISTER == i) {
+                } else if (DEREGISTER == i) {
                     msg("DEREGISTER was successful");
                 } else {
                     String gid = ocRepresentation.getValue("gid");
@@ -632,10 +579,9 @@ public class CloudFragment extends Fragment implements
                     msg("\tGroupMasterID: " + gmid);
 
                     String[] midlist = ocRepresentation.getValue("midlist");
-                    if (midlist == null){
+                    if (midlist == null) {
                         msg("\tMember List is empty");
-                    }
-                    else {
+                    } else {
                         msg("\tMember List(" + midlist.length + ")");
                         for (String mid : midlist) {
                             msg("\t : " + mid);
@@ -643,10 +589,9 @@ public class CloudFragment extends Fragment implements
                     }
 
                     String[] dilist = ocRepresentation.getValue("dilist");
-                    if (dilist == null){
+                    if (dilist == null) {
                         msg("\tDevice List is empty");
-                    }
-                    else {
+                    } else {
                         msg("\tDevice List(" + dilist.length + ")");
                         for (String di : dilist) {
                             msg("\t : " + di);
@@ -695,7 +640,7 @@ public class CloudFragment extends Fragment implements
             msg("leaveGroup was successful");
             try {
                 msg("getGroupList");
-                mAccountManager.getGroupList(onGetGrouptList);
+                mAccountManager.getGroupList(onGetGroupList);
             } catch (OcException e) {
                 e.printStackTrace();
             }
@@ -706,6 +651,7 @@ public class CloudFragment extends Fragment implements
             msg("Failed to leaveGroup");
         }
     };
+
     // ******************************************************************************
     // End of the Account Manager specific code
     // ******************************************************************************
@@ -795,9 +741,16 @@ public class CloudFragment extends Fragment implements
 
     private void subscribeDevicePresence() {
         try {
-            List<String> di = new ArrayList<>();
-            mOcPresenceHandle = OcPlatform.subscribeDevicePresence(
-                    Common.HOST, di, EnumSet.of(OcConnectivityType.CT_ADAPTER_TCP), this);
+            if (null == mOcPresenceHandle) {
+                List<String> di = new ArrayList<>();
+                mOcPresenceHandle = OcPlatform.subscribeDevicePresence(
+                        Common.HOST, di, EnumSet.of(OcConnectivityType.CT_ADAPTER_TCP), this);
+                mDevicePresenceButton.setText(R.string.unsub_presence);
+            } else {
+                OcPlatform.unsubscribePresence(mOcPresenceHandle);
+                mOcPresenceHandle = null;
+                mDevicePresenceButton.setText(R.string.sub_presence);
+            }
         } catch (OcException e) {
             e.printStackTrace();
         }
@@ -823,6 +776,8 @@ public class CloudFragment extends Fragment implements
             } catch (OcException e) {
                 e.printStackTrace();
             }
+        } else {
+            msg("Successful unsubscribePresence");
         }
     }
 
@@ -836,13 +791,13 @@ public class CloudFragment extends Fragment implements
     // ******************************************************************************
 
     void getMQBroker() {
-        List<String> resourceTypeList = new ArrayList<String>();
-        List<String> resourceInterfaceList = new ArrayList<String>();
+        List<String> resourceTypeList = new ArrayList<>();
+        List<String> resourceInterfaceList = new ArrayList<>();
         resourceInterfaceList.add(Common.RESOURCE_INTERFACE);
         resourceTypeList.add("ocf.wk.ps");
         try {
             MQbrokerResource = OcPlatform.constructResourceObject(
-                    "coap+tcp://" + Common.TCP_ADDRESS + ":" + Common.TCP_PORT,
+                    Common.HOST,
                     Common.MQ_BROKER_URI,
                     EnumSet.of(OcConnectivityType.CT_ADAPTER_TCP, OcConnectivityType.CT_IP_USE_V4),
                     false,
@@ -875,7 +830,6 @@ public class CloudFragment extends Fragment implements
         synchronized (this) {
             String resourceUri = ocResource.getUri();
 
-            Log.d(TAG, "onTopicDiscoveried : " + resourceUri + " found");
             msg("onTopicDiscoveried : " + resourceUri + " found");
         }
     }
@@ -899,7 +853,7 @@ public class CloudFragment extends Fragment implements
     void createMQTopic() {
         try {
             if (null != MQbrokerResource) {
-                Map<String, String> queryParameters = new HashMap<String, String>();
+                Map<String, String> queryParameters = new HashMap<>();
                 queryParameters.put("rt", "light");
                 MQbrokerResource.createMQTopic(
                         new OcRepresentation(),
@@ -917,11 +871,9 @@ public class CloudFragment extends Fragment implements
     synchronized public void onTopicResourceCreated(OcResource ocResource) {
         synchronized (this) {
             Log.d(TAG, "onTopicResourceCreated");
-            String resourceUri = ocResource.getUri();
             currentTopicResource = ocResource;
-            Log.d(TAG, "onTopicResourceCreated : " + resourceUri + " found");
 
-            msg("onTopicCreated : " + currentTopicResource.getUri());
+            msg("onTopicResourceCreated : " + currentTopicResource.getUri());
         }
     }
 
@@ -945,7 +897,7 @@ public class CloudFragment extends Fragment implements
     }
 
     void subscribeMQTopic() {
-        Map<String, String> queryParameters = new HashMap<String, String>();
+        Map<String, String> queryParameters = new HashMap<>();
         queryParameters.put("rt", "light");
 
         try {
@@ -970,6 +922,7 @@ public class CloudFragment extends Fragment implements
             Log.d(TAG, "onSubScribeCompleted sequenceNumber : " + sequenceNumber);
 
             try {
+                int subFlag;
                 OcRepresentation val = ocRepresentation.getValue("message");
 
                 if (sequenceNumber == 0) {
@@ -1004,7 +957,7 @@ public class CloudFragment extends Fragment implements
             String resourceUri = ocRepresentation.getUri();
             Log.d(TAG, "onUnsubScribeCompleted sequenceNumber : " + sequenceNumber);
 
-            if (sequenceNumber == cancelSubScribe + 1) {
+            if (sequenceNumber == maxSequenceNumber + 1) {
                 Log.d(TAG, "onUnsubScribeCompleted : " + resourceUri);
                 msg("onUnsubScribeCompleted : " + resourceUri);
             }
@@ -1115,7 +1068,6 @@ public class CloudFragment extends Fragment implements
                 }
             };
 
-
     // ******************************************************************************
     // End of the Message Queue specific code
     // ******************************************************************************
@@ -1123,16 +1075,22 @@ public class CloudFragment extends Fragment implements
     private void showTCPInput() {
 
         LayoutInflater layoutInflater = LayoutInflater.from(mContext);
-        View inputView = layoutInflater.inflate(R.layout.tcp_input, null);
+        View inputView = layoutInflater.inflate(R.layout.input, null);
         AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(mActivity);
         alertDialogBuilder.setView(inputView);
 
         final EditText editText = (EditText) inputView.getRootView().findViewById(R.id.inputText);
+        final CheckBox isSecured = (CheckBox) inputView.getRootView().findViewById(R.id.secured);
+
         StringBuilder sb = new StringBuilder();
         sb.append(Common.TCP_ADDRESS);
         sb.append(Common.PORT_SEPARATOR);
         sb.append(Common.TCP_PORT);
         editText.setText(sb.toString());
+
+        isSecured.setVisibility(View.VISIBLE);
+        isSecured.setChecked(mSecured);
+
         alertDialogBuilder
                 .setCancelable(true)
                 .setPositiveButton("OK", new DialogInterface.OnClickListener() {
@@ -1144,9 +1102,14 @@ public class CloudFragment extends Fragment implements
                                 final String host[] = hosts.split(Common.PORT_SEPARATOR);
                                 Common.TCP_ADDRESS = host[0];
                                 Common.TCP_PORT = host[1];
+                                mSecured = isSecured.isChecked();
 
                                 StringBuilder sb = new StringBuilder();
-                                sb.append(Common.COAP_TCP);
+                                if (mSecured) {
+                                    sb.append(Common.COAPS_TCP);
+                                } else {
+                                    sb.append(Common.COAP_TCP);
+                                }
                                 sb.append(Common.TCP_ADDRESS);
                                 sb.append(Common.PORT_SEPARATOR);
                                 sb.append(Common.TCP_PORT);
@@ -1171,7 +1134,7 @@ public class CloudFragment extends Fragment implements
     private void showInviteUser() {
 
         LayoutInflater layoutInflater = LayoutInflater.from(mContext);
-        View inputView = layoutInflater.inflate(R.layout.tcp_input, null);
+        View inputView = layoutInflater.inflate(R.layout.input, null);
         AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(mActivity);
         alertDialogBuilder.setView(inputView);
 
@@ -1187,7 +1150,7 @@ public class CloudFragment extends Fragment implements
                             final String userID = editText.getText().toString();
 
                             try {
-                                Map<String, String> option = new HashMap<String, String>();
+                                Map<String, String> option = new HashMap<>();
                                 option.put("userid", userID);
 
                                 msg("searchUser (User ID: " + userID + ")");
@@ -1236,7 +1199,7 @@ public class CloudFragment extends Fragment implements
                     public void onClick(DialogInterface dialog, int id) {
                         dialog.cancel();
                         try {
-                            msg("gid: " +mGroupId);
+                            msg("gid: " + mGroupId);
                             msg("deleteInvitation");
                             mAccountManager.deleteInvitation(mGroupId, onDeleteInvitation);
                         } catch (OcException e) {
@@ -1288,9 +1251,9 @@ public class CloudFragment extends Fragment implements
         mActionLog.setText("[Action Log]" + EOL);
 
         int viewID = view.getId();
-        if (mAccountManager == null &&
-                (viewID == R.id.signin_button || viewID == R.id.signout_button || viewID == R.id.creategroup_button
-                || viewID == R.id.invite_button || viewID == R.id.leavegroup_button)){
+        if (mAccountManager == null && (viewID == R.id.signin_button
+                || viewID == R.id.signout_button || viewID == R.id.creategroup_button
+                || viewID == R.id.invite_button || viewID == R.id.leavegroup_button)) {
             mActionLog.append("Do 'SignUp' first" + EOL);
             return;
         }
@@ -1361,6 +1324,10 @@ public class CloudFragment extends Fragment implements
                 mActionLog.append("Publish MQ Topic" + EOL);
                 publishMQTopic();
                 break;
+            case R.id.mqreq_button:
+                mActionLog.append("Request MQ Publish" + EOL);
+                requestMQPublish();
+                break;
         }
     }
 
@@ -1373,12 +1340,12 @@ public class CloudFragment extends Fragment implements
         mRDLayout = (LinearLayout) rootView.findViewById(R.id.rd_layout);
         mMQLayout = (LinearLayout) rootView.findViewById(R.id.mq_layout);
 
-        mAccountSwitch = (Switch) rootView.findViewById(R.id.account_switch);
-        mRDSwitch = (Switch) rootView.findViewById(R.id.rd_switch);
-        mMQSwitch = (Switch) rootView.findViewById(R.id.mq_switch);
-        mAccountSwitch.setOnCheckedChangeListener(this);
-        mRDSwitch.setOnCheckedChangeListener(this);
-        mMQSwitch.setOnCheckedChangeListener(this);
+        Switch accountSwitch = (Switch) rootView.findViewById(R.id.account_switch);
+        Switch RDSwitch = (Switch) rootView.findViewById(R.id.rd_switch);
+        Switch MQSwitch = (Switch) rootView.findViewById(R.id.mq_switch);
+        accountSwitch.setOnCheckedChangeListener(this);
+        RDSwitch.setOnCheckedChangeListener(this);
+        MQSwitch.setOnCheckedChangeListener(this);
 
         mAccountText = (TextView) rootView.findViewById(R.id.account_view);
         mRDText = (TextView) rootView.findViewById(R.id.rd_view);
@@ -1387,38 +1354,38 @@ public class CloudFragment extends Fragment implements
         mActionLog = (TextView) rootView.findViewById(R.id.action_log_view);
         mResultLog = (TextView) rootView.findViewById(R.id.result_log_view);
 
-        mSetIPButton = (Button) rootView.findViewById(R.id.setip_button);
-        mSignUpButton = (Button) rootView.findViewById(R.id.signup_button);
-        mSignInButton = (Button) rootView.findViewById(R.id.signin_button);
-        mSignOutButton = (Button) rootView.findViewById(R.id.signout_button);
-        mCreateGroupButton = (Button) rootView.findViewById(R.id.creategroup_button);
-        mInviteButton = (Button) rootView.findViewById(R.id.invite_button);
-        mLeaveGroupButton = (Button) rootView.findViewById(R.id.leavegroup_button);
-        mSetIPButton.setOnClickListener(this);
-        mSignUpButton.setOnClickListener(this);
-        mSignInButton.setOnClickListener(this);
-        mSignOutButton.setOnClickListener(this);
-        mCreateGroupButton.setOnClickListener(this);
-        mInviteButton.setOnClickListener(this);
-        mLeaveGroupButton.setOnClickListener(this);
-
-        mRdPubButton = (Button) rootView.findViewById(R.id.rdpub_button);
-        mRdDelButton = (Button) rootView.findViewById(R.id.rddel_button);
+        Button setIPButton = (Button) rootView.findViewById(R.id.setip_button);
+        Button signUpButton = (Button) rootView.findViewById(R.id.signup_button);
+        Button signInButton = (Button) rootView.findViewById(R.id.signin_button);
+        Button signOutButton = (Button) rootView.findViewById(R.id.signout_button);
+        Button createGroupButton = (Button) rootView.findViewById(R.id.creategroup_button);
+        Button inviteButton = (Button) rootView.findViewById(R.id.invite_button);
+        Button leaveGroupButton = (Button) rootView.findViewById(R.id.leavegroup_button);
+        setIPButton.setOnClickListener(this);
+        signUpButton.setOnClickListener(this);
+        signInButton.setOnClickListener(this);
+        signOutButton.setOnClickListener(this);
+        createGroupButton.setOnClickListener(this);
+        inviteButton.setOnClickListener(this);
+        leaveGroupButton.setOnClickListener(this);
+
+        Button rdPubButton = (Button) rootView.findViewById(R.id.rdpub_button);
+        Button rdDelButton = (Button) rootView.findViewById(R.id.rddel_button);
         mDevicePresenceButton = (Button) rootView.findViewById(R.id.rddp_button);
-        mRdPubButton.setOnClickListener(this);
-        mRdDelButton.setOnClickListener(this);
+        rdPubButton.setOnClickListener(this);
+        rdDelButton.setOnClickListener(this);
         mDevicePresenceButton.setOnClickListener(this);
 
-        mMqBrokerButton = (Button) rootView.findViewById(R.id.mqget_button);
-        mCreateTopicButton = (Button) rootView.findViewById(R.id.mqcreate_button);
-        mSubTopicButton = (Button) rootView.findViewById(R.id.mqsub_button);
-        mUnsubTopicButton = (Button) rootView.findViewById(R.id.mqunsub_button);
-        mPubToicButton = (Button) rootView.findViewById(R.id.mqpub_button);
-        mMqBrokerButton.setOnClickListener(this);
-        mCreateTopicButton.setOnClickListener(this);
-        mSubTopicButton.setOnClickListener(this);
-        mUnsubTopicButton.setOnClickListener(this);
-        mPubToicButton.setOnClickListener(this);
+        Button mqBrokerButton = (Button) rootView.findViewById(R.id.mqget_button);
+        Button createTopicButton = (Button) rootView.findViewById(R.id.mqcreate_button);
+        Button subTopicButton = (Button) rootView.findViewById(R.id.mqsub_button);
+        Button unsubTopicButton = (Button) rootView.findViewById(R.id.mqunsub_button);
+        Button pubToicButton = (Button) rootView.findViewById(R.id.mqpub_button);
+        mqBrokerButton.setOnClickListener(this);
+        createTopicButton.setOnClickListener(this);
+        subTopicButton.setOnClickListener(this);
+        unsubTopicButton.setOnClickListener(this);
+        pubToicButton.setOnClickListener(this);
 
         return rootView;
     }
@@ -1433,5 +1400,4 @@ public class CloudFragment extends Fragment implements
         super.onDestroy();
     }
 
-}
-
+}
\ No newline at end of file
index 4d78391..4eef8a1 100644 (file)
@@ -40,10 +40,11 @@ import java.util.Locale;
 public class Common {
 
     public static final int    DATA_SIZE          = 3000;
-    public static String       HOST               = "coap+tcp://192.168.0.1:8000";
+    public static String       HOST               = "coap+tcp://192.168.0.1:5683";
     public static final String COAP_TCP           = "coap+tcp://";
+    public static final String COAPS_TCP          = "coaps+tcp://";
     public static String       TCP_ADDRESS        = "192.168.0.1";
-    public static String       TCP_PORT           = "8000";
+    public static String       TCP_PORT           = "5683";
     public static final String PORT_SEPARATOR     = ":";
     public static final String IP_ADDRESS         = "0.0.0.0";
     public static final int    IP_PORT            = 0;
index befd6ce..6778978 100644 (file)
@@ -52,7 +52,7 @@ public class DrawerFragment extends Fragment {
     private ListView              mDrawerListView;
     private View                  mFragmentContainerView;
 
-    private int                   mCurrentSelectedPosition = 2;
+    private int                   mCurrentSelectedPosition = 0;
 
     @Override
     public void onCreate(Bundle savedInstanceState) {
index 0012b9f..ef0a4fc 100644 (file)
@@ -91,9 +91,9 @@
                 android:layout_width="match_parent"
                 android:layout_height="wrap_content"
                 android:layout_gravity="center_horizontal"
+                android:layout_marginBottom="2dp"
                 android:gravity="center_horizontal"
-                android:orientation="horizontal"
-                android:layout_marginBottom="2dp">
+                android:orientation="horizontal">
 
                 <Button
                     android:id="@+id/creategroup_button"
                     android:layout_gravity="center_horizontal"
                     android:layout_weight="1"
                     android:text="PUB\nTopic" />
+
+                <Button
+                    android:id="@+id/mqreq_button"
+                    android:layout_width="match_parent"
+                    android:layout_height="wrap_content"
+                    android:layout_gravity="center_horizontal"
+                    android:layout_weight="1"
+                    android:text="REQ\nPUB"
+                    android:visibility="gone" />
             </LinearLayout>
         </LinearLayout>
 
@@ -7,7 +7,7 @@
 
     <TextView
         android:id="@+id/inputView"
-        android:layout_width="wrap_content"
+        android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:text="Input Server IP and Port"
         android:textAppearance="?android:attr/textAppearanceMedium" />
         android:layout_height="wrap_content"
         android:padding="@dimen/activity_vertical_margin" />
 
+    <CheckBox
+        android:id="@+id/secured"
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+        android:text="SECURED"
+        android:visibility="gone" />
+
 </LinearLayout>
\ No newline at end of file
index d10d416..2765bcf 100644 (file)
@@ -22,6 +22,9 @@
     <string name="rd_view">[Resource Directory View]</string>
     <string name="mq_view">[Message Queue View]</string>
 
+    <string name="sub_presence">SUB DEVICE\nPRESENCE</string>
+    <string name="unsub_presence">UNSUBSCRIBE\nPRESENCE</string>
+
     <string name="button_A">Button A</string>
     <string name="button_B">Button B</string>
     <string name="button_C">Button C</string>
index d17e800..7ef2c28 100644 (file)
@@ -36,7 +36,10 @@ def call_scons(build_options, extra_option_str):
     cmd_line += " " + str(extra_option_str)
 
     print ("Running : " + cmd_line)
-    subprocess.Popen([cmd_line], shell=True).wait()
+    sys.stdout.flush()
+    exit_code = subprocess.Popen([cmd_line], shell=True).wait()
+    if exit_code != 0:
+        exit(exit_code)
 
 def build_all(flag, extra_option_str):
     if platform.system() == "Linux":
@@ -160,6 +163,12 @@ def build_android(flag, extra_option_str):
     build_android_armeabi_with_rm(flag, extra_option_str)
 
 def build_android_x86(flag, extra_option_str):
+    """ Build Android x86 Suite """
+    build_android_x86_with_ip(flag, extra_option_str)
+    build_android_x86_with_bt(flag, extra_option_str)
+    build_android_x86_with_ble(flag, extra_option_str)
+
+def build_android_x86_with_ip(flag, extra_option_str):
     print ("*********** Build for android x86 *************")
     build_options = {
                         'TARGET_OS':'android',
@@ -169,13 +178,33 @@ def build_android_x86(flag, extra_option_str):
                     }
     call_scons(build_options, extra_option_str)
 
-    build_options['TARGET_TRANSPORT'] = 'BT'
+def build_android_x86_with_bt(flag, extra_option_str):
+    print ("*********** Build for android x86 with Bluetooth *************")
+    build_options = {
+                        'TARGET_OS':'android',
+                        'TARGET_ARCH':'x86',
+                        'RELEASE':flag,
+                        'TARGET_TRANSPORT':'BT',
+                    }
     call_scons(build_options, extra_option_str)
 
-    build_options['TARGET_TRANSPORT'] = 'BLE'
+def build_android_x86_with_ble(flag, extra_option_str):
+    print ("*********** Build for android x86 with Bluetooth Low Energy *************")
+    build_options = {
+                        'TARGET_OS':'android',
+                        'TARGET_ARCH':'x86',
+                        'RELEASE':flag,
+                        'TARGET_TRANSPORT':'BLE',
+                    }
     call_scons(build_options, extra_option_str)
 
 def build_android_x86_with_rm(flag, extra_option_str):
+    """ Build Android x86 Routing Manager Suite """
+    build_android_x86_with_rm_and_ip(flag, extra_option_str)
+    build_android_x86_with_rm_and_bt(flag, extra_option_str)
+    build_android_x86_with_rm_and_ble(flag, extra_option_str)
+
+def build_android_x86_with_rm_and_ip(flag, extra_option_str):
     print ("*********** Build for android x86 with Routing Manager *************")
     build_options = {
                         'TARGET_OS':'android',
@@ -186,13 +215,35 @@ def build_android_x86_with_rm(flag, extra_option_str):
                     }
     call_scons(build_options, extra_option_str)
 
-    build_options['TARGET_TRANSPORT'] = 'BT'
+def build_android_x86_with_rm_and_bt(flag, extra_option_str):
+    print ("*********** Build for android x86 with Routing Manager and Bluetooth *************")
+    build_options = {
+                        'TARGET_OS':'android',
+                        'TARGET_ARCH':'x86',
+                        'ROUTING':'GW',
+                        'RELEASE':flag,
+                        'TARGET_TRANSPORT':'BT',
+                    }
     call_scons(build_options, extra_option_str)
 
-    build_options['TARGET_TRANSPORT'] = 'BLE'
+def build_android_x86_with_rm_and_ble(flag, extra_option_str):
+    print ("*********** Build for android x86 with Routing Manager and Bluetooth Low Energy *************")
+    build_options = {
+                        'TARGET_OS':'android',
+                        'TARGET_ARCH':'x86',
+                        'ROUTING':'GW',
+                        'RELEASE':flag,
+                        'TARGET_TRANSPORT':'BLE',
+                    }
     call_scons(build_options, extra_option_str)
 
 def build_android_armeabi(flag, extra_option_str):
+    """ Build Android Armeabi Suite """
+    build_android_armeabi_with_ip(flag, extra_option_str)
+    build_android_armeabi_with_bt(flag, extra_option_str)
+    build_android_armeabi_with_ble(flag, extra_option_str)
+
+def build_android_armeabi_with_ip(flag, extra_option_str):
     print ("*********** Build for android armeabi *************")
     build_options = {
                         'TARGET_OS':'android',
@@ -202,14 +253,34 @@ def build_android_armeabi(flag, extra_option_str):
                     }
     call_scons(build_options, extra_option_str)
 
-    build_options['TARGET_TRANSPORT'] = 'BT'
+def build_android_armeabi_with_bt(flag, extra_option_str):
+    print ("*********** Build for android armeabi with Bluetooth *************")
+    build_options = {
+                        'TARGET_OS':'android',
+                        'TARGET_ARCH':'armeabi',
+                        'RELEASE':flag,
+                        'TARGET_TRANSPORT':'BT',
+                    }
     call_scons(build_options, extra_option_str)
 
-    build_options['TARGET_TRANSPORT'] = 'BLE'
+def build_android_armeabi_with_ble(flag, extra_option_str):
+    print ("*********** Build for android armeabi with Bluetooth Low Energy *************")
+    build_options = {
+                        'TARGET_OS':'android',
+                        'TARGET_ARCH':'armeabi',
+                        'RELEASE':flag,
+                        'TARGET_TRANSPORT':'BLE',
+                    }
     call_scons(build_options, extra_option_str)
 
 def build_android_armeabi_with_rm(flag, extra_option_str):
-    print ("*********** Build for android armeabi with Routing Manager*************")
+    """ Build Android Armeabi Routing Manager Suite """
+    build_android_armeabi_with_rm_and_ip(flag, extra_option_str)
+    build_android_armeabi_with_rm_and_bt(flag, extra_option_str)
+    build_android_armeabi_with_rm_and_ble(flag, extra_option_str)
+
+def build_android_armeabi_with_rm_and_ip(flag, extra_option_str):
+    print ("*********** Build for android armeabi with Routing Manager *************")
     build_options = {
                         'TARGET_OS':'android',
                         'TARGET_ARCH':'armeabi',
@@ -219,10 +290,26 @@ def build_android_armeabi_with_rm(flag, extra_option_str):
                     }
     call_scons(build_options, extra_option_str)
 
-    build_options['TARGET_TRANSPORT'] = 'BT'
+def build_android_armeabi_with_rm_and_bt(flag, extra_option_str):
+    print ("*********** Build for android armeabi with Routing Manager and Bluetooth *************")
+    build_options = {
+                        'TARGET_OS':'android',
+                        'TARGET_ARCH':'armeabi',
+                        'ROUTING':'GW',
+                        'RELEASE':flag,
+                        'TARGET_TRANSPORT':'BT',
+                    }
     call_scons(build_options, extra_option_str)
 
-    build_options['TARGET_TRANSPORT'] = 'BLE'
+def build_android_armeabi_with_rm_and_ble(flag, extra_option_str):
+    print ("*********** Build for android armeabi with Routing Manager and Bluetooth Low Energy *************")
+    build_options = {
+                        'TARGET_OS':'android',
+                        'TARGET_ARCH':'armeabi',
+                        'ROUTING':'GW',
+                        'RELEASE':flag,
+                        'TARGET_TRANSPORT':'BLE',
+                    }
     call_scons(build_options, extra_option_str)
 
 def build_arduino(flag, extra_option_str):
@@ -414,8 +501,8 @@ elif arg_num == 2:
         unit_tests()
 
     elif str(sys.argv[1]) == "linux":
-        build_all("true", "")
-        build_all("false", "")
+        build_linux("true", "")
+        build_linux("false", "")
 
     elif str(sys.argv[1]) == "linux_unsecured":
         build_linux_unsecured("true", "")
@@ -461,12 +548,60 @@ elif arg_num == 2:
         build_android_x86_with_rm("true", "")
         build_android_x86_with_rm("false", "")
 
+    elif str(sys.argv[1]) == "android_x86_with_ip":
+        build_android_x86_with_ip("true", "")
+        build_android_x86_with_ip("false", "")
+
+    elif str(sys.argv[1]) == "android_x86_with_bt":
+        build_android_x86_with_bt("true", "")
+        build_android_x86_with_bt("false", "")
+
+    elif str(sys.argv[1]) == "android_x86_with_ble":
+        build_android_x86_with_ble("true", "")
+        build_android_x86_with_ble("false", "")
+
+    elif str(sys.argv[1]) == "android_x86_with_rm_and_ip":
+        build_android_x86_with_rm_and_ip("true", "")
+        build_android_x86_with_rm_and_ip("false", "")
+
+    elif str(sys.argv[1]) == "android_x86_with_rm_and_bt":
+        build_android_x86_with_rm_and_bt("true", "")
+        build_android_x86_with_rm_and_bt("false", "")
+
+    elif str(sys.argv[1]) == "android_x86_with_rm_and_ble":
+        build_android_x86_with_rm_and_ble("true", "")
+        build_android_x86_with_rm_and_ble("false", "")
+
     elif str(sys.argv[1]) == "android_armeabi":
         build_android_armeabi("true", "")
         build_android_armeabi("false", "")
         build_android_armeabi_with_rm("true", "")
         build_android_armeabi_with_rm("false", "")
 
+    elif str(sys.argv[1]) == "android_armeabi_with_ip":
+        build_android_armeabi_with_ip("true", "")
+        build_android_armeabi_with_ip("false", "")
+
+    elif str(sys.argv[1]) == "android_armeabi_with_bt":
+        build_android_armeabi_with_bt("true", "")
+        build_android_armeabi_with_bt("false", "")
+
+    elif str(sys.argv[1]) == "android_armeabi_with_ble":
+        build_android_armeabi_with_ble("true", "")
+        build_android_armeabi_with_ble("false", "")
+
+    elif str(sys.argv[1]) == "android_armeabi_with_rm_and_ip":
+        build_android_armeabi_with_rm_and_ip("true", "")
+        build_android_armeabi_with_rm_and_ip("false", "")
+
+    elif str(sys.argv[1]) == "android_armeabi_with_rm_and_bt":
+        build_android_armeabi_with_rm_and_bt("true", "")
+        build_android_armeabi_with_rm_and_bt("false", "")
+
+    elif str(sys.argv[1]) == "android_armeabi_with_rm_and_ble":
+        build_android_armeabi_with_rm_and_ble("true", "")
+        build_android_armeabi_with_rm_and_ble("false", "")
+
     elif str(sys.argv[1]) == "arduino":
         build_arduino("true", "")
         build_arduino("false", "")
index 59a063f..ae0d8e7 100644 (file)
@@ -6,6 +6,8 @@
 import os
 import platform
 
+project_version = '1.2.0'
+
 # Map of host os and allowed target os (host: allowed target os)
 host_target_map = {
                'linux': ['linux', 'android', 'arduino', 'yocto', 'tizen'],
@@ -24,7 +26,7 @@ os_arch_map = {
                'darwin': ['i386', 'x86_64'],
                'ios': ['i386', 'x86_64', 'armv7', 'armv7s', 'arm64'],
                'arduino': ['avr', 'arm'],
-               'yocto': ['i586', 'x86_64', 'arm', 'powerpc', 'powerpc64', 'mips', 'mipsel'],
+               'yocto': ['i586', 'i686', 'x86_64', 'arm', 'powerpc', 'powerpc64', 'mips', 'mipsel'],
                }
 
 host = platform.system().lower()
@@ -64,6 +66,8 @@ require_upload = ARGUMENTS.get('UPLOAD', False)
 # Get the device name. This name can be used as network display name wherever possible
 device_name = ARGUMENTS.get('DEVICE_NAME', "OIC-DEVICE")
 
+default_with_upstream_libcoap = 0
+
 if ARGUMENTS.get('TEST'):
        logging_default = False
 else:
@@ -73,7 +77,6 @@ else:
        logging_default = (release_mode == False)
 
 
-
 ######################################################################
 # Common build options (release, target os, target arch)
 ######################################################################
@@ -87,6 +90,7 @@ help_vars.Add(EnumVariable('TARGET_OS', 'Target platform', host, host_target_map
 
 help_vars.Add(BoolVariable('WITH_RA', 'Build with Remote Access module', False))
 help_vars.Add(BoolVariable('WITH_TCP', 'Build with TCP adapter', False))
+help_vars.Add(BoolVariable('WITH_PROXY', 'Build with CoAP-HTTP Proxy', False))
 help_vars.Add(ListVariable('WITH_MQ', 'Build with MQ publisher/broker', 'OFF', ['OFF', 'SUB', 'PUB', 'BROKER']))
 help_vars.Add(BoolVariable('WITH_CLOUD', 'Build including AccountManager class and Cloud Client sample', False))
 help_vars.Add(ListVariable('RD_MODE', 'Resource Directory build mode', 'CLIENT', ['CLIENT', 'SERVER']))
@@ -113,6 +117,12 @@ help_vars.AddVariables(('DEVICE_NAME', 'Network display name for device (For Ard
 help_vars.Add(PathVariable('ANDROID_NDK', 'Android NDK path', None, PathVariable.PathAccept))
 help_vars.Add(PathVariable('ANDROID_HOME', 'Android SDK path', None, PathVariable.PathAccept))
 help_vars.Add(PathVariable('ANDROID_GRADLE', 'Gradle binary file', None, PathVariable.PathIsFile))
+help_vars.Add(EnumVariable('WITH_UPSTREAM_LIBCOAP', 'Use latest stable version of LibCoAP downloaded from github', default_with_upstream_libcoap, allowed_values=('0','1')))
+
+if target_os == 'windows':
+       # For VS2013, MSVC_VERSION is '12.0'. For VS2015, MSVC_VERSION is '14.0'.
+       # Default value is None, meaning that SCons has to choose automatically a VS version.
+       help_vars.Add(EnumVariable('MSVC_VERSION', 'MSVC compiler version - Windows', None, allowed_values=('12.0', '14.0')))
 
 AddOption('--prefix',
                   dest='prefix',
@@ -307,30 +317,31 @@ Export('env')
 ######################################################################
 pc_file = env.get('SRC_DIR') + '/iotivity.pc.in'
 
-if env.get('ROUTING') == 'GW':
-       routing_define = 'ROUTING_GATEWAY'
-elif env.get('ROUTING') == 'EP':
-       routing_define = 'ROUTING_EP'
-
 user_prefix = env.get('PREFIX')
 user_lib = env.get('LIB_INSTALL_DIR')
+
+if not user_prefix:
+    user_prefix = env.get('BUILD_DIR').encode('string_escape')
+
 if not user_lib:
-       user_lib = '$${prefix}/lib'
-
-if user_prefix:
-       pc_vars = {'\@PREFIX\@': user_prefix,
-                               '\@EXEC_PREFIX\@':user_prefix,
-                               '\@VERSION\@': '1.1.1',
-                               '\@LIB_INSTALL_DIR\@': user_lib,
-                               '\@ROUTING_DEFINE\@': routing_define
-                               }
-else:
-       pc_vars = {'\@PREFIX\@': env.get('BUILD_DIR').encode('string_escape'),
-                               '\@EXEC_PREFIX\@': env.get('BUILD_DIR').encode('string_escape'),
-                               '\@VERSION\@': '1.1.1',
-                               '\@LIB_INSTALL_DIR\@': user_lib,
-                               '\@ROUTING_DEFINE\@': routing_define
-                               }
+    user_lib = '$${prefix}/lib'
+
+defines = []
+if env.get('LOGGING'):
+    defines.append('-DTB_LOG=1')
+
+if env.get('ROUTING') == 'GW':
+    defines.append('-DROUTING_GATEWAY=1')
+elif env.get('ROUTING') == 'EP':
+    defines.append('-DROUTING_EP=1')
+
+pc_vars = {
+    '\@VERSION\@': project_version,
+    '\@PREFIX\@': user_prefix,
+    '\@EXEC_PREFIX\@': user_prefix,
+    '\@LIB_INSTALL_DIR\@': user_lib,
+    '\@DEFINES\@': " ".join(defines)
+}
 
 env.Substfile(pc_file, SUBST_DICT = pc_vars)
 
@@ -431,52 +442,6 @@ conf = Configure(env,
 # POSIX_SUPPORTED, 1 if it is supported, 0 otherwise
 conf.CheckPThreadsSupport()
 
-######################################################################
-# Generate macros for presence of headers
-######################################################################
-cxx_headers = ['arpa/inet.h',
-               'fcntl.h',
-               'grp.h',
-               'in6addr.h',
-               'linux/limits.h',
-               'memory.h',
-               'netdb.h',
-               'netinet/in.h',
-               'pthread.h',
-               'pwd.h',
-               'stdlib.h',
-               'string.h',
-               'strings.h',
-               'sys/socket.h',
-               'sys/stat.h',
-               'sys/time.h',
-               'sys/timeb.h',
-               'sys/types.h',
-               'sys/unistd.h',
-               'syslog.h',
-               'time.h',
-               'unistd.h',
-               'uuid/uuid.h',
-               'windows.h',
-               'winsock2.h',
-               'ws2tcpip.h']
-
-if target_os == 'arduino':
-       # Detection of headers on the Arduino platform is currently broken.
-       cxx_headers = []
-
-if target_os == 'msys_nt':
-       # WinPThread provides a pthread.h, but we want to use native threads.
-       cxx_headers.remove('pthread.h')
-
-def get_define_from_header_file(header_file):
-       header_file_converted = header_file.replace("/","_").replace(".","_").upper()
-       return "HAVE_" + header_file_converted
-
-for header_file_name in cxx_headers:
-       if conf.CheckCXXHeader(header_file_name):
-               conf.env.AppendUnique(CPPDEFINES = [get_define_from_header_file(header_file_name)])
-
 env = conf.Finish()
 ######################################################################
 
index 20d7c38..fa45866 100644 (file)
@@ -221,8 +221,10 @@ env.AppendUnique(LIBPATH = [src_dir + '/resource/csdk/connectivity/lib/android']
 env.AppendUnique(LIBS = ['log', 'coap'])
 
 if env.get('SECURED') == '1':
+       env.SConscript('#extlibs/tinydtls/SConscript')
        env.AppendUnique(LIBS = ['tinydtls'])
        if env.get('WITH_TCP'):
+               env.SConscript('#extlibs/mbedtls/SConscript')
                env.AppendUnique(LIBS = ['mbedtls','mbedx509','mbedcrypto'])
 
 # From android-5 (API > 20), all application must be built with flags '-fPIE' '-pie'.
index 48eee71..f8a3fb5 100644 (file)
@@ -21,15 +21,10 @@ if env['CC'] == 'cl':
 
     env.AppendUnique(CCFLAGS=['/EHsc'])
 
-    vs_version = env['MSVC_VERSION']
-
     # Set release/debug flags
     if env.get('RELEASE'):
         env.AppendUnique(CCFLAGS = ['/MD', '/O2', '/GF'])
         env.AppendUnique(CPPDEFINES = ['NDEBUG'])
-    elif env.get('TARGET_ARCH') in ['x86', 'x86_64'] or "14.0" in vs_version:
-        env.AppendUnique(CCFLAGS = ['/MDd', '/Od', '/ZI', '/RTC1', '/Gm'])
-        env.AppendUnique(LINKFLAGS = ['/debug'])
     else:
         env.AppendUnique(CCFLAGS = ['/MDd', '/Od', '/Zi', '/RTC1', '/Gm'])
         env.AppendUnique(LINKFLAGS = ['/debug'])
index 1168093..a282d13 100644 (file)
@@ -63,6 +63,8 @@ public class AccountServer {
 
         serverSystem.addResource(new GroupResource());
 
+        serverSystem.addResource(new AclResource());
+
         serverSystem.addResource(new CertificateResource());
 
         serverSystem.addResource(new CrlResource());
index 14e2479..772a051 100644 (file)
@@ -22,6 +22,7 @@
 package org.iotivity.cloud.ciserver;
 
 import java.util.HashMap;
+import java.util.Iterator;
 
 import org.iotivity.cloud.base.OICConstants;
 import org.iotivity.cloud.base.ServerSystem;
@@ -29,6 +30,7 @@ import org.iotivity.cloud.base.connector.ConnectorPool;
 import org.iotivity.cloud.base.device.CoapDevice;
 import org.iotivity.cloud.base.device.Device;
 import org.iotivity.cloud.base.device.IRequestChannel;
+import org.iotivity.cloud.base.exception.ClientException;
 import org.iotivity.cloud.base.exception.ServerException;
 import org.iotivity.cloud.base.exception.ServerException.BadRequestException;
 import org.iotivity.cloud.base.exception.ServerException.UnAuthorizedException;
@@ -41,6 +43,7 @@ import org.iotivity.cloud.base.protocols.enums.ResponseStatus;
 import org.iotivity.cloud.base.server.CoapServer;
 import org.iotivity.cloud.base.server.HttpServer;
 import org.iotivity.cloud.base.server.Server;
+import org.iotivity.cloud.util.Bytes;
 import org.iotivity.cloud.util.Cbor;
 import org.iotivity.cloud.util.Log;
 
@@ -67,13 +70,25 @@ public class DeviceServerSystem extends ServerSystem {
             }
         }
 
-        public void removeDevice(Device device) {
+        public void removeDevice(Device device) throws ClientException {
             String deviceId = ((CoapDevice) device).getDeviceId();
             synchronized (mMapDevice) {
                 if (mMapDevice.get(deviceId) == device) {
                     mMapDevice.remove(deviceId);
                 }
             }
+            removeObserveDevice(device);
+        }
+
+        private void removeObserveDevice(Device device) throws ClientException {
+            Iterator<String> iterator = mMapDevice.keySet().iterator();
+            while (iterator.hasNext()) {
+                String deviceId = iterator.next();
+                CoapDevice getDevice = (CoapDevice) mDevicePool
+                        .queryDevice(deviceId);
+                getDevice.removeObserveChannel(
+                        ((CoapDevice) device).getRequestChannel());
+            }
         }
 
         public Device queryDevice(String deviceId) {
@@ -101,6 +116,31 @@ public class DeviceServerSystem extends ServerSystem {
                         throw new UnAuthorizedException("token is expired");
                     }
 
+                    CoapRequest coapRequest = (CoapRequest) msg;
+                    IRequestChannel targetChannel = null;
+                    if (coapRequest.getUriPathSegments()
+                            .contains(Constants.REQ_DEVICE_ID)) {
+                        CoapDevice targetDevice = (CoapDevice) mDevicePool
+                                .queryDevice(coapRequest.getUriPathSegments()
+                                        .get(1));
+                        targetChannel = targetDevice.getRequestChannel();
+                    }
+                    switch (coapRequest.getObserve()) {
+                        case SUBSCRIBE:
+                            coapDevice.addObserveRequest(
+                                    Bytes.bytesToLong(coapRequest.getToken()),
+                                    coapRequest);
+                            coapDevice.addObserveChannel(targetChannel);
+                            break;
+                        case UNSUBSCRIBE:
+                            coapDevice.removeObserveChannel(targetChannel);
+                            coapDevice.removeObserveRequest(
+                                    Bytes.bytesToLong(coapRequest.getToken()));
+                            break;
+                        default:
+                            break;
+                    }
+
                 } catch (Throwable t) {
                     Log.f(ctx.channel(), t);
                     ResponseStatus responseStatus = t instanceof ServerException
@@ -117,27 +157,30 @@ public class DeviceServerSystem extends ServerSystem {
 
         @Override
         public void channelActive(ChannelHandlerContext ctx) {
-
-            // Authenticated device connected
             Device device = ctx.channel().attr(keyDevice).get();
-            mDevicePool.addDevice(device);
-            device.onConnected();
+            // Authenticated device connected
 
             sendDevicePresence(device.getDeviceId(), "on");
+            mDevicePool.addDevice(device);
+
+            device.onConnected();
         }
 
         @Override
-        public void channelInactive(ChannelHandlerContext ctx) {
+        public void channelInactive(ChannelHandlerContext ctx)
+                throws ClientException {
             Device device = ctx.channel().attr(keyDevice).get();
             // Some cases, this event occurs after new device connected using
             // same di.
             // So compare actual value, and remove if same.
             if (device != null) {
-                mDevicePool.removeDevice(device);
+                sendDevicePresence(device.getDeviceId(), "off");
+
                 device.onDisconnected();
+
+                mDevicePool.removeDevice(device);
                 ctx.channel().attr(keyDevice).remove();
 
-                sendDevicePresence(device.getDeviceId(), "off");
             }
         }
 
index 544133d..c433417 100644 (file)
@@ -6,12 +6,13 @@ Build and Run
 
     http://maven.apache.org
 
-2) Install Apache Kafka if you don't have it
+2) Install Apache Kafka ver.0.9.0.0 if you don't have it
 
     http://kafka.apache.org/downloads.html
 
-    Set 'host.name' in Kafka server configuration file to your ip address,
-      Run Zookeeper server and Kafka broker with the configuration file.
+    Set 'host.name' in Kafka server configuration file('server.properties' file in this folder)
+      to your ip address,
+    Run Zookeeper server and Kafka broker with the configuration file.
 
 3) Build a CloudStack. If you are building first time, then build the stack.
 
index 473a635..ae946ee 100644 (file)
@@ -23,6 +23,8 @@ offsets.topic.num.partitions=1
 
 delete.topic.enable=true
 
+auto.create.topics.enable=false
+
 controlled.shutdown.enable=true
 
 unclean.leader.election.enable=false
index 6feb5cb..369e268 100644 (file)
@@ -83,17 +83,17 @@ public class CoapClient implements IRequestChannel, IResponseEventHandler {
 
             switch (request.getObserve()) {
                 case UNSUBSCRIBE:
-                    newToken = mSubscription.remove(Bytes.bytesToLong(token));
+                    newToken = removeObserve(Bytes.bytesToLong(token));
                     break;
 
                 case SUBSCRIBE:
-                    mSubscription.put(Bytes.bytesToLong(token), newToken);
+                    addObserve(Bytes.bytesToLong(token), newToken);
                 default:
                     // We create temp token
                     // TODO: temporal handling
                     if (request.getUriPath()
                             .equals(OICConstants.RESOURCE_PRESENCE_FULL_URI)) {
-                        mSubscription.put(Bytes.bytesToLong(token), newToken);
+                        addObserve(Bytes.bytesToLong(token), newToken);
                         observe = Observe.SUBSCRIBE;
                     }
                     synchronized (mToken) {
@@ -133,9 +133,31 @@ public class CoapClient implements IRequestChannel, IResponseEventHandler {
         // Subscription response should stored
         if (reqInfo.observe != Observe.SUBSCRIBE) {
             mTokenExchanger.remove(Bytes.bytesToLong(coapResponse.getToken()));
+            if (reqInfo.observe == Observe.UNSUBSCRIBE && mSubscription
+                    .containsKey(Bytes.bytesToLong(reqInfo.originToken))) {
+                mSubscription.remove(Bytes.bytesToLong(reqInfo.originToken));
+            }
         }
 
         coapResponse.setToken(reqInfo.originToken);
         reqInfo.responseHandler.onResponseReceived(response);
     }
+
+    private void addObserve(long token, long newtoken) {
+
+        mSubscription.put(token, newtoken);
+    }
+
+    private Long removeObserve(long token) {
+
+        Long getToken = mSubscription.remove(token);
+        return getToken;
+    }
+
+    public Long isObserveRequest(Long token) {
+        Long getToken = null;
+        getToken = mSubscription.get(token);
+
+        return getToken;
+    }
 }
index a4f3fef..bf57799 100644 (file)
@@ -22,6 +22,7 @@
 package org.iotivity.cloud.base.connector;
 
 import java.net.InetSocketAddress;
+import java.util.ArrayList;
 import java.util.HashMap;
 
 import org.iotivity.cloud.base.device.IRequestChannel;
@@ -44,4 +45,8 @@ public class ConnectorPool {
     public static IRequestChannel getConnection(String name) {
         return mConnection.get(name);
     }
+
+    public static ArrayList<IRequestChannel> getConnectionList() {
+        return new ArrayList<IRequestChannel>(mConnection.values());
+    }
 }
index 1e9d37b..196ecca 100644 (file)
  */
 package org.iotivity.cloud.base.device;
 
+import java.util.ArrayList;
 import java.util.Date;
+import java.util.HashMap;
+import java.util.Iterator;
 
 import org.iotivity.cloud.base.connector.CoapClient;
+import org.iotivity.cloud.base.connector.ConnectorPool;
+import org.iotivity.cloud.base.exception.ClientException;
+import org.iotivity.cloud.base.protocols.IRequest;
 import org.iotivity.cloud.base.protocols.IResponse;
+import org.iotivity.cloud.base.protocols.MessageBuilder;
+import org.iotivity.cloud.base.protocols.coap.CoapRequest;
+import org.iotivity.cloud.base.protocols.coap.CoapResponse;
+import org.iotivity.cloud.base.protocols.enums.Observe;
+import org.iotivity.cloud.base.protocols.enums.ResponseStatus;
+import org.iotivity.cloud.util.Bytes;
 import org.iotivity.cloud.util.Log;
 
 import io.netty.channel.ChannelHandlerContext;
 
 public class CoapDevice extends Device {
-    private CoapClient       mCoapClient    = null;
-    private String           mUserId        = null;
-    private String           mDeviceId      = null;
-    private String           mAccessToken   = null;
-    private Date             mIssuedTime    = null;
-    private int              mExpiredPolicy = 0;
+    private CoapClient                 mCoapClient         = null;
+    private String                     mUserId             = null;
+    private String                     mDeviceId           = null;
+    private String                     mAccessToken        = null;
+    private Date                       mIssuedTime         = null;
+    private int                        mExpiredPolicy      = 0;
+    private ArrayList<IRequestChannel> mObserveChannelList = new ArrayList<>();
+    private HashMap<Long, IRequest>    mObserveRequestList = new HashMap<>();
 
-    private static final int INFINITE_TIME  = -1;
+    private static final int           INFINITE_TIME       = -1;
 
     public CoapDevice(ChannelHandlerContext ctx) {
         super(ctx);
@@ -85,10 +99,60 @@ public class CoapDevice extends Device {
         this.mAccessToken = accessToken;
     }
 
+    public void addObserveChannel(IRequestChannel channel) {
+
+        if (channel != null) {
+            mObserveChannelList.add(channel);
+        }
+    }
+
+    public void removeObserveChannel(IRequestChannel channel)
+            throws ClientException {
+        if (channel != null && mObserveChannelList.contains(channel)) {
+
+            Iterator<Long> iterator = mObserveRequestList.keySet().iterator();
+            while (iterator.hasNext()) {
+                Long token = iterator.next();
+                CoapClient coapClient = (CoapClient) channel;
+                if (coapClient.isObserveRequest(token) != null) {
+                    IRequest getRequest = mObserveRequestList.get(token);
+
+                    CoapRequest coapRequest = (CoapRequest) getRequest;
+                    coapRequest.setObserve(Observe.UNSUBSCRIBE);
+
+                    coapClient.onResponseReceived(MessageBuilder.createResponse(
+                            coapRequest, ResponseStatus.CONTENT, null, null));
+                }
+            }
+            mObserveChannelList.remove(channel);
+        }
+    }
+
+    public void addObserveRequest(Long token, IRequest request) {
+
+        mObserveRequestList.put(token, request);
+    }
+
+    public void removeObserveRequest(Long token) {
+
+        mObserveRequestList.remove(token);
+    }
+
     // This is called by cloud resource model
     @Override
     public void sendResponse(IResponse response) {
         // This message must converted to CoapResponse
+        CoapResponse coapResp = (CoapResponse) response;
+
+        Iterator<Long> iterator = mObserveRequestList.keySet().iterator();
+        while (iterator.hasNext()) {
+            Long token = iterator.next();
+            Long respToken = Bytes.bytesToLong(coapResp.getToken());
+            if (respToken.equals(token)
+                    && coapResp.getObserve().equals(Observe.UNSUBSCRIBE)) {
+                iterator.remove();
+            }
+        }
         ctx.channel().writeAndFlush(response);
     }
 
@@ -121,10 +185,26 @@ public class CoapDevice extends Device {
 
     @Override
     public void onConnected() {
+        mObserveChannelList.addAll(ConnectorPool.getConnectionList());
     }
 
     @Override
     public void onDisconnected() {
+        for (IRequestChannel serverChannel : mObserveChannelList) {
+            Iterator<Long> iterator = mObserveRequestList.keySet().iterator();
+            while (iterator.hasNext()) {
+                Long token = iterator.next();
+                CoapClient coapClient = (CoapClient) serverChannel;
+
+                if (coapClient.isObserveRequest(token) != null) {
+                    CoapRequest coapRequest = (CoapRequest) mObserveRequestList
+                            .get(token);
+                    coapRequest.setObserve(Observe.UNSUBSCRIBE);
+                    coapRequest.setToken(Bytes.longTo8Bytes(token));
+                    serverChannel.sendRequest(MessageBuilder.modifyRequest(
+                            coapRequest, null, null, null, null), this);
+                }
+            }
+        }
     }
-
 }
index d29c324..d127ccf 100644 (file)
@@ -1,3 +1,4 @@
+# -*- mode: python; python-indent-offset: 4; indent-tabs-mode: nil -*-
 ##
 # 'googletest' script to check if Google Unit Test library is installed.
 # If not, get it and install it
@@ -17,7 +18,7 @@ gtest_dir      = os.path.join(src_dir, 'extlibs', 'gtest', 'gtest-1.7.0')
 gtest_lib_dir = os.path.join(gtest_dir,'lib')
 gtest_dotlib_dir =  os.path.join(gtest_lib_dir, '.libs')
 gtest_zip_file = os.path.join(src_dir, 'extlibs', 'gtest', 'gtest-1.7.0.zip')
-gtest_url      = 'https://googletest.googlecode.com/files/gtest-1.7.0.zip'
+gtest_url = 'http://pkgs.fedoraproject.org/repo/pkgs/gtest/gtest-1.7.0.zip/2d6ec8ccdf5c46b05ba54a9fd1d130d7/gtest-1.7.0.zip'
 
 if target_os in targets_need_gtest:
        print '*** Checking for installation of google unit test 1.7.0 ***'
@@ -96,71 +97,18 @@ elif target_os == 'msys_nt':
                        gtest_env.Configure(gtest_dir, 'mv libgtest_main.a lib/.libs')
 
 elif target_os == 'windows':
-       if os.path.exists(gtest_dir):
-               if gtest_env.get('RELEASE'):
-                       output_dir = os.path.join(gtest_dir, 'Release') + os.sep
-               else:
-                       output_dir = os.path.join(gtest_dir, 'Debug') + os.sep
-
-               # Three parts to the gtest config string...
-               # 1. "Visual Studio" toolchain name.
-               # 2. VS Version + Year ("14 2015", "12 2013").
-               # 3. Target Architecture ("Win64", "Win32").
-               vs_version_year = ""
-               vs_target_arch  = ""
-               vs_num = env['MSVC_VERSION']
-               if "12.0" in vs_num:
-                       vs_version_year = "Visual Studio 12 2013"
-               elif "14.0" in vs_num:
-                       vs_version_year = "Visual Studio 14 2015"
-               else:
-                       print "Error: unknown Visual Studio version %s" % vs_num
-
-               vs_arch = env['TARGET_ARCH']
-               if "amd64" in vs_arch:
-                       vs_target_arch = "Win64"
-               elif "x86" in vs_arch:
-                       vs_target_arch = ""
-               else:
-                       print "Error: unknown Visual Studio target arch %s" % vs_arch
-
-               vs_target_string = vs_version_year + " " + vs_target_arch
-
-               # Exit if we didn't get a match for one of the above.
-               if not vs_version_year or not vs_target_arch:
-                       Exit(1)
-
-               if not gtest_env.WhereIs('cmake', gtest_env.get('PATH')):
-                       print '''*********************** Error ************************
-*                                                    *
-* Please make sure that CMake is in your System PATH *
-*                                                    *
-* You can download CMake from:                       *
-*            https://cmake.org/download/             *
-*                                                    *
-******************************************************
-'''
-                       Exit(1)
-
-               if not os.path.exists(gtest_lib_dir):
-                       # Create lib dir
-                       os.mkdir(gtest_lib_dir)
-                       os.mkdir(gtest_dotlib_dir)
-
-                       # Run configure on gtest
-                       print 'Configuring google unit test for compilation'
-                       gtest_env.Configure(gtest_dir, 'cmake . -G"' + vs_target_string + '" -Dgtest_force_shared_crt=ON')
-
-                       # Run make on gtest
-                       print 'Making google unit test'
-                       gtest_env.Configure(gtest_dir, 'msbuild gtest.vcxproj')
-                       gtest_env.Configure(gtest_dir, 'msbuild gtest_main.vcxproj')
-
-                       print 'Moving libraries to lib folder'
-                       gtest_env.Configure(gtest_dir, 'copy '+output_dir+'gtest.lib %s' % gtest_lib_dir)
-                       gtest_env.Configure(gtest_dir, 'move '+output_dir+'gtest.lib %s' % gtest_dotlib_dir )
-                       gtest_env.Configure(gtest_dir, 'copy '+output_dir+'gtest_main.lib %s' % gtest_lib_dir)
-                       gtest_env.Configure(gtest_dir, 'move '+output_dir+'gtest_main.lib %s' % gtest_dotlib_dir)
+       # Avoid building the same StaticLibrary in more than one environment, by using the
+       # IOTIVITY_GTEST_HAS_BEEN_BUILT environment variable
+       if not env.has_key('IOTIVITY_GTEST_HAS_BEEN_BUILT'):
+               gtest_env.Append(CPPPATH = [ gtest_dir ])
+               gtest = gtest_env.StaticLibrary(target = 'gtest', source = [ '%s/src/gtest-all.cc' % gtest_dir ])
+               gtest_main = gtest_env.StaticLibrary(target = 'gtest_main', source = [ '%s/src/gtest_main.cc' % gtest_dir ])
+               gtest_env.InstallTarget(gtest, 'gtest')
+               gtest_env.InstallTarget(gtest_main, 'gtest_main')
+
+               vars = Variables();
+               vars.AddVariables(('IOTIVITY_GTEST_HAS_BEEN_BUILT', '', '1'))
+               vars.Update(env)
 
 # Export flags once for all
 if target_os in targets_need_gtest:
@@ -176,5 +124,7 @@ if target_os in targets_need_gtest:
                        gtest_env.AppendUnique(CXXFLAGS = ['-pthread'])
                        gtest_env.PrependUnique(LIBS = ['pthread'])
        gtest_env.PrependUnique(LIBS = ['gtest', 'gtest_main'])
+       if target_os in ['windows']:
+               gtest_env.AppendUnique(LINKFLAGS = ['/subsystem:CONSOLE'])
 
 Return('gtest_env')
index 5832177..0826f97 100644 (file)
@@ -31,8 +31,7 @@ Import('env')
 target_os = env.get('TARGET_OS')
 src_dir = env.get('SRC_DIR')
 
-# Only verify/install on linux
-if target_os in ['linux']:
+if target_os in ['linux', 'windows']:
        print '*** Checking for installation of hippomocks ***'
 
        hippomocks_sha      = '8e210c5808d490b26fff69151c801fa28d291fcb'
diff --git a/extlibs/libcoap/SConscript b/extlibs/libcoap/SConscript
new file mode 100644 (file)
index 0000000..52a75ac
--- /dev/null
@@ -0,0 +1,170 @@
+################################################################################
+#
+# Copyright 2016 Intel Corporation
+#
+#
+#
+# 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.
+#
+################################################################################
+
+##
+# 'libcoap' script to check if LibCoAP library is installed.  If not,
+# get it and install it
+#
+##
+
+import os
+import glob
+
+Import('env')
+
+libcoap_env = env.Clone()
+target_os = libcoap_env.get('TARGET_OS')
+src_dir = libcoap_env.get('SRC_DIR')
+ca_transport = libcoap_env.get('TARGET_TRANSPORT')
+with_tcp = libcoap_env.get('WITH_TCP')
+with_upstream_libcoap = libcoap_env.get('WITH_UPSTREAM_LIBCOAP')
+
+# Temporary LibCoAP URL is a fork of the original.
+# Once a pull request is merged, change this back to the obgm original below.
+libcoap_repo_url    = 'https://github.com/dthaler/libcoap'
+#libcoap_repo_url    = 'https://github.com/obgm/libcoap'
+
+######################################################################
+# Download libCoAP
+######################################################################
+libcoap_branch           = 'develop'
+libcoap_dir              = os.path.join(src_dir, 'extlibs', 'libcoap', 'libcoap')
+libcoap_zip_file         = os.path.join(src_dir, 'extlibs', 'libcoap', libcoap_branch + '.zip')
+libcoap_url              = libcoap_repo_url + '/archive/' + libcoap_branch + '.zip'
+libcoap_checkout_command = 'git clone ' + libcoap_repo_url + '.git extlibs/libcoap/libcoap --branch ' + libcoap_branch
+
+if with_upstream_libcoap == '1':
+    print '*** Checking for installation of libCoAP ***'
+    if not os.path.exists(libcoap_dir):
+        # If the libcoap zip file is not already present, download it
+        if not os.path.exists(libcoap_zip_file):
+            libcoap_zip = libcoap_env.Download(libcoap_zip_file, libcoap_url)
+        else:
+            libcoap_zip = libcoap_zip_file
+        # Unzip libcoap
+        if libcoap_zip and not os.path.exists(os.path.join(libcoap_dir, 'configure')):
+            print 'Unzipping libCoAP'
+            env.UnpackAll(libcoap_dir, libcoap_zip)
+        # Rename libcoap
+        libcoap_unzip_dir = os.path.join(src_dir, 'extlibs', 'libcoap', 'libcoap-' + libcoap_branch)
+        if os.path.exists(os.path.join(libcoap_unzip_dir)):
+            os.rename(libcoap_unzip_dir, libcoap_dir)
+        if not os.path.exists(os.path.join(libcoap_dir, 'README')):
+            print '''
+*********************************** Error: ****************************************
+* Unable to download and unpack libcoap!                                          *
+* Please download libcoap using the following command:                            *
+*                                                                                 *
+''' + libcoap_checkout_command + '''
+*                                                                                 *
+***********************************************************************************'''
+            Exit()
+else:
+    print '''
+*********************************** Info: *****************************************
+* Using FORKED copy of libCoap located in:                                        *
+* resource/csdk/connectivity/lib/libcoap-4.1.1                                    *
+***********************************************************************************'''
+
+######################################################################
+# Build libCoAP
+######################################################################
+# As in the source code(C) includes arduino Time library head file(C++)
+# It requires compile the .c with g++
+if target_os == 'arduino':
+    libcoap_env.Replace(CFLAGS = libcoap_env.get('CXXFLAGS'))
+    libcoap_env.PrependUnique(CPPPATH = [
+        './',
+        env.get('ARDUINO_HOME') + '/',
+        env.get('ARDUINO_HOME') + '/hardware/arduino/avr/cores/arduino',
+        env.get('ARDUINO_HOME') + '/hardware/tools/avr/avr/include/',
+        env.get('ARDUINO_HOME') + '/hardware/arduino/avr/variants/mega',
+        env.get('ARDUINO_HOME') + '/libraries/Time/Time',
+        env.get('ARDUINO_HOME') + '/libraries/TimedAction',
+        env.get('ARDUINO_HOME') + '/hardware/arduino/avr/libraries/SPI',
+        env.get('ARDUINO_HOME') + '/libraries/Ethernet/src/utility',
+        ])
+
+# Build flags
+if target_os not in ['arduino', 'windows', 'winrt', 'msys_nt']:
+    libcoap_env.AppendUnique(CPPDEFINES = ['WITH_POSIX', '_DEFAULT_SOURCE'])
+    libcoap_env.AppendUnique(CFLAGS = ['-std=gnu99','-fPIC'])
+
+if target_os not in ['windows', 'winrt']:
+    libcoap_env.AppendUnique(CFLAGS = ['-Wall', '-ffunction-sections',
+            '-fdata-sections', '-fno-exceptions'])
+
+if target_os == 'msys_nt':
+    libcoap_env.AppendUnique(CPPDEFINES = ['_DEFAULT_SOURCE'])
+    libcoap_env.AppendUnique(CFLAGS = ['-std=c99'])
+
+if target_os in ['linux', 'tizen', 'android', 'ios', 'arduino']:
+    if with_tcp == True:
+        libcoap_env.AppendUnique(CPPDEFINES = ['WITH_TCP'])
+
+if target_os in ['linux', 'tizen', 'android', 'arduino']:
+    libcoap_env.AppendUnique(LIBS = ['log'])
+    if (('BLE' in ca_transport) or ('BT' in ca_transport) or ('ALL' in ca_transport)):
+        libcoap_env.AppendUnique(CPPDEFINES = ['WITH_TCP'])
+
+if target_os == 'arduino':
+    libcoap_env.AppendUnique(CPPDEFINES = ['NDEBUG', 'WITH_ARDUINO'])
+
+if target_os in ['darwin', 'ios']:
+    libcoap_env.AppendUnique(CPPDEFINES = ['_DARWIN_C_SOURCE'])
+
+if env.get('LOGGING') == '1':
+    libcoap_env.AppendUnique(CPPDEFINES = ['TB_LOG'])
+
+######################################################################
+# Source files and Target(s)
+######################################################################
+with_upstream_libcoap = libcoap_env.get('WITH_UPSTREAM_LIBCOAP')
+if with_upstream_libcoap == '1':
+    libcoap_env.PrependUnique(CPPPATH = ['libcoap/include/coap'])
+    libcoap_env.AppendUnique(CPPDEFINES = ['WITH_UPSTREAM_LIBCOAP'])
+    libcoap_src_root = os.path.join(libcoap_dir, 'src')
+
+    # We need to generate coap.h from coap.h.in
+    coap_h_pc_file = os.path.join(libcoap_dir, 'include', 'coap', 'coap.h.in')
+    coap_h_output  = os.path.join(libcoap_dir, 'include', 'coap', 'coap.h')
+
+    libcoap_version = libcoap_branch
+    lib_prefix = '' + str(libcoap_env.get('PREFIX'))
+    pc_vars = {
+        '\@LIBCOAP_PACKAGE_NAME\@'          : lib_prefix + 'coap',
+        '\@LIBCOAP_PACKAGE_STRING\@'        : lib_prefix + 'coap-' + libcoap_version,
+        '\@LIBCOAP_PACKAGE_URL\@'           : libcoap_repo_url,
+        '\@LIBCOAP_PACKAGE_BUGREPORT\@'     : libcoap_repo_url + '/issues',
+        '\@LIBCOAP_PACKAGE_VERSION\@'       : libcoap_version
+        }
+    libcoap_env.Substfile(coap_h_pc_file, SUBST_DICT = pc_vars)
+
+    libcoap_src = glob.glob(os.path.join(libcoap_src_root, '*.c'))
+    libcoap_src.remove(os.path.join(libcoap_src_root, 'coap_io_lwip.c'))
+else:
+    # For bring up purposes only, the forked version will live here.
+    libcoap_src_root = src_dir + '/resource/csdk/connectivity/lib/libcoap-4.1.1'
+    libcoap_src = glob.glob(os.path.join(libcoap_src_root, '*.c'))
+
+libcoap = libcoap_env.StaticLibrary('coap', libcoap_src, OBJPREFIX='libcoap_')
+
+libcoap_env.InstallTarget([libcoap], 'coap')
+
index f774ecd..9d20cb2 100644 (file)
@@ -21,6 +21,7 @@ EXT_PATH = EXT_BASE + '/' + SRC_NAME
 SRC_PATH = base_dir + '/' + EXT_PATH
 INC_PATH = SRC_PATH
 LIB_PATH = SRC_PATH + '/' + '.libs'
+LIBSTROPHY_LIBS = ['strophe', 'ssl', 'crypto', 'resolv']
 
 if with_ra_ibb:
        # check 'libstrophe' library, if it doesn't exits, ask user to download it
@@ -44,32 +45,40 @@ if with_ra_ibb:
                else:
                        print 'Download xmpp library complete'
 
-       print 'Building with ' + SRC_NAME
-       #print 'base_dir', base_dir
-       #print 'target_os', target_os
-       #print 'target_arch', target_arch
-
-       foo=commands.getoutput('patch -N -p1 -d libstrophe < strophe-xmpp_conn_is_secured.patch')
-       print foo
-
-       os.chdir(SRC_NAME)
-       #sconsflags = ' RELEASE=true' if  env['RELEASE'] else ' RELEASE=false'
-       if not os.path.exists('configure') :
-               foo=commands.getoutput('./bootstrap.sh')
-               print foo
-       if not os.path.exists('config.status') :
-               foo=commands.getoutput('./configure')
+       if not env.GetOption('clean'):
+               print 'Building with ' + SRC_NAME
+               #print 'base_dir', base_dir
+               #print 'target_os', target_os
+               #print 'target_arch', target_arch
+       
+               foo=commands.getoutput('patch -N -p1 -d libstrophe < strophe-xmpp_conn_is_secured.patch')
                print foo
-       if not os.path.exists('.libs/libstrophe.a') :
-               foo=commands.getoutput('make libstrophe.la')
-               print foo
-       if not os.path.exists('.libs/libstrophe.a') :
-               print 'Building with ' + SRC_NAME + ' failed.'
-               Exit(2)
+               os.chdir(SRC_NAME)
+               #sconsflags = ' RELEASE=true' if  env['RELEASE'] else ' RELEASE=false'
+               if not os.path.exists('configure') :
+                       foo=commands.getoutput('./bootstrap.sh')
+                       print foo
+               if not os.path.exists('config.status') :
+                       foo=commands.getoutput('./configure')
+                       print foo
+               if not os.path.exists('.libs/libstrophe.a') :
+                       foo=commands.getoutput('make libstrophe.la')
+                       print foo
+               if not os.path.exists('.libs/libstrophe.a') :
+                       print 'Building with ' + SRC_NAME + ' failed.'
+                       Exit(2)
+               else:
+                       foo = commands.getoutput('cp .libs/libstrophe.a ' + env.get('BUILD_DIR'))
+                       foo = commands.getoutput('cp .libs/libstrophe.so* ' + env.get('BUILD_DIR'))
+                       print foo
 
-       print 'Building with ' + SRC_NAME + ' Completely.'
-       env.AppendUnique(CPPPATH = [INC_PATH], RALIBS = ['strophe', 'ssl', 'crypto', 'resolv'], RALIBPATH = [LIB_PATH], RARPATH = [LIB_PATH])
+               print 'Building with ' + SRC_NAME + ' Completely.'
+       env.AppendUnique(CPPPATH = [INC_PATH], RALIBS = LIBSTROPHY_LIBS, RALIBPATH = [LIB_PATH], RARPATH = [LIB_PATH])
+       env.AppendUnique(LIBS= LIBSTROPHY_LIBS, LIBPATH = [LIB_PATH])
 
-if env.GetOption('clean') :
+if env.GetOption('clean'):
        act = env.Action(['cd ' + SRC_PATH, 'make clean'])
        env.Execute(act)
+       if os.path.isfile(env.get('BUILD_DIR') + '/libstrophe.a'):
+               act2 = env.Action(['rm ' + env.get('BUILD_DIR') + '/libstrophe.*'])
+               env.Execute(act2)
index 3dda84b..08b9a6e 100755 (executable)
@@ -22,6 +22,7 @@
 
 #define _BSD_SOURCE
 
+#include "iotivity_config.h"
 #ifdef HAVE_WINDOWS_H
 #include <windows.h>
 #endif
@@ -40,7 +41,6 @@
 #ifdef HAVE_STRING_H
 #include <string.h>
 #endif
-#include "platform_features.h"
 
 #include <stdio.h>
 
index 3ad432a..ffa304c 100644 (file)
@@ -21,6 +21,7 @@
 #ifndef TIMER_H_
 #define TIMER_H_
 
+#include "iotivity_config.h"
 #ifdef HAVE_SYS_TIME_H
 #include <sys/time.h>
 #endif
index cb6cb8c..3b593ce 100644 (file)
@@ -4301,6 +4301,7 @@ handle_ccs(dtls_context_t *ctx, dtls_peer_t *peer,
           uint8 *record_header, uint8 *data, size_t data_length)
 {
   int err;
+  dtls_handshake_parameters_t *handshake;
 
   /* A CCS message is handled after a KeyExchange message was
    * received from the client. When security parameters have been
@@ -4316,7 +4317,7 @@ handle_ccs(dtls_context_t *ctx, dtls_peer_t *peer,
   if (data_length < 1 || data[0] != 1)
     return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
 
-  dtls_handshake_parameters_t *handshake = peer->handshake_params;
+  handshake = peer->handshake_params;
   /* Just change the cipher when we are on the same epoch */
   if (peer->role == DTLS_SERVER) {
     err = calculate_key_block(ctx, handshake, peer,
index 08f1a30..9c71254 100644 (file)
@@ -1,3 +1,4 @@
+#include "iotivity_config.h" 
 #include "tinydtls.h" 
 
 /* This is needed for apple */
@@ -28,7 +29,6 @@
 #endif
 #include <signal.h>
 #include <getopt.h>
-#include "platform_features.h"
 
 #include "global.h"
 #include "debug.h"
index 9a8918a..07acd18 100644 (file)
@@ -2,6 +2,7 @@
 /* This is needed for apple */
 #define __APPLE_USE_RFC_3542
 
+#include "iotivity_config.h"
 #include <assert.h>
 #include <stdio.h>
 #include <string.h>
index eca7ff7..7921b08 100644 (file)
@@ -52,7 +52,7 @@
 #  if defined(__cplusplus)
 #    define INLINE_API inline
 #  else
-#    ifdef _WIN32
+#    ifdef _MSC_VER
 #      define INLINE_API static __inline
 #    else
 #      define INLINE_API static inline
index c6bb6ce..f8e9b2c 100644 (file)
@@ -20,6 +20,7 @@ EXT_PATH = EXT_BASE + '/' + SRC_NAME
 SRC_PATH = base_dir + '/' + EXT_PATH
 INC_PATH = SRC_PATH + '/include'
 LIB_PATH = SRC_PATH
+WJSXMPPXEP_LIBS = ['wksxmppxep', 'm', 'crypto']
 
 if with_ra_ibb:
        env.SConscript(base_dir + '/extlibs/libstrophe/SConscript')
@@ -43,21 +44,31 @@ if with_ra_ibb:
                else:
                        print 'Download', SRC_NAME, 'library complete'
 
-       print 'Building with ' + SRC_NAME
-       os.chdir(SRC_NAME)
-       if not os.path.exists('libwksxmppxep.so') :
-               LIBSTROPHE_BASE=base_dir + '/extlibs/libstrophe/libstrophe'
-               foo=commands.getoutput('make LIBSTROPHE_BASE=' + LIBSTROPHE_BASE + ' libraries')
-               print foo
-
-       if not os.path.exists('libwksxmppxep.so') :
-               print 'Building with ' + SRC_NAME + ' failed.'
-               Exit(2)
-
-       print 'Building with ' + SRC_NAME + ' Completely.'
+       if not env.GetOption('clean'):
+               print 'Building with ' + SRC_NAME
+               os.chdir(SRC_NAME)
+               if not os.path.exists('libwksxmppxep.so') :
+                       LIBSTROPHE_BASE=base_dir + '/extlibs/libstrophe/libstrophe'
+                       foo=commands.getoutput('make LIBSTROPHE_BASE=' + LIBSTROPHE_BASE + ' libraries')
+                       print foo
+               if not os.path.exists('libwksxmppxep.so') :
+                       print 'Building with ' + SRC_NAME + ' failed.'
+                       Exit(2)
+               else:
+                       foo = commands.getoutput('cp libwksxmppxep.so ' + env.get('BUILD_DIR'))
+                       print foo
+                       foo = commands.getoutput('cp libwksxmppxep.a ' + env.get('BUILD_DIR'))
+                       print foo
+       
+               print 'Building with ' + SRC_NAME + ' Completely.'
 
-       env.PrependUnique(CPPPATH = [INC_PATH], RALIBS = ['wksxmppxep', 'm', 'crypto'], RALIBPATH = [LIB_PATH], RARPATH = [LIB_PATH])
+       env.PrependUnique(CPPPATH = [INC_PATH], RALIBS = WJSXMPPXEP_LIBS, RALIBPATH = [LIB_PATH], RARPATH = [LIB_PATH])
+       env.AppendUnique(LIBS = WJSXMPPXEP_LIBS, LIBPATH = [LIB_PATH])
+       env.AppendUnique(LIBS = ['boost_system', 'boost_thread'])
 
 if env.GetOption('clean') :
        act = env.Action(['cd ' + SRC_PATH, 'make clean'])
        env.Execute(act)
+       if os.path.isfile(env.get('BUILD_DIR') + '/libwksxmppxep.so'):
+               act2 = env.Action(['rm ' + env.get('BUILD_DIR') + '/libwksxmppxep.*'])
+               env.Execute(act2)
\ No newline at end of file
index 633a286..72ef981 100755 (executable)
@@ -36,6 +36,7 @@ cp -R ./extlibs/tinydtls $sourcedir/tmp/extlibs
 cp -LR ./extlibs/sqlite3 $sourcedir/tmp/extlibs
 cp -R ./extlibs/timer $sourcedir/tmp/extlibs
 cp -R ./extlibs/rapidxml $sourcedir/tmp/extlibs
+cp -R ./extlibs/libcoap $sourcedir/tmp/extlibs
 cp -R ./resource $sourcedir/tmp
 cp -R ./service $sourcedir/tmp
 cp ./extra_options.scons $sourcedir/tmp
index 59bd6b5..f5c06c9 100644 (file)
@@ -13,9 +13,10 @@ URL: https://www.iotivity.org
 Requires:
 Libs: -L${libdir} -loc -loc_logger -loc_logger_core -loctbstack -lconnectivity_abstraction
 Cflags: -I${includedir}/resource \
+                       -I${includedir}/c_common \
                        -I${svcincludedir}/resource-encapsulation \
                        -I${svcincludedir}/resource-container \
                        -I${svcincludedir}/resource-hosting \
                        -I${svcincludedir}/resource-directory \
                        -I${svcincludedir}/things-manager \
-                       -D@ROUTING_DEFINE@
+                       @DEFINES@
index a586483..1cca407 100644 (file)
@@ -34,14 +34,20 @@ print"Reading PI script"
 ######################################################################
 # Build flags
 ######################################################################
+with_unforked_libcoap = env.get('WITH_UNFORKED_LIBCOAP')
+if with_unforked_libcoap == '1':
+    # For bring up purposes only, we manually copy the forked version to where the unforked version is downloaded.
+    env.PrependUnique(CPPPATH = ['#extlibs/libcoap/libcoap/include'])
+else:
+    # For bring up purposes only, the forked version will live here.
+    env.PrependUnique(CPPPATH = [os.path.join(src_dir, 'resource', 'csdk', 'connectivity', 'lib', 'libcoap-4.1.1', 'include')])
 
 env.PrependUnique(CPPPATH = [ os.path.join(src_dir, 'resource', 'c_common', 'oic_malloc', 'include'),
                               os.path.join(src_dir, 'resource', 'c_common', 'oic_string', 'include'),
                               os.path.join(src_dir, 'resource', 'c_common', 'oic_time', 'include'),
                               os.path.join(src_dir, 'resource', 'oc_logger', 'include'),
                               os.path.join(src_dir, 'resource', 'csdk', 'logger', 'include'),
-                              os.path.join(src_dir, 'resource', 'csdk', 'stack', 'include'),
-                              os.path.join(src_dir, 'resource', 'csdk', 'connectivity', 'lib', 'libcoap-4.1.1')
+                              os.path.join(src_dir, 'resource', 'csdk', 'stack', 'include')
                             ])
 env.AppendUnique(CPPPATH = [ os.path.join(pi_path, 'include'),
                              os.path.join(pi_path, 'include', 'internal'),
index 01c7adc..2b5b661 100644 (file)
@@ -24,7 +24,7 @@
 #include <string.h>
 
 #include "zigbee_wrapper.h"
-#include "utlist.h"
+#include <coap/utlist.h>
 #include "oic_malloc.h"
 #include "oic_string.h"
 #include "ocstack.h"
index 6b4092f..ebd6bc7 100644 (file)
@@ -36,7 +36,8 @@ extern "C" {
 
 #include "plugintypes.h"
 #include "telegesis_socket.h"
-#include "utlist.h"
+
+#include <coap/utlist.h>
 
 // TODO: Use OICThread instead of pthread directly.
 // TODO: Use OICMutex instead of mutex directly.
index 1542c2f..decd536 100644 (file)
@@ -34,8 +34,8 @@ SConscript('csdk/logger/SConscript')
 if target_os not in ['arduino', 'darwin', 'ios', 'android', 'msys_nt', 'windows']:
        env.AppendUnique(LIBS=['rt'])
 
-# Build libcoap
-SConscript('csdk/connectivity/lib/libcoap-4.1.1/SConscript')
+# Download (if not already present) & build libcoap
+SConscript('#extlibs/libcoap/SConscript')
 
 # Build C Common dependencies
 SConscript('c_common/SConscript')
@@ -69,8 +69,9 @@ if target_os in ['linux', 'windows']:
        SConscript('csdk/stack/test/linux/SConscript')
        SConscript('csdk/stack/samples/linux/SimpleClientServer/SConscript')
 
-       # Build secure samples
-       SConscript('csdk/stack/samples/linux/secure/SConscript')
+        if env.get('SECURED') == '1':
+               # Build secure samples
+               SConscript('csdk/stack/samples/linux/secure/SConscript')
 
        # Build C/C++ unit tests
        SConscript('unit_tests.scons')
index f412655..8613ad8 100644 (file)
 
 Import('env')
 import os
+import datetime
 
 target_os = env.get('TARGET_OS')
+target_arch = env.get('TARGET_ARCH')
 
+######################################################################
+# Generate iotivity_config.h using presence of headers
+######################################################################
+
+config_h_env = env.Clone()
+conf = Configure(config_h_env)
+
+config_h_header = '''
+/* ****************************************************************************
+ * iotivity_config.h - IoTivity platform-specific configuration header.
+ *
+ * Auto-generated code for the %s %s platform.
+ *
+ * Generated at %s
+ *
+ *************************************************************************** */
+
+#ifndef IOTIVITY_CONFIG_H__
+#define IOTIVITY_CONFIG_H__
+
+#include "platform_features.h"
+
+''' % (str(target_os), str(target_arch), str(datetime.datetime.utcnow()))
+
+config_h_body = ''
+
+config_h_footer = '''
+
+#endif // IOTIVITY_CONFIG_H__
+
+'''
+
+cxx_headers = ['arpa/inet.h',
+               'fcntl.h',
+               'grp.h',
+               'in6addr.h',
+               'linux/limits.h',
+               'memory.h',
+               'netdb.h',
+               'netinet/in.h',
+               'pthread.h',
+               'pwd.h',
+               'stdlib.h',
+               'string.h',
+               'strings.h',
+               'sys/socket.h',
+               'sys/stat.h',
+               'sys/time.h',
+               'sys/timeb.h',
+               'sys/types.h',
+               'sys/unistd.h',
+               'syslog.h',
+               'time.h',
+               'unistd.h',
+               'uuid/uuid.h',
+               'windows.h',
+               'winsock2.h',
+               'ws2tcpip.h']
+
+if target_os == 'arduino':
+       # Detection of headers on the Arduino platform is currently broken.
+       cxx_headers = []
+
+if target_os == 'msys_nt':
+       # WinPThread provides a pthread.h, but we want to use native threads.
+       cxx_headers.remove('pthread.h')
+
+def get_define_from_header_file(header_file):
+       header_file_converted = header_file.replace("/","_").replace(".","_").upper()
+       return "HAVE_" + header_file_converted
+
+for header_file_name in cxx_headers:
+       if conf.CheckCXXHeader(header_file_name):
+               config_h_body += "#define %s 1\n\n" % get_define_from_header_file(header_file_name)
+conf.Finish()
+
+# Autoconf feature doesn't work with Jenkins' arduino toolchain, so hardcode it here.
+if target_os == 'arduino':
+       config_h_body += "#define HAVE_ARDUINO_TIME_H\n\n"
+
+# Generate the file
+src_dir = env.get('SRC_DIR')
+config_h_file_path = os.path.join(src_dir, 'resource', 'c_common', 'iotivity_config.h')
+if os.path.exists(config_h_file_path):
+       os.remove(config_h_file_path)
+config_h_file = open(config_h_file_path, "w")
+config_h_file.write(config_h_header + config_h_body + config_h_footer)
+config_h_file.close()
+
+# Sanity check to ensure that the above block created the file.
+if not os.path.exists(config_h_file_path):
+       print "Error: iotivity_config.h file not created!"
+
+# iotivity_config.h should be copied to the build dir
+env.UserInstallTargetHeader(config_h_file_path, 'c_common', 'iotivity_config.h')
+
+# Use the generated file internally
+env.AppendUnique(CPPPATH = [os.path.join(src_dir, 'resource', 'c_common')])
+
+######################################################################
+
+######################################################################
 # Add platform-specific helper library
+######################################################################
+
 if target_os in ['windows', 'msys_nt']:
        SConscript('windows/SConscript')
 
 env.AppendUnique(CPPPATH = [
-            os.path.join(Dir('.').abspath),
             os.path.join(Dir('.').abspath, 'oic_malloc', 'include'),
             os.path.join(Dir('.').abspath, 'oic_string', 'include'),
             os.path.join(Dir('.').abspath, 'oic_time', 'include'),
-            os.path.join(Dir('.').abspath, 'ocrandom', 'include')
+            os.path.join(Dir('.').abspath, 'ocrandom', 'include'),
+            os.path.join(Dir('.').abspath, 'octhread', 'include')
         ])
 
 if target_os == 'tizen':
@@ -45,7 +151,6 @@ if target_os in ['tizen', 'linux']:
        env.ParseConfig("pkg-config --cflags --libs uuid")
 
 common_env = env.Clone()
-common_env.AppendUnique(LIBPATH = [os.path.join(env.get('BUILD_DIR'), 'resource')])
 
 ######################################################################
 # Build flags
@@ -62,12 +167,19 @@ common_src = [
        'oic_string/src/oic_string.c',
        'oic_malloc/src/oic_malloc.c',
        'oic_time/src/oic_time.c',
-       'ocrandom/src/ocrandom.c',
+       'ocrandom/src/ocrandom.c'
        ]
 
+if env['POSIX_SUPPORTED']:
+       common_src.append('octhread/src/posix/octhread.c')
+elif target_os  in ['windows']:
+       common_src.append('octhread/src/windows/octhread.c')
+else:
+       common_src.append('octhread/src/noop/octhread.c')
+
 commonlib = common_env.StaticLibrary('c_common', common_src)
 common_env.InstallTarget(commonlib, 'c_common')
 common_env.UserInstallTargetLib(commonlib, 'c_common')
-common_env.UserInstallTargetHeader('platform_features.h', 'resource', 'platform_features.h')
+common_env.UserInstallTargetHeader('platform_features.h', 'c_common', 'platform_features.h')
 
 env.PrependUnique(LIBS = ['c_common'])
index 118aeee..32c4b4b 100644 (file)
@@ -30,7 +30,8 @@
 #define _POSIX_C_SOURCE 200809L
 #endif
 
-#include "platform_features.h"
+#include "iotivity_config.h"
+
 #ifdef HAVE_FCNTL_H
 #include <fcntl.h>
 #endif
index d6ac4dc..632f22c 100644 (file)
@@ -37,7 +37,8 @@ randomtest_env.PrependUnique(CPPPATH = [
 
 randomtest_env.AppendUnique(LIBPATH = [randomtest_env.get('BUILD_DIR')])
 randomtest_env.PrependUnique(LIBS = ['octbstack',
-                                    'uuid'])
+                                     'connectivity_abstraction',
+                                     'uuid'])
 
 if target_os in ['linux']:
     randomtest_env.AppendUnique(LIBS = ['m'])
@@ -52,13 +53,13 @@ if randomtest_env.get('LOGGING'):
 ######################################################################
 # Source files and Targets
 ######################################################################
-randomtests = randomtest_env.Program('randomtests', ['linux/randomtest.cpp'])
+randomtests = randomtest_env.Program('randomtests', ['randomtest.cpp'])
 
 Alias("test", [randomtests])
 
 randomtest_env.AppendTarget('test')
 if randomtest_env.get('TEST') == '1':
-       if target_os in ['linux']:
+       if target_os in ['linux', 'windows']:
                 from tools.scons.RunTest import *
                 run_test(randomtest_env,
                          'resource_csdk_random_test.memcheck',
diff --git a/resource/c_common/ocrandom/test/android/randomtest.cpp b/resource/c_common/ocrandom/test/android/randomtest.cpp
deleted file mode 100644 (file)
index 07028e2..0000000
+++ /dev/null
@@ -1,104 +0,0 @@
-
-//******************************************************************
-//
-// 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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-extern "C" {
-    #include "ocrandom.h"
-}
-
-#include "gtest/gtest.h"
-#include "math.h"
-
-
-int main(int argc, char* argv[]) {
-    testing::InitGoogleTest(&argc, argv);
-    return RUN_ALL_TESTS();
-}
-
-TEST(RandomGeneration,OCSeedRandom) {
-    EXPECT_EQ((uint32_t )0, OCSeedRandom());
-}
-
-TEST(RandomGeneration,OCGetRandomByte) {
-    uint8_t value = OCGetRandomByte();
-    EXPECT_LE((uint8_t )0, value);
-    EXPECT_GT(pow(2, 8), value);
-}
-
-TEST(RandomGeneration,OCGetRandom) {
-    uint32_t value = OCGetRandom();
-    EXPECT_LE((uint8_t )0, value);
-    EXPECT_GT(pow(2, 32), value);
-}
-
-TEST(RandomGeneration,OCFillRandomMem) {
-    uint16_t ARR_SIZE = 20;
-    uint8_t array[ARR_SIZE]={};
-    OCFillRandomMem(array + 1, ARR_SIZE - 2);
-
-    for (int i = 1; i < ARR_SIZE - 2; i++) {
-        uint8_t value = array[i];
-        EXPECT_LE((uint8_t )0, value);
-        EXPECT_GT(pow(2, 8), value);
-    }
-    EXPECT_EQ((uint8_t )0, array[0]);
-    EXPECT_EQ((uint8_t )0, array[ARR_SIZE - 1]);
-}
-
-TEST(RandomGeneration, OCGenerateUuid)
-{
-    EXPECT_EQ(RAND_UUID_INVALID_PARAM, OCGenerateUuid(NULL));
-
-    uint8_t uuid[16] = {};
-
-    EXPECT_EQ(RAND_UUID_OK, OCGenerateUuid(uuid));
-
-    EXPECT_FALSE(uuid[0] == '0' && uuid[1] == '0' &&
-                 uuid[2] == '0' && uuid[3] == '0' &&
-                 uuid[4] == '0' && uuid[5] == '0' &&
-                 uuid[6] == '0' && uuid[7] == '0' &&
-                 uuid[8] == '0' && uuid[9] == '0' &&
-                 uuid[10] == '0' && uuid[11] == '0' &&
-                 uuid[12] == '0' && uuid[13] == '0' &&
-                 uuid[14] == '0' && uuid[15] == '0');
-}
-
-TEST(RandomGeneration, OCGenerateUuidString)
-{
-    EXPECT_EQ(RAND_UUID_INVALID_PARAM, OCGenerateUuidString(NULL));
-
-    char uuidString[37] ={};
-
-    EXPECT_EQ(RAND_UUID_OK, OCGenerateUuidString(uuidString));
-    EXPECT_EQ(0, uuidString[36]);
-    EXPECT_EQ('-', uuidString[8]);
-    EXPECT_EQ('-', uuidString[13]);
-    EXPECT_EQ('-', uuidString[18]);
-    EXPECT_EQ('-', uuidString[23]);
-
-    for(int i = 0; i < 36; ++i)
-    {
-        EXPECT_TRUE(
-                i == 8 || i == 13 || i == 18 || i == 23 ||
-                (uuidString[i] >= 'a' && uuidString[i] <= 'f') ||
-                (uuidString[i] >= '0' && uuidString[i] <= '9'))
-                << "UUID Character out of range: "<< uuidString[i];
-    }
-}
@@ -25,40 +25,27 @@ extern "C" {
 }
 
 #include "gtest/gtest.h"
-#include "math.h"
 
 #define ARR_SIZE (20)
 
-int main(int argc, char* argv[]) {
-    testing::InitGoogleTest(&argc, argv);
-    return RUN_ALL_TESTS();
-}
-
 TEST(RandomGeneration,OCSeedRandom) {
     EXPECT_EQ(0, OCSeedRandom());
 }
 
 TEST(RandomGeneration,OCGetRandomByte) {
-    uint8_t value = OCGetRandomByte();
-    EXPECT_LE((uint8_t )0, value);
-    EXPECT_GT(pow(2, 8), value);
+    EXPECT_NO_THROW(OCGetRandomByte());
 }
 
 TEST(RandomGeneration,OCGetRandom) {
-    uint32_t value = OCGetRandom();
-    EXPECT_LE((uint8_t )0, value);
-    EXPECT_GT(pow(2, 32), value);
+    EXPECT_NO_THROW(OCGetRandom());
 }
 
-TEST(RandomGeneration,OCFillRandomMem) {
+TEST(RandomGeneration,OCFillRandomMem_BoundsCheck) {
     uint8_t array[ARR_SIZE] = {};
+
+    // Ignore the first and last bytes of the array
     OCFillRandomMem(array + 1, ARR_SIZE - 2);
 
-    for (int i = 1; i <= ARR_SIZE - 2; i++) {
-        uint8_t value = array[i];
-        EXPECT_LE((uint8_t )0, value);
-        EXPECT_GT(pow(2, 8), value);
-    }
     EXPECT_EQ((uint8_t )0, array[0]);
     EXPECT_EQ((uint8_t )0, array[ARR_SIZE - 1]);
 }
diff --git a/resource/c_common/octhread/include/octhread.h b/resource/c_common/octhread/include/octhread.h
new file mode 100644 (file)
index 0000000..c9a6062
--- /dev/null
@@ -0,0 +1,197 @@
+/* ****************************************************************
+ *
+ * Copyright 2014 Samsung Electronics 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.
+ *
+ ******************************************************************/
+
+/**
+ * @file
+ *
+ * This file provides APIs related to mutex and semaphores.
+ */
+
+#ifndef OC_THREAD_H_
+#define OC_THREAD_H_
+
+#include <stdbool.h>
+#include <stdlib.h>
+#include <stdint.h>
+
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif /* __cplusplus */
+
+typedef struct oc_mutex_internal *oc_mutex;
+typedef struct oc_cond_internal *oc_cond;
+typedef struct oc_thread_internal *oc_thread;
+
+/**
+ * Enums for oc_cond_wait_for return values.
+ */
+typedef enum
+{
+   OC_WAIT_SUCCESS = 0,    /**< Condition Signal. */
+   OC_WAIT_INVAL = -1,     /**< Invalid Condition. */
+   OC_WAIT_TIMEDOUT = -2   /**< Condition Timed Out. */
+} OCWaitResult_t;
+
+typedef enum
+{
+    OC_THREAD_SUCCESS = 0,
+    OC_THREAD_ALLOCATION_FAILURE = 1,
+    OC_THREAD_CREATE_FAILURE=2,
+    OC_THREAD_INVALID=3,
+    OC_THREAD_WAIT_FAILURE=4,
+    OC_THREAD_INVALID_PARAMETER=5
+} OCThreadResult_t;
+
+/**
+ * Allocates, and starts a new thread
+ *
+ * @param[out] t  The thread that will refer to a newly allocated, and started thread
+ * @param[in] start_routine The function that will execute in a new thread
+ * @param[in] arg The information passed to the start_routine
+ * @return OCThreadResult_t An enumeration of possible outcomes
+ * @retval OC_THREAD_SUCCESS If a thread was successfully allocated and started.
+ * @retval OC_THREAD_ALLOCATION_FAILURE If a thread was unable to be allocated
+ * @retval OC_THREAD_CREATE_FAILURE If a thread was unable to be started
+ *
+ */
+OCThreadResult_t oc_thread_new(oc_thread *t, void *(*start_routine)(void *), void *arg);
+
+/**
+ * Frees a thread previously allocated with oc_thread_new()
+ *
+ * @param[in] t The thread to be unallocated
+ * @return OCThreadResult_t An enumeration of possible outcomes
+ * @retval OC_THREAD_SUCCESS If a thread was successfully unallocated
+ * @retval OC_THREAD_INVALID_PARAMETER If param t is NULL
+ *
+ */
+OCThreadResult_t oc_thread_free(oc_thread t);
+
+/**
+ * Block until a thread's execution has been completed
+ *
+ * @param[in] t The thread to be waited on
+ * @return OCThreadResult_t An enumeration of possible outcomes
+ * @retval OC_THREAD_SUCCESS If the thread successfully completed execution
+ * @retval OC_THREAD_WAIT_FAILURE If a problem occured while waiting for execution of the thread to complete
+ *
+ */
+OCThreadResult_t oc_thread_wait(oc_thread t);
+
+/**
+ * Creates new mutex.
+ *
+ * @return  Reference to newly created mutex, otherwise NULL.
+ *
+ */
+oc_mutex oc_mutex_new(void);
+
+/**
+ * Lock the mutex.
+ *
+ * @param  mutex  The mutex to be locked.
+ *
+ */
+void oc_mutex_lock(oc_mutex mutex);
+
+/**
+ * Unlock the mutex.
+ *
+ * @param  mutex  The mutex to be unlocked.
+ *
+ */
+void oc_mutex_unlock(oc_mutex mutex);
+
+/**
+ * Free the mutex.
+ *
+ * @param  mutex  The mutex to be freed.
+ * @return bool to indicate success or failure
+ * @retval true if mutex was freed successfully
+ * @retval false if mutex parameter is invalid
+ *
+ */
+bool oc_mutex_free(oc_mutex mutex);
+
+/**
+ * Creates new condition.
+ *
+ * @return  Reference to newly created oc_cond, otherwise NULL.
+ *
+ */
+oc_cond oc_cond_new(void);
+
+/**
+ * One of threads is woken up if multiple threads are waiting for cond.
+ *
+ * @param  cond  The condtion to be signaled.
+ *
+ */
+void oc_cond_signal(oc_cond cond);
+
+/**
+ * All of threads are woken up if multiple threads are waiting for cond.
+ *
+ * @param  cond  The condtion to be signaled.
+ *
+ */
+void oc_cond_broadcast(oc_cond cond);
+
+/**
+ * Waits until this thread woken up on cond.
+ *
+ * @param  cond  The condtion to be wait for to signal.
+ * @param  mutex  The mutex which is currently locked from calling thread.
+ *
+ */
+void oc_cond_wait(oc_cond cond, oc_mutex mutex);
+
+/**
+ * Waits until this thread woken up on cond,
+ * but not longer than the interval specified by microseconds.
+ * The mutex is unlocked before falling asleep and locked again before resuming.
+ * If microseconds is 0, oc_cond_wait_for() acts like oc_cond_wait().
+ *
+ * @param  cond  The condtion to be wait for to signal.
+ * @param  mutex  The mutex which is currently locked from calling thread.
+ * @param  microseconds  relative time for waiting, microseconds.
+ *
+ * @return OC_WAIT_SUCCESS if the condition was signaled,
+ *         OC_WAIT_TIMEDOUT if wait period exceeded,
+ *         OC_WAIT_INVAL for invalid parameters.
+ *
+ */
+OCWaitResult_t oc_cond_wait_for(oc_cond cond, oc_mutex mutex, uint64_t microseconds);
+
+/**
+ * Free the condition.
+ *
+ * @param  cond  The condition to be freed.
+ *
+ */
+void oc_cond_free(oc_cond cond);
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif /* __cplusplus */
+
+#endif /* OC_THREAD_H_ */
@@ -26,8 +26,7 @@
  * This file provides APIs related to mutex with no operation
  * for Singlethread implementation.
  */
-
-#include "camutex.h"
+#include "octhread.h"
 
 /**
  * TAG
 
 typedef struct _tagMutexInfo_t
 {
-#if defined(_MSC_VER)
-    uint8_t unused; //VS doesnt like empty structs
-#endif
-} ca_mutex_internal;
+} oc_mutex_internal;
 
 typedef struct _tagEventInfo_t
 {
-#if defined(_MSC_VER)
-    uint8_t unused; //VS doesnt like empty structs
-#endif
-} ca_cond_internal;
+} oc_cond_internal;
+
+typedef struct _tagThreadInfo_t
+{
+} oc_thread_internal;
+
 
 /**
  * @var g_mutexInfo
- * @brief This is used to return a non NULL value for ca_mutex_new().
+ * @brief This is used to return a non NULL value for oc_mutex_new().
  */
-static ca_mutex_internal g_mutexInfo = { 0 };
+static oc_mutex_internal g_mutexInfo = { 0 };
 
 /**
  * @var g_condInfo
- * @brief This is used to return a non NULL value for ca_cond_new().
+ * @brief This is used to return a non NULL value for oc_cond_new().
  */
-static ca_cond_internal g_condInfo = { 0 };
+static oc_cond_internal g_condInfo = { 0 };
+
+OCThreadResult_t oc_thread_new(oc_thread *t, void *(*start_routine)(void *), void *arg)
+{
+    return OC_THREAD_CREATE_FAILURE;
+}
+
+OCThreadResult_t oc_thread_free(oc_thread t)
+{
+    return OC_THREAD_INVALID;
+}
+
+OCThreadResult_t oc_thread_wait(oc_thread t)
+{
+    return OC_THREAD_INVALID;
+}
 
-ca_mutex ca_mutex_new(void)
+oc_mutex oc_mutex_new(void)
 {
-    return (ca_mutex)&g_mutexInfo;
+    return (oc_mutex)&g_mutexInfo;
 }
 
-bool ca_mutex_free(ca_mutex mutex)
+bool oc_mutex_free(oc_mutex mutex)
 {
     return true;
 }
 
-void ca_mutex_lock(ca_mutex mutex)
+void oc_mutex_lock(oc_mutex mutex)
 {
     return;
 }
 
-void ca_mutex_unlock(ca_mutex mutex)
+void oc_mutex_unlock(oc_mutex mutex)
 {
     return;
 }
 
-ca_cond ca_cond_new(void)
+oc_cond oc_cond_new(void)
 {
-    return (ca_cond)&g_condInfo;
+    return (oc_cond)&g_condInfo;
 }
 
-void ca_cond_free(ca_cond cond)
+void oc_cond_free(oc_cond cond)
 {
     return;
 }
 
-void ca_cond_signal(ca_cond cond)
+void oc_cond_signal(oc_cond cond)
 {
     return;
 }
 
-void ca_cond_broadcast(ca_cond cond)
+void oc_cond_broadcast(oc_cond cond)
 {
     return;
 }
 
-void ca_cond_wait(ca_cond cond, ca_mutex mutex)
+void oc_cond_wait(oc_cond cond, oc_mutex mutex)
 {
     return;
 }
 
-CAWaitResult_t ca_cond_wait_for(ca_cond cond, ca_mutex mutex, uint64_t microseconds)
+OCWaitResult_t oc_cond_wait_for(oc_cond cond, oc_mutex mutex, uint64_t microseconds)
 {
-    return CA_WAIT_SUCCESS;
+    return OC_WAIT_SUCCESS;
 }
 
@@ -36,6 +36,8 @@
 #define _POSIX_C_SOURCE 200809L
 #endif
 
+#include "iotivity_config.h"
+#include "octhread.h"
 #ifdef HAVE_STRING_H
 #include <string.h>
 #endif
 #ifdef HAVE_SYS_TIME_H
 #include <sys/time.h>
 #endif
-#ifdef HAVE_WINSOCK2_H
-#include <winsock2.h>
-#endif
 #include <stdio.h>
 #include <errno.h>
 #include <assert.h>
 #include <oic_malloc.h>
-#include "platform_features.h"
-#include "camutex.h"
 #include "logger.h"
 
 /**
@@ -90,45 +87,96 @@ static const uint64_t NANOSECS_PER_SEC      = 1000000000L;
 
 typedef struct _tagMutexInfo_t
 {
-#if defined(_WIN32)
-    CRITICAL_SECTION mutex;
-#else
     pthread_mutex_t mutex;
-#endif
-} ca_mutex_internal;
+} oc_mutex_internal;
 
 typedef struct _tagEventInfo_t
 {
-#if defined(_WIN32)
-    CONDITION_VARIABLE cond;
-#else
     pthread_cond_t cond;
     pthread_condattr_t condattr;
-#endif
-} ca_cond_internal;
+} oc_cond_internal;
+
+typedef struct _tagThreadInfo_t
+{
+    pthread_t thread;
+    pthread_attr_t  threadattr;
+} oc_thread_internal;
+
+OCThreadResult_t oc_thread_new(oc_thread *t, void *(*start_routine)(void *), void *arg)
+{
+    OCThreadResult_t res = OC_THREAD_SUCCESS;
+    oc_thread_internal *threadInfo = (oc_thread_internal*)OICMalloc(sizeof(oc_thread_internal));
+    if (NULL != threadInfo)
+    {
+        int result = pthread_create(&threadInfo->thread, NULL, start_routine, arg);
+        if (result != 0)
+        {
+            res = OC_THREAD_CREATE_FAILURE;
+            *t = NULL;
+            OICFree(threadInfo);
+            OIC_LOG_V(ERROR, TAG, "%s: pthread_create failed", __func__);
+        }
+        else
+        {
+            *t = (oc_thread)threadInfo;
+        }
+    }
+    else
+    {
+        OIC_LOG_V(ERROR, TAG, "%s Failed to allocate thread!", __func__);
+        *t = NULL;
+        res = OC_THREAD_ALLOCATION_FAILURE;
+    }
+    return res;
+}
+
+OCThreadResult_t oc_thread_free(oc_thread t)
+{
+    OCThreadResult_t res = OC_THREAD_SUCCESS;
+    oc_thread_internal *threadInfo = (oc_thread_internal*) t;
+    if (threadInfo)
+    {
+        OICFree(threadInfo);
+    }
+    else
+    {
+        OIC_LOG_V(ERROR, TAG, "%s Invalid thread !", __func__);
+        res = OC_THREAD_INVALID;
+    }
+    return res;
+}
+
+OCThreadResult_t oc_thread_wait(oc_thread t)
+{
+    OCThreadResult_t res = OC_THREAD_SUCCESS;
+    oc_thread_internal *threadInfo = (oc_thread_internal*) t;
+    int joinres = pthread_join(threadInfo->thread, NULL);
+    if (0 != joinres)
+    {
+        OIC_LOG_V(ERROR, TAG, "Failed to join thread with error %d", joinres);
+        res = OC_THREAD_WAIT_FAILURE;
+    }
+
+    return res;
+}
 
-ca_mutex ca_mutex_new(void)
+oc_mutex oc_mutex_new(void)
 {
-    ca_mutex retVal = NULL;
-    ca_mutex_internal *mutexInfo = (ca_mutex_internal*) OICMalloc(sizeof(ca_mutex_internal));
+    oc_mutex retVal = NULL;
+    oc_mutex_internal *mutexInfo = (oc_mutex_internal*) OICMalloc(sizeof(oc_mutex_internal));
     if (NULL != mutexInfo)
     {
-#if defined(_WIN32)
-        InitializeCriticalSection(&mutexInfo->mutex);
-        retVal = (ca_mutex)mutexInfo;
-#else
         // create the mutex with the attributes set
         int ret=pthread_mutex_init(&(mutexInfo->mutex), PTHREAD_MUTEX_DEFAULT);
         if (0 == ret)
         {
-            retVal = (ca_mutex) mutexInfo;
+            retVal = (oc_mutex) mutexInfo;
         }
         else
         {
             OIC_LOG_V(ERROR, TAG, "%s Failed to initialize mutex !", __func__);
             OICFree(mutexInfo);
         }
-#endif
     }
     else
     {
@@ -138,18 +186,12 @@ ca_mutex ca_mutex_new(void)
     return retVal;
 }
 
-bool ca_mutex_free(ca_mutex mutex)
+bool oc_mutex_free(oc_mutex mutex)
 {
     bool bRet=false;
-
-    ca_mutex_internal *mutexInfo = (ca_mutex_internal*) mutex;
+    oc_mutex_internal *mutexInfo = (oc_mutex_internal*) mutex;
     if (mutexInfo)
     {
-#if defined(_WIN32)
-        DeleteCriticalSection(&mutexInfo->mutex);
-        OICFree(mutexInfo);
-        bRet=true;
-#else
         int ret = pthread_mutex_destroy(&mutexInfo->mutex);
         if (0 == ret)
         {
@@ -160,7 +202,6 @@ bool ca_mutex_free(ca_mutex mutex)
         {
             OIC_LOG_V(ERROR, TAG, "%s Failed to free mutex !", __func__);
         }
-#endif
     }
     else
     {
@@ -170,37 +211,29 @@ bool ca_mutex_free(ca_mutex mutex)
     return bRet;
 }
 
-void ca_mutex_lock(ca_mutex mutex)
+void oc_mutex_lock(oc_mutex mutex)
 {
-    ca_mutex_internal *mutexInfo = (ca_mutex_internal*) mutex;
+    oc_mutex_internal *mutexInfo = (oc_mutex_internal*) mutex;
     if (mutexInfo)
     {
-#if defined(_WIN32)
-        EnterCriticalSection(&mutexInfo->mutex);
-#else
         int ret = pthread_mutex_lock(&mutexInfo->mutex);
         if(ret != 0)
         {
             OIC_LOG_V(ERROR, TAG, "Pthread Mutex lock failed: %d", ret);
             exit(ret);
         }
-#endif
     }
     else
     {
         OIC_LOG_V(ERROR, TAG, "%s Invalid mutex !", __func__);
-        return;
     }
 }
 
-void ca_mutex_unlock(ca_mutex mutex)
+void oc_mutex_unlock(oc_mutex mutex)
 {
-    ca_mutex_internal *mutexInfo = (ca_mutex_internal*) mutex;
+    oc_mutex_internal *mutexInfo = (oc_mutex_internal*) mutex;
     if (mutexInfo)
     {
-#if defined(_WIN32)
-        LeaveCriticalSection(&mutexInfo->mutex);
-#else
         int ret = pthread_mutex_unlock(&mutexInfo->mutex);
         if(ret != 0)
         {
@@ -208,25 +241,19 @@ void ca_mutex_unlock(ca_mutex mutex)
             exit(ret);
         }
         (void)ret;
-#endif
     }
     else
     {
         OIC_LOG_V(ERROR, TAG, "%s: Invalid mutex !", __func__);
-        return;
     }
 }
 
-ca_cond ca_cond_new(void)
+oc_cond oc_cond_new(void)
 {
-    ca_cond retVal = NULL;
-    ca_cond_internal *eventInfo = (ca_cond_internal*) OICMalloc(sizeof(ca_cond_internal));
+    oc_cond retVal = NULL;
+    oc_cond_internal *eventInfo = (oc_cond_internal*) OICMalloc(sizeof(oc_cond_internal));
     if (NULL != eventInfo)
     {
-#if defined(_WIN32)
-        InitializeConditionVariable(&eventInfo->cond);
-        retVal = (ca_cond) eventInfo;
-#else
         int ret = pthread_condattr_init(&(eventInfo->condattr));
         if(0 != ret)
         {
@@ -258,7 +285,7 @@ ca_cond ca_cond_new(void)
         ret = pthread_cond_init(&(eventInfo->cond), &(eventInfo->condattr));
         if (0 == ret)
         {
-            retVal = (ca_cond) eventInfo;
+            retVal = (oc_cond) eventInfo;
         }
         else
         {
@@ -266,7 +293,6 @@ ca_cond ca_cond_new(void)
             pthread_condattr_destroy(&(eventInfo->condattr));
             OICFree(eventInfo);
         }
-#endif
     }
     else
     {
@@ -276,14 +302,11 @@ ca_cond ca_cond_new(void)
     return retVal;
 }
 
-void ca_cond_free(ca_cond cond)
+void oc_cond_free(oc_cond cond)
 {
-    ca_cond_internal *eventInfo = (ca_cond_internal*) cond;
+    oc_cond_internal *eventInfo = (oc_cond_internal*) cond;
     if (eventInfo != NULL)
     {
-#if defined(_WIN32)
-        OICFree(cond);
-#else
         int ret = pthread_cond_destroy(&(eventInfo->cond));
         int ret2 = pthread_condattr_destroy(&(eventInfo->condattr));
         if (0 == ret && 0 == ret2)
@@ -295,7 +318,6 @@ void ca_cond_free(ca_cond cond)
             OIC_LOG_V(ERROR, TAG, "%s: Failed to destroy condition variable %d, %d",
                     __func__, ret, ret2);
         }
-#endif
     }
     else
     {
@@ -303,20 +325,16 @@ void ca_cond_free(ca_cond cond)
     }
 }
 
-void ca_cond_signal(ca_cond cond)
+void oc_cond_signal(oc_cond cond)
 {
-    ca_cond_internal *eventInfo = (ca_cond_internal*) cond;
+    oc_cond_internal *eventInfo = (oc_cond_internal*) cond;
     if (eventInfo != NULL)
     {
-#if defined(_WIN32)
-        WakeConditionVariable(&eventInfo->cond);
-#else
         int ret = pthread_cond_signal(&(eventInfo->cond));
         if (0 != ret)
         {
             OIC_LOG_V(ERROR, TAG, "%s: Failed to signal condition variable", __func__);
         }
-#endif
     }
     else
     {
@@ -324,20 +342,16 @@ void ca_cond_signal(ca_cond cond)
     }
 }
 
-void ca_cond_broadcast(ca_cond cond)
+void oc_cond_broadcast(oc_cond cond)
 {
-    ca_cond_internal* eventInfo = (ca_cond_internal*) cond;
+    oc_cond_internal* eventInfo = (oc_cond_internal*) cond;
     if (eventInfo != NULL)
     {
-#if defined(_WIN32)
-        WakeAllConditionVariable(&eventInfo->cond);
-#else
         int ret = pthread_cond_broadcast(&(eventInfo->cond));
         if (0 != ret)
         {
             OIC_LOG_V(ERROR, TAG, "%s: failed to signal condition variable", __func__);
         }
-#endif
     }
     else
     {
@@ -345,9 +359,9 @@ void ca_cond_broadcast(ca_cond cond)
     }
 }
 
-void ca_cond_wait(ca_cond cond, ca_mutex mutex)
+void oc_cond_wait(oc_cond cond, oc_mutex mutex)
 {
-    ca_cond_wait_for(cond, mutex, 0L);
+    oc_cond_wait_for(cond, mutex, 0L);
 }
 
 #ifndef TIMEVAL_TO_TIMESPEC
@@ -357,8 +371,7 @@ void ca_cond_wait(ca_cond cond, ca_mutex mutex)
 }
 #endif
 
-#if !defined(_WIN32)
-struct timespec ca_get_current_time()
+struct timespec oc_get_current_time()
 {
 #if defined(__ANDROID__) || _POSIX_TIMERS > 0
     struct timespec ts;
@@ -373,7 +386,7 @@ struct timespec ca_get_current_time()
 #endif
 }
 
-void ca_add_microseconds_to_timespec(struct timespec* ts, uint64_t microseconds)
+void oc_add_microseconds_to_timespec(struct timespec* ts, uint64_t microseconds)
 {
     time_t secPart = microseconds/USECS_PER_SEC;
     uint64_t nsecPart = (microseconds % USECS_PER_SEC) * NANOSECS_PER_USECS;
@@ -383,48 +396,28 @@ void ca_add_microseconds_to_timespec(struct timespec* ts, uint64_t microseconds)
     ts->tv_nsec = (totalNs)% NANOSECS_PER_SEC;
     ts->tv_sec += secPart + secOfNs;
 }
-#endif
 
-CAWaitResult_t ca_cond_wait_for(ca_cond cond, ca_mutex mutex, uint64_t microseconds)
+OCWaitResult_t oc_cond_wait_for(oc_cond cond, oc_mutex mutex, uint64_t microseconds)
 {
-    CAWaitResult_t retVal = CA_WAIT_INVAL;
+    OCWaitResult_t retVal = OC_WAIT_INVAL;
 
-    ca_cond_internal *eventInfo = (ca_cond_internal*) cond;
-    ca_mutex_internal *mutexInfo = (ca_mutex_internal*) mutex;
+    oc_cond_internal *eventInfo = (oc_cond_internal*) cond;
+    oc_mutex_internal *mutexInfo = (oc_mutex_internal*) mutex;
 
     if (NULL == mutexInfo)
     {
         OIC_LOG_V(ERROR, TAG, "%s: Invalid mutex", __func__);
-        return CA_WAIT_INVAL;
+        return OC_WAIT_INVAL;
     }
 
     if (NULL == eventInfo)
     {
         OIC_LOG_V(ERROR, TAG, "%s: Invalid condition", __func__);
-        return CA_WAIT_INVAL;
+        return OC_WAIT_INVAL;
     }
 
     if (microseconds > 0)
     {
-#if defined(_WIN32)
-        // Wait for the given time
-        DWORD milli = (DWORD)(microseconds / 1000);
-        if (!SleepConditionVariableCS(&eventInfo->cond, &mutexInfo->mutex, milli))
-        {
-            if (GetLastError() == ERROR_TIMEOUT)
-            {
-                retVal = CA_WAIT_TIMEDOUT;
-            }
-            else
-            {
-                OIC_LOG_V(ERROR, TAG, "SleepConditionVariableCS() with Timeout failed %i", GetLastError());
-                retVal = CA_WAIT_INVAL;
-            }
-        }else
-        {
-            retVal = CA_WAIT_SUCCESS;
-        }
-#else
         int ret = 0;
         struct timespec abstime = { .tv_sec = 0 };
 
@@ -438,8 +431,8 @@ CAWaitResult_t ca_cond_wait_for(ca_cond cond, ca_mutex mutex, uint64_t microseco
         } else
 #endif
         {
-             abstime = ca_get_current_time();
-            ca_add_microseconds_to_timespec(&abstime, microseconds);
+             abstime = oc_get_current_time();
+            oc_add_microseconds_to_timespec(&abstime, microseconds);
 
             //Wait for the given time
             ret = pthread_cond_timedwait(&(eventInfo->cond), &(mutexInfo->mutex), &abstime);
@@ -449,39 +442,26 @@ CAWaitResult_t ca_cond_wait_for(ca_cond cond, ca_mutex mutex, uint64_t microseco
         {
             case 0:
                 // Success
-                retVal = CA_WAIT_SUCCESS;
+                retVal = OC_WAIT_SUCCESS;
                 break;
             case ETIMEDOUT:
-                retVal = CA_WAIT_TIMEDOUT;
+                retVal = OC_WAIT_TIMEDOUT;
                 break;
             case EINVAL:
                 OIC_LOG_V(ERROR, TAG, "%s: condition, mutex, or abstime is Invalid", __func__);
-                retVal = CA_WAIT_INVAL;
+                retVal = OC_WAIT_INVAL;
                 break;
             default:
                 OIC_LOG_V(ERROR, TAG, "%s: pthread_cond_timedwait returned %d", __func__, retVal);
-                retVal = CA_WAIT_INVAL;
+                retVal = OC_WAIT_INVAL;
                 break;
         }
-#endif
     }
     else
     {
-#if defined(_WIN32)
-        // Wait forever
-        if (!SleepConditionVariableCS(&eventInfo->cond, &mutexInfo->mutex, INFINITE))
-        {
-            OIC_LOG_V(ERROR, TAG, "SleepConditionVariableCS() w/o Timeout failed %i", GetLastError());
-            retVal = CA_WAIT_INVAL;
-        }else
-        {
-            retVal = CA_WAIT_SUCCESS;
-        }
-#else
         // Wait forever
         int ret = pthread_cond_wait(&eventInfo->cond, &mutexInfo->mutex);
-        retVal = ret == 0 ? CA_WAIT_SUCCESS : CA_WAIT_INVAL;
-#endif
+        retVal = ret == 0 ? OC_WAIT_SUCCESS : OC_WAIT_INVAL;
     }
     return retVal;
 }
diff --git a/resource/c_common/octhread/src/windows/octhread.c b/resource/c_common/octhread/src/windows/octhread.c
new file mode 100644 (file)
index 0000000..2613883
--- /dev/null
@@ -0,0 +1,287 @@
+/* *****************************************************************
+*
+* Copyright 2016 Intel Corporation
+*
+*
+* 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.
+*
+******************************************************************/
+
+
+/**
+ * @file
+ * This file provides APIs related to mutex, semaphores, and threads.
+ */
+#include "iotivity_config.h"
+#include "octhread.h"
+#include <string.h>
+#include <time.h>
+#include <winsock2.h>
+#include <stdio.h>
+#include <errno.h>
+#include <oic_malloc.h>
+
+#include "logger.h"
+
+static const uint64_t USECS_PER_MSEC = 1000;
+
+typedef struct _tagMutexInfo_t
+{
+    CRITICAL_SECTION mutex;
+} oc_mutex_internal;
+
+typedef struct _tagEventInfo_t
+{
+    CONDITION_VARIABLE cond;
+} oc_cond_internal;
+
+typedef struct _tagThreadInfo_t
+{
+    HANDLE handle;
+} oc_thread_internal;
+
+OCThreadResult_t oc_thread_new(oc_thread *t, void *(*start_routine)(void *), void *arg)
+{
+    OCThreadResult_t res = OC_THREAD_SUCCESS;
+    oc_thread_internal *threadInfo = (oc_thread_internal*)OICMalloc(sizeof(oc_thread_internal));
+    if (NULL != threadInfo)
+    {
+        threadInfo->handle = CreateThread(NULL, 0, (PTHREAD_START_ROUTINE)start_routine, arg, 0, NULL);
+        if (threadInfo->handle == NULL)
+        {
+            res = OC_THREAD_CREATE_FAILURE;
+            *t = NULL;
+            OICFree(threadInfo);
+            OIC_LOG_V(ERROR, TAG, "%s: CreateThread failed: %i", __func__, GetLastError());
+        }
+        else
+        {
+            *t = (oc_thread)threadInfo;
+        }
+    }
+    else
+    {
+        OIC_LOG_V(ERROR, TAG, "%s Failed to allocate thread!", __func__);
+        *t = NULL;
+        res = OC_THREAD_ALLOCATION_FAILURE;
+    }
+
+   return res;
+}
+
+OCThreadResult_t oc_thread_free(oc_thread t)
+{
+    OCThreadResult_t res = OC_THREAD_INVALID_PARAMETER;
+    oc_thread_internal *threadInfo = (oc_thread_internal*) t;
+    if (threadInfo)
+    {
+        CloseHandle(threadInfo->handle);
+        OICFree(threadInfo);
+        res = OC_THREAD_SUCCESS;
+    }
+    else
+    {
+        OIC_LOG_V(ERROR, TAG, "%s Invalid thread !", __func__);
+    }
+    return res;
+}
+
+OCThreadResult_t oc_thread_wait(oc_thread t)
+{
+    OCThreadResult_t res = OC_THREAD_SUCCESS;
+    oc_thread_internal *threadInfo = (oc_thread_internal*) t;
+    DWORD joinres = WaitForSingleObject(threadInfo->handle, INFINITE);
+    if (WAIT_OBJECT_0 != joinres)
+    {
+        OIC_LOG(ERROR, TAG, "Failed to join thread");
+        res = OC_THREAD_WAIT_FAILURE;
+    }
+    else
+    {
+        CloseHandle(threadInfo->handle);
+    }
+    return res;
+}
+
+oc_mutex oc_mutex_new(void)
+{
+    oc_mutex retVal = NULL;
+    oc_mutex_internal *mutexInfo = (oc_mutex_internal*) OICMalloc(sizeof(oc_mutex_internal));
+    if (NULL != mutexInfo)
+    {
+        InitializeCriticalSection(&mutexInfo->mutex);
+        retVal = (oc_mutex)mutexInfo;
+    }
+    else
+    {
+        OIC_LOG_V(ERROR, TAG, "%s Failed to allocate mutex!", __func__);
+    }
+
+    return retVal;
+}
+
+bool oc_mutex_free(oc_mutex mutex)
+{
+    bool bRet = false;
+    oc_mutex_internal *mutexInfo = (oc_mutex_internal*) mutex;
+    if (mutexInfo)
+    {
+        DeleteCriticalSection(&mutexInfo->mutex);
+        OICFree(mutexInfo);
+        bRet=true;
+    }
+    else
+    {
+        OIC_LOG_V(ERROR, TAG, "%s Invalid mutex !", __func__);
+    }
+
+    return bRet;
+}
+
+void oc_mutex_lock(oc_mutex mutex)
+{
+    oc_mutex_internal *mutexInfo = (oc_mutex_internal*) mutex;
+    if (mutexInfo)
+    {
+        EnterCriticalSection(&mutexInfo->mutex);
+    }
+    else
+    {
+        OIC_LOG_V(ERROR, TAG, "%s Invalid mutex !", __func__);
+    }
+}
+
+void oc_mutex_unlock(oc_mutex mutex)
+{
+    oc_mutex_internal *mutexInfo = (oc_mutex_internal*) mutex;
+    if (mutexInfo)
+    {
+        LeaveCriticalSection(&mutexInfo->mutex);
+    }
+    else
+    {
+        OIC_LOG_V(ERROR, TAG, "%s: Invalid mutex !", __func__);
+    }
+}
+
+oc_cond oc_cond_new(void)
+{
+    oc_cond retVal = NULL;
+    oc_cond_internal *eventInfo = (oc_cond_internal*) OICMalloc(sizeof(oc_cond_internal));
+    if (NULL != eventInfo)
+    {
+        InitializeConditionVariable(&eventInfo->cond);
+        retVal = (oc_cond) eventInfo;
+    }
+    else
+    {
+        OIC_LOG_V(ERROR, TAG, "%s: Failed to allocate condition variable!", __func__);
+    }
+
+    return retVal;
+}
+
+void oc_cond_free(oc_cond cond)
+{
+    oc_cond_internal *eventInfo = (oc_cond_internal*) cond;
+    if (eventInfo != NULL)
+    {
+        OICFree(cond);
+    }
+    else
+    {
+        OIC_LOG_V(ERROR, TAG, "%s: Invalid parameter", __func__);
+    }
+}
+
+void oc_cond_signal(oc_cond cond)
+{
+    oc_cond_internal *eventInfo = (oc_cond_internal*) cond;
+    if (eventInfo != NULL)
+    {
+        WakeConditionVariable(&eventInfo->cond);
+    }
+    else
+    {
+        OIC_LOG_V(ERROR, TAG, "%s: Invalid parameter", __func__);
+    }
+}
+
+void oc_cond_broadcast(oc_cond cond)
+{
+    oc_cond_internal* eventInfo = (oc_cond_internal*) cond;
+    if (eventInfo != NULL)
+    {
+        WakeAllConditionVariable(&eventInfo->cond);
+    }
+    else
+    {
+        OIC_LOG_V(ERROR, TAG, "%s: Invalid parameter", __func__);
+    }
+}
+
+void oc_cond_wait(oc_cond cond, oc_mutex mutex)
+{
+    oc_cond_wait_for(cond, mutex, 0L);
+}
+
+OCWaitResult_t oc_cond_wait_for(oc_cond cond, oc_mutex mutex, uint64_t microseconds)
+{
+    OCWaitResult_t retVal = OC_WAIT_INVAL;
+
+    oc_cond_internal *eventInfo = (oc_cond_internal*) cond;
+    oc_mutex_internal *mutexInfo = (oc_mutex_internal*) mutex;
+
+    if (NULL == mutexInfo)
+    {
+        OIC_LOG_V(ERROR, TAG, "%s: Invalid mutex", __func__);
+        return OC_WAIT_INVAL;
+    }
+
+    if (NULL == eventInfo)
+    {
+        OIC_LOG_V(ERROR, TAG, "%s: Invalid condition", __func__);
+        return OC_WAIT_INVAL;
+    }
+
+    DWORD milli = 0;
+    if (microseconds > 0)
+    {
+        milli = (DWORD)(microseconds / USECS_PER_MSEC);
+    }
+    else
+    {
+        milli = INFINITE;
+    }
+
+    // Wait for the given time        
+    if (!SleepConditionVariableCS(&eventInfo->cond, &mutexInfo->mutex, milli))
+    {
+        if (GetLastError() == ERROR_TIMEOUT)
+        {
+            retVal = OC_WAIT_TIMEDOUT;
+        }
+        else
+        {
+            OIC_LOG_V(ERROR, TAG, "SleepConditionVariableCS() failed %i", GetLastError());
+            retVal = OC_WAIT_INVAL;
+        }
+    }
+    else
+    {
+        retVal = OC_WAIT_SUCCESS;
+    }
+
+    return retVal;
+}
+
index b1d9e2a..589be23 100644 (file)
@@ -47,7 +47,7 @@ Alias("test", [malloctests])
 
 malloctest_env.AppendTarget('test')
 if malloctest_env.get('TEST') == '1':
-       if target_os in ['linux']:
+       if target_os in ['linux', 'windows']:
                 from tools.scons.RunTest import *
                 run_test(malloctest_env,
                          'resource_ccommon_malloc_test.memcheck',
index dd94aad..5a9222d 100644 (file)
@@ -18,6 +18,7 @@
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
+#include "iotivity_config.h"
 
 extern "C" {
     #include "oic_malloc.h"
@@ -28,7 +29,9 @@ extern "C" {
 #include <sys/stat.h>
 #include <errno.h>
 #include <fcntl.h>
+#ifdef HAVE_UNISTD_H
 #include <unistd.h>
+#endif
 #include <stdlib.h>
 #include <stdint.h>
 
index 4aea907..f736bfa 100644 (file)
@@ -38,6 +38,14 @@ extern "C"
 char *OICStrdup(const char *str);
 
 /**
+ * Convert source string to lower case characters.
+ *
+ * @param str Original valid string which needs to be converted.
+ *
+ */
+void OICStringToLower(char* str);
+
+/**
  * Copies a C string into destination buffer.  Ensures that the destination
  * is null terminated.
  *
index 644b4d2..8a8a960 100644 (file)
@@ -42,6 +42,17 @@ char *OICStrdup(const char *str)
     return dup;
 }
 
+void OICStringToLower(char* str)
+{
+    for (int ch = 0; str[ch] != '\0'; ch++)
+    {
+        if (str[ch] >= 'A' && str[ch] <= 'Z')
+        {
+            str[ch] += 32;
+        }
+    }
+}
+
 char* OICStrcpy(char* dest, size_t destSize, const char* source)
 {
     return OICStrcpyPartial(dest, destSize, source, destSize == 0 ? 0 : destSize - 1);
index 94bbd2b..29fbcda 100644 (file)
@@ -46,7 +46,7 @@ Alias("test", [stringtests])
 
 stringtest_env.AppendTarget('test')
 if stringtest_env.get('TEST') == '1':
-    if target_os in ['linux']:
+    if target_os in ['linux', 'windows']:
                 from tools.scons.RunTest import *
                 run_test(stringtest_env,
                          'resource_ccommon_string_test.memcheck',
index 320d30f..9b023e7 100644 (file)
@@ -191,12 +191,15 @@ TEST(StringTests, StrcpyZeroSource)
 // tests a copy where the destination is of length 0
 TEST(StringTests, StrcpyZeroDestination)
 {
-    char target[0];
+    char target[1] = { (char)0xde };
     char source[] = "123456789";
+    char beforeValue = target[0];
 
-    char *result = OICStrcpy(target, sizeof(target), source);
+    char *result = OICStrcpy(target, 0, source);
 
+    char afterValue = target[0];
     EXPECT_EQ(target, result);
+    EXPECT_EQ(beforeValue, afterValue);
 }
 
 // tests a copy where the destination is of length 0
@@ -398,11 +401,15 @@ TEST(StringTests, StrcatZeroSource)
 // Tests a cat where the Destination is zero length
 TEST(StringTests, StrcatZeroDestination)
 {
-    char target[0];
+    char target[1] = { (char)0xde };
     char source[] = "12345";
+    char beforeValue = target[0];
 
-    char *result = OICStrcat(target, sizeof(target), source);
+    char *result = OICStrcat(target, 0, source);
+
+    char afterValue = target[0];
     EXPECT_EQ(target, result);
+    EXPECT_EQ(beforeValue, afterValue);
 }
 
 // Tests a cat where the Destination is zero length
index 0b094f5..e01e6fb 100644 (file)
@@ -30,6 +30,7 @@
 #define _POSIX_C_SOURCE 200809L
 #endif
 
+#include "iotivity_config.h"
 #include "oic_time.h"
 
 #include <stddef.h>        // For NULL
index c4cb46b..2cca0e5 100644 (file)
@@ -34,7 +34,6 @@ timetest_env.PrependUnique(CPPPATH = [
 
 timetest_env.AppendUnique(LIBPATH = [os.path.join(timetest_env.get('BUILD_DIR'), 'resource', 'c_common')])
 timetest_env.PrependUnique(LIBS = ['c_common'])
-timetest_env.Append(LIBS = ['rt']);
 
 if timetest_env.get('LOGGING'):
     timetest_env.AppendUnique(CPPDEFINES = ['TB_LOG'])
@@ -48,7 +47,7 @@ Alias("test", [timetests])
 
 timetest_env.AppendTarget('test')
 if timetest_env.get('TEST') == '1':
-    if target_os in ['linux']:
+    if target_os in ['linux', 'windows']:
                 from tools.scons.RunTest import *
                 run_test(timetest_env,
                          'resource_ccommon_time_test.memcheck',
index a2e0e51..63ccb45 100644 (file)
@@ -21,6 +21,9 @@ helper_src = [
 static_libwinhelper = env.StaticLibrary('win_helper', helper_src)
 env.InstallTarget(static_libwinhelper, 'win_helper')
 env.UserInstallTargetLib(static_libwinhelper, 'win_helper')
+env.UserInstallTargetHeader('include/win_sleep.h', 'c_common/windows/include', 'win_sleep.h')
+env.UserInstallTargetHeader('include/pthread_create.h', 'c_common/windows/include', 'pthread_create.h')
+env.UserInstallTargetHeader('include/vs12_snprintf.h', 'c_common/windows/include', 'vs12_snprintf.h')
 
 env.AppendUnique(LIBS = ['win_helper'])
 
index abc4184..7868ca1 100644 (file)
@@ -1,4 +1,21 @@
-/** @todo: Add Microsoft license information */
+/* *****************************************************************
+*
+* Copyright 2016 Microsoft
+*
+*
+* 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.
+*
+******************************************************************/
 
 #include "getopt.h"
 #include <windows.h>
index 7aa175e..afcfe76 100644 (file)
@@ -43,6 +43,14 @@ if target_os == 'arduino':
 ######################################################################
 # Build flags
 ######################################################################
+with_upstream_libcoap = liboctbstack_env.get('WITH_UPSTREAM_LIBCOAP')
+if with_upstream_libcoap == '1':
+       # For bring up purposes only, we manually copy the forked version to where the unforked version is downloaded.
+       liboctbstack_env.PrependUnique(CPPPATH = ['#extlibs/libcoap/libcoap/include'])
+else:
+       # For bring up purposes only, the forked version will live here.
+       liboctbstack_env.PrependUnique(CPPPATH = ['connectivity/lib/libcoap-4.1.1/include'])
+
 liboctbstack_env.PrependUnique(CPPPATH = [
                '../../extlibs/cjson/',
                '../../extlibs/timer/',
@@ -50,7 +58,6 @@ liboctbstack_env.PrependUnique(CPPPATH = [
                'stack/include',
                'stack/include/internal',
                '../oc_logger/include',
-               'connectivity/lib/libcoap-4.1.1',
                'connectivity/common/inc',
                'connectivity/inc',
                'connectivity/inc/pkix',
@@ -69,7 +76,7 @@ if 'BROKER' in with_mq:
        liboctbstack_env.AppendUnique(CPPDEFINES = ['MQ_BROKER', 'WITH_MQ'])
 
 if target_os not in ['arduino', 'windows']:
-       liboctbstack_env.AppendUnique(CPPDEFINES  = ['WITH_POSIX'])
+       liboctbstack_env.AppendUnique(CPPDEFINES  = ['WITH_POSIX', '_GNU_SOURCE'])
        liboctbstack_env.AppendUnique(CFLAGS = ['-std=c99'])
 
 if liboctbstack_env.get('ROUTING') == 'GW':
@@ -77,6 +84,9 @@ if liboctbstack_env.get('ROUTING') == 'GW':
 elif liboctbstack_env.get('ROUTING') == 'EP':
        liboctbstack_env.AppendUnique(CPPDEFINES = ['ROUTING_EP'])
 
+if liboctbstack_env.get('WITH_PROXY'):
+       liboctbstack_env.AppendUnique(CPPDEFINES = ['WITH_CHPROXY'])
+
 if target_os not in ['windows']:
        liboctbstack_env.AppendUnique(CFLAGS = ['-Wall'])
 
@@ -102,15 +112,19 @@ if target_os in ['android', 'linux', 'tizen', 'msys_nt', 'windows']:
                        liboctbstack_env.AppendUnique(LIBS = ['ra_xmpp'])
 
 if target_os in ['windows', 'msys_nt']:
-       # octbstack.dll is exporting ocpmapi APIs on Windows - there is no ocpmapi.dll.
-       liboctbstack_env.PrependUnique(LIBS = ['ocpmapi'])
-
        # octbstack.def specifies the list of functions exported by octbstack.dll.
        liboctbstack_env.Replace(WINDOWS_INSERT_DEF = ['1'])
        if env.get('TEST') == '1':
-               liboctbstack_env.Textfile(target = 'octbstack.def', source = [File('octbstack_product.def'), File('octbstack_test.def')])
+               liboctbstack_env.Textfile(target = 'octbstack_not_secured.def', source = [File('octbstack_product.def'), File('octbstack_test.def')])
        else:
-               liboctbstack_env.Textfile(target = 'octbstack.def', source = [File('octbstack_product.def')])
+               liboctbstack_env.Textfile(target = 'octbstack_not_secured.def', source = [File('octbstack_product.def')])
+
+       if env.get('SECURED') == '1':
+               # octbstack.dll is exporting ocpmapi APIs on Windows - there is no ocpmapi.dll.
+               liboctbstack_env.PrependUnique(LIBS = ['ocpmapi'])
+               liboctbstack_env.Textfile(target = 'octbstack.def', source = [File('octbstack_not_secured.def'), File('octbstack_product_secured.def')])
+       else:
+               liboctbstack_env.Textfile(target = 'octbstack.def', source = [File('octbstack_not_secured.def')])
 
        liboctbstack_env.AppendUnique(LIBS = ['ws2_32', 'advapi32', 'iphlpapi'])
 else:
@@ -118,6 +132,8 @@ else:
 
 if target_os in ['tizen', 'linux']:
        liboctbstack_env.ParseConfig("pkg-config --cflags --libs uuid")
+if target_os in ['tizen']:
+       liboctbstack_env.ParseConfig('pkg-config --cflags --libs sqlite3')
 
 if target_os == 'arduino':
        liboctbstack_env.AppendUnique(CPPDEFINES = ['NDEBUG', 'WITH_ARDUINO'])
@@ -175,6 +191,11 @@ if with_tcp == True:
 
 liboctbstack_src.extend(env['cbor_files'])
 
+# Insert a hack for Arduino, whose compiler may not support all defines expected
+# by tinycbor
+if target_os in ['arduino']:
+       liboctbstack_env.AppendUnique(CPPDEFINES = ['INT64_MAX=0x7FFFFFFFFFFFFFFF'])
+
 if target_os in ['windows', 'msys_nt']:
        # Avoid a name conflict with the octbstack.lib target of the SharedLibrary.
        static_liboctbstack = liboctbstack_env.StaticLibrary('octbstack_static', liboctbstack_src)
index 87d1174..9fd62d1 100644 (file)
@@ -26,6 +26,8 @@
 #ifndef CA_COMMON_H_
 #define CA_COMMON_H_
 
+#include "iotivity_config.h"
+
 #ifndef WITH_ARDUINO
 #ifdef TCP_ADAPTER
 #define HAVE_SYS_POLL_H
@@ -68,7 +70,11 @@ extern "C"
 /**
  * Max header options data length.
  */
+#ifdef ARDUINO
 #define CA_MAX_HEADER_OPTION_DATA_LENGTH 20
+#else
+#define CA_MAX_HEADER_OPTION_DATA_LENGTH 1024
+#endif
 
 /**
 * Max token length.
@@ -339,7 +345,9 @@ typedef enum
     CA_REQUEST_ENTITY_INCOMPLETE = 408,     /**< Request Entity Incomplete */
     CA_REQUEST_ENTITY_TOO_LARGE = 413,      /**< Request Entity Too Large */
     CA_INTERNAL_SERVER_ERROR = 500,         /**< Internal Server Error */
-    CA_RETRANSMIT_TIMEOUT = 504             /**< Retransmit timeout */
+    CA_BAD_GATEWAY = 502,
+    CA_RETRANSMIT_TIMEOUT = 504,            /**< Retransmit timeout */
+    CA_PROXY_NOT_SUPPORTED = 505            /**< Proxy not enabled to service a request */
     /* Response status code - END HERE */
 } CAResponseResult_t;
 
index 5d50d8d..1c2bbfa 100644 (file)
@@ -231,7 +231,16 @@ CAResult_t CAHandleRequestResponse();
 CAResult_t CASetRAInfo(const CARAInfo_t *caraInfo);
 #endif
 
-
+#ifdef WITH_CHPROXY
+/**
+ * This function sets uri being used for proxy.
+ *
+ * @param uri            NULL terminated resource uri for CoAP-HTTP Proxy.
+ *
+ * @return  ::CA_STATUS_OK or ::CA_STATUS_INVALID_PARAM
+ */
+CAResult_t CASetProxyUri(const char *uri);
+#endif
 
 #ifdef __cplusplus
 } /* extern "C" */
index e9a27cb..bae8653 100644 (file)
@@ -95,6 +95,14 @@ CAResult_t CARegisterDTLSCredentialsHandler(CAGetDTLSPskCredentialsHandler GetDT
 
 #ifdef __WITH_TLS__
 /**
+ * This internal callback is used by CA layer to
+ * retrieve all credential types from SRM
+ *
+ * @param[out]  list of enabled credential types for CA handshake
+ *
+ */
+typedef void (*CAgetCredentialTypesHandler)(bool * list);
+/**
  * Binary structure containing PKIX related info
  * own certificate chain, public key, CA's and CRL's
  */
@@ -111,6 +119,12 @@ typedef struct
 } PkiInfo_t;
 
 /**
+ * Register callback to receive credential types.
+ * @param[in] credTypesCallback callback to get cerdential types
+ * @return ::CA_STATUS_OK
+ */
+CAResult_t CAregisterGetCredentialTypesCallback(CAgetCredentialTypesHandler credTypesCallback);
+/**
  * Register callback to receive the result of TLS handshake.
  * @param[in] tlsHandshakeCallback callback for get tls handshake result
  * @return ::CA_STATUS_OK
index 4464303..5a1c8e6 100644 (file)
@@ -21,7 +21,7 @@ os_arch_map = {
                'darwin': ['i386', 'x86_64'],
                'ios': ['i386', 'x86_64', 'armv7', 'armv7s', 'arm64'],
                'arduino': ['avr', 'arm'],
-                'yocto': ['i586', 'x86_64', 'arm', 'powerpc', 'powerpc64', 'mips', 'mipsel'],
+                'yocto': ['i586', 'i686', 'x86_64', 'arm', 'powerpc', 'powerpc64', 'mips', 'mipsel'],
                }
 
 host = platform.system().lower()
index d7c12a6..2376dac 100755 (executable)
@@ -42,19 +42,21 @@ echo `pwd`
 rm -rf ./tmp
 mkdir ./tmp
 mkdir ./tmp/con/
+mkdir -p $sourcedir/tmp/con/extlibs/
+
 cp -R $cur_dir/* $sourcedir/tmp/con
 cp -R $cur_dir/SConscript $sourcedir/tmp/con
 cp -R $cur_dir/src/ip_adapter/SConscript $sourcedir/tmp/con/src/ip_adapter/
 cp -R $cur_dir/src/bt_le_adapter/SConscript $sourcedir/tmp/con/src/bt_le_adapter/
 cp -R $cur_dir/src/bt_edr_adapter/SConscript $sourcedir/tmp/con/src/bt_edr_adapter/
 cp -R $cur_dir/common/SConscript $sourcedir/tmp/con/common/
-cp -R $cur_dir/lib/libcoap-4.1.1/SConscript $sourcedir/tmp/con/lib/libcoap-4.1.1/
 cp -R $cur_dir/samples/tizen/ $sourcedir/tmp/con/sample/
 mkdir -p $sourcedir/tmp/con/sample/external/inc
 cp -R $cur_dir/external/inc/* $sourcedir/tmp/con/sample/external/inc/
-mkdir -p $sourcedir/tmp/con/extlibs/
+
 cp -R ./extlibs/tinydtls/ $sourcedir/tmp/con/extlibs/
 cp -R ./extlibs/timer/ $sourcedir/tmp/con/extlibs/
+cp -R ./extlibs/libcoap/ $sourcedir/tmp/con/extlibs/
 mkdir -p $sourcedir/tmp/con/c_common
 cp -R ./resource/c_common/* $sourcedir/tmp/con/c_common/
 cp -R ./resource/csdk/logger/include/* $sourcedir/tmp/con/common/inc/
index 70b52d1..11e7823 100644 (file)
@@ -6,7 +6,7 @@
 
 
 Name: com-oic-ca
-Version:    1.1.1
+Version:    1.2.0
 Release:    0
 Summary: Tizen oicca application
 URL: http://slp-source.sec.samsung.net
@@ -44,7 +44,7 @@ mkdir -p %{DEST_INC_DIR}
 mkdir -p %{DEST_LIB_DIR}/pkgconfig
 
 cp -f %{ROOTDIR}/con/src/libconnectivity_abstraction.so %{buildroot}/%{_libdir}
-cp -f %{ROOTDIR}/con/lib/libcoap-4.1.1/libcoap.a %{buildroot}/%{_libdir}
+cp -f %{ROOTDIR}/extlibs/libcoap/libcoap.a %{buildroot}/%{_libdir}
 if echo %{SECURED}|grep -qi '1'; then
        cp -f %{ROOTDIR}/con/extlibs/tinydtls/libtinydtls.a %{buildroot}/%{_libdir}
 fi
index 4db7d47..3cdeef1 100644 (file)
@@ -15,6 +15,7 @@ ca_common_path = root_dir + 'common/'
 ca_common_src_path = ca_common_path + 'src/'
 
 env.AppendUnique(CPPPATH = [
+       '#resource/c_common/octhread/include/',
        'common/inc/',
        src_dir + '/resource/csdk/logger/include/',
        ])
@@ -29,16 +30,12 @@ ca_common_src = [
                ca_common_src_path + 'caremotehandler.c'
        ]
 
-if env['POSIX_SUPPORTED'] or (ca_os in ['windows']):
+if env['POSIX_SUPPORTED'] or ca_os in ['windows']:
        platform_src = [
                ca_common_src_path + 'cathreadpool_pthreads.c',
-               ca_common_src_path + 'camutex_pthreads.c'
        ]
 else:
-       platform_src = [
-               ca_common_src_path + 'camutex_noop.c'
-               ]
-
+       platform_src = []
 
 env.AppendUnique(CA_SRC = ca_common_src)
 env.AppendUnique(CA_SRC = platform_src)
diff --git a/resource/csdk/connectivity/common/inc/camutex.h b/resource/csdk/connectivity/common/inc/camutex.h
deleted file mode 100644 (file)
index 5a1c00f..0000000
+++ /dev/null
@@ -1,144 +0,0 @@
-/* ****************************************************************
- *
- * Copyright 2014 Samsung Electronics 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.
- *
- ******************************************************************/
-
-/**
- * @file
- *
- * This file provides APIs related to mutex and semaphores.
- */
-
-#ifndef CA_MUTEX_H_
-#define CA_MUTEX_H_
-
-#include "cacommon.h"
-
-#ifdef __cplusplus
-extern "C"
-{
-#endif /* __cplusplus */
-
-typedef struct ca_mutex_internal *ca_mutex;
-typedef struct ca_cond_internal *ca_cond;
-
-/**
- * Enums for ca_cond_wait_for return values.
- */
-typedef enum
-{
-   CA_WAIT_SUCCESS = 0,    /**< Condition Signal. */
-   CA_WAIT_INVAL = -1,     /**< Invalid Condition. */
-   CA_WAIT_TIMEDOUT = -2   /**< Condition Timed Out. */
-} CAWaitResult_t;
-
-/**
- * Creates new mutex.
- *
- * @return  Reference to newly created mutex, otherwise NULL.
- *
- */
-ca_mutex ca_mutex_new(void);
-
-/**
- * Lock the mutex.
- *
- * @param  mutex  The mutex to be locked.
- *
- */
-void ca_mutex_lock(ca_mutex mutex);
-
-/**
- * Unlock the mutex.
- *
- * @param  mutex  The mutex to be unlocked.
- *
- */
-void ca_mutex_unlock(ca_mutex mutex);
-
-/**
- * Free the mutex.
- *
- * @param  mutex  The mutex to be freed.
- *
- */
-bool ca_mutex_free(ca_mutex mutex);
-
-/**
- * Creates new condition.
- *
- * @return  Reference to newly created ::ca_cond, otherwise NULL.
- *
- */
-ca_cond ca_cond_new(void);
-
-/**
- * One of threads is woken up if multiple threads are waiting for cond.
- *
- * @param  cond  The condtion to be signaled.
- *
- */
-void ca_cond_signal(ca_cond cond);
-
-/**
- * All of threads are woken up if multiple threads are waiting for cond.
- *
- * @param  cond  The condtion to be signaled.
- *
- */
-void ca_cond_broadcast(ca_cond cond);
-
-/**
- * Waits until this thread woken up on cond.
- *
- * @param  cond  The condtion to be wait for to signal.
- * @param  mutex  The mutex which is currently locked from calling thread.
- *
- */
-void ca_cond_wait(ca_cond cond, ca_mutex mutex);
-
-/**
- * Waits until this thread woken up on cond,
- * but not longer than the interval specified by microseconds.
- * The mutex is unlocked before falling asleep and locked again before resuming.
- * If microseconds is 0, ca_cond_wait_for() acts like ca_cond_wait().
- *
- * @param  cond  The condtion to be wait for to signal.
- * @param  mutex  The mutex which is currently locked from calling thread.
- * @param  microseconds  relative time for waiting, microseconds.
- *
- * @return ::CA_WAIT_SUCCESS if the condition was signaled,
- *         ::CA_WAIT_TIMEDOUT if wait period exceeded,
- *         ::CA_WAIT_INVAL for invalid parameters.
- *
- */
-CAWaitResult_t ca_cond_wait_for(ca_cond cond, ca_mutex mutex, uint64_t microseconds);
-
-/**
- * Free the condition.
- *
- * @param  cond  The condition to be freed.
- *
- */
-void ca_cond_free(ca_cond cond);
-
-#ifdef __cplusplus
-} /* extern "C" */
-#endif /* __cplusplus */
-
-#endif /* CA_MUTEX_H_ */
index d17af9c..2b1939f 100644 (file)
 #ifndef _GNU_SOURCE
 #define _GNU_SOURCE
 #endif
+#include "iotivity_config.h"
 #include <errno.h>
-#if defined HAVE_PTHREAD_H
-#include <pthread.h>
-#endif
 #if defined HAVE_WINSOCK2_H
 #include <winsock2.h>
 #endif
@@ -38,7 +36,7 @@
 #include "logger.h"
 #include "oic_malloc.h"
 #include "uarraylist.h"
-#include "camutex.h"
+#include "octhread.h"
 #include "platform_features.h"
 
 #define TAG PCF("UTHREADPOOL")
@@ -50,7 +48,7 @@
 typedef struct ca_thread_pool_details_t
 {
     u_arraylist_t* threads_list;
-    ca_mutex list_lock;
+    oc_mutex list_lock;
 } ca_thread_pool_details_t;
 
 /**
@@ -110,7 +108,7 @@ CAResult_t ca_thread_pool_init(int32_t num_of_threads, ca_thread_pool_t *thread_
         return CA_MEMORY_ALLOC_FAILED;
     }
 
-    (*thread_pool)->details->list_lock = ca_mutex_new();
+    (*thread_pool)->details->list_lock = oc_mutex_new();
 
     if(!(*thread_pool)->details->list_lock)
     {
@@ -123,7 +121,7 @@ CAResult_t ca_thread_pool_init(int32_t num_of_threads, ca_thread_pool_t *thread_
     if(!(*thread_pool)->details->threads_list)
     {
         OIC_LOG(ERROR, TAG, "Failed to create thread-pool list");
-        if(!ca_mutex_free((*thread_pool)->details->list_lock))
+        if(!oc_mutex_free((*thread_pool)->details->list_lock))
         {
             OIC_LOG(ERROR, TAG, "Failed to free thread-pool mutex");
         }
@@ -161,22 +159,23 @@ CAResult_t ca_thread_pool_add_task(ca_thread_pool_t thread_pool, ca_thread_func
     info->func = method;
     info->data = data;
 
-    pthread_t threadHandle;
-    int result = pthread_create(&threadHandle, NULL, ca_thread_pool_pthreads_delegate, info);
-
-    if(result != 0)
+    oc_thread thread;
+    int thrRet = oc_thread_new(&thread, ca_thread_pool_pthreads_delegate, info);
+    if (thrRet != 0)
     {
-        OIC_LOG_V(ERROR, TAG, "Thread start failed with error %d", result);
+        OIC_LOG_V(ERROR, TAG, "Thread start failed with error %d", thrRet);
+        OICFree(info);
         return CA_STATUS_FAILED;
     }
 
-    ca_mutex_lock(thread_pool->details->list_lock);
-    bool addResult = u_arraylist_add(thread_pool->details->threads_list, (void*)threadHandle);
-    ca_mutex_unlock(thread_pool->details->list_lock);
+    oc_mutex_lock(thread_pool->details->list_lock);
+    bool addResult = u_arraylist_add(thread_pool->details->threads_list, (void*)thread);
+    oc_mutex_unlock(thread_pool->details->list_lock);
 
     if(!addResult)
     {
         OIC_LOG_V(ERROR, TAG, "Arraylist Add failed, may not be properly joined: %d", addResult);
+        oc_thread_free(thread);
         return CA_STATUS_FAILED;
     }
 
@@ -194,31 +193,19 @@ void ca_thread_pool_free(ca_thread_pool_t thread_pool)
         return;
     }
 
-    ca_mutex_lock(thread_pool->details->list_lock);
+    oc_mutex_lock(thread_pool->details->list_lock);
 
     for(uint32_t i = 0; i<u_arraylist_length(thread_pool->details->threads_list); ++i)
     {
-        pthread_t tid = (pthread_t)u_arraylist_get(thread_pool->details->threads_list, i);
-#if defined(_WIN32)
-        DWORD joinres = WaitForSingleObject(tid, INFINITE);
-        if (WAIT_OBJECT_0 != joinres)
-        {
-            OIC_LOG_V(ERROR, TAG, "Failed to join thread at index %u with error %d", i, joinres);
-        }
-        CloseHandle(tid);
-#else
-        int joinres = pthread_join(tid, NULL);
-        if(0 != joinres)
-        {
-            OIC_LOG_V(ERROR, TAG, "Failed to join thread at index %u with error %d", i, joinres);
-        }
-#endif
+        oc_thread thr = (oc_thread)u_arraylist_get(thread_pool->details->threads_list, i);
+        oc_thread_wait(thr);
+        oc_thread_free(thr);
     }
 
     u_arraylist_free(&(thread_pool->details->threads_list));
 
-    ca_mutex_unlock(thread_pool->details->list_lock);
-    ca_mutex_free(thread_pool->details->list_lock);
+    oc_mutex_unlock(thread_pool->details->list_lock);
+    oc_mutex_free(thread_pool->details->list_lock);
 
     OICFree(thread_pool->details);
     OICFree(thread_pool);
index 449e79e..130c126 100644 (file)
@@ -59,8 +59,13 @@ void CAsetTlsAdapterCallbacks(CAPacketReceivedCallback recvCallback,
                               CATransportAdapter_t type);
 
 /**
- * Register callback to get TLS PSK credentials.
- * @param[in]  credCallback    callback to get TLS PSK credentials.
+ * Register callback to get credentials types.
+ * @param[in]   credTypesCallback    callback to get credential types.
+ */
+void CAsetCredentialTypesCallback(CAgetCredentialTypesHandler credTypesCallback);
+/**
+ * Register callback to get credential types.
+ * @param[in]  typesCallback    callback to get credential types.
  */
 void CAsetTlsCredentialsCallback(CAGetDTLSPskCredentialsHandler credCallback);
 
index 6d03c7e..386cd3d 100644 (file)
 #ifndef CA_ADAPTER_NET_DTLS_H_
 #define CA_ADAPTER_NET_DTLS_H_
 
-#include "platform_features.h"
 #include "dtls.h"
 #include "uarraylist.h"
-#include "camutex.h"
+#include "octhread.h"
 #include "caadapterutils.h"
 #include "cainterface.h"
 #include "cacommon.h"
index 5f8c248..1f2d113 100644 (file)
@@ -27,6 +27,8 @@
 #ifndef CA_ADAPTER_UTILS_H_
 #define CA_ADAPTER_UTILS_H_
 
+#include "iotivity_config.h"
+
 #include <stdbool.h>
 #ifdef __ANDROID__
 #include <jni.h>
@@ -46,7 +48,7 @@
 
 #include "cacommon.h"
 #include "logger.h"
-#include "pdu.h"
+#include <coap/pdu.h>
 #include "uarraylist.h"
 #include "cacommonutil.h"
 
index 51677e6..3a7f948 100644 (file)
@@ -28,9 +28,9 @@
 
 #include <stdint.h>
 
-#include "coap.h"
+#include <coap/coap.h>
 #include "cathreadpool.h"
-#include "camutex.h"
+#include "octhread.h"
 #include "uarraylist.h"
 #include "cacommon.h"
 #include "caprotocolmessage.h"
@@ -68,10 +68,10 @@ typedef struct
     u_arraylist_t *dataList;
 
     /** data list mutex for synchronization. **/
-    ca_mutex blockDataListMutex;
+    oc_mutex blockDataListMutex;
 
     /** sender mutex for synchronization. **/
-    ca_mutex blockDataSenderMutex;
+    oc_mutex blockDataSenderMutex;
 } CABlockWiseContext_t;
 
 /**
index 5a70271..5596039 100644 (file)
@@ -27,7 +27,7 @@
 #define CA_MESSAGE_HANDLER_H_
 
 #include "cacommon.h"
-#include "coap.h"
+#include <coap/coap.h>
 
 #define CA_MEMORY_ALLOC_CHECK(arg) { if (NULL == arg) {OIC_LOG(ERROR, TAG, "Out of memory"); \
 goto memory_error_exit;} }
index b752a4d..6e23174 100644 (file)
 #define CA_PROTOCOL_MESSAGE_H_
 
 #include "cacommon.h"
-#include "config.h"
-#include "coap.h"
+#ifndef WITH_UPSTREAM_LIBCOAP
+#include "coap/config.h"
+#endif
+#include <coap/coap.h>
 
 #ifdef __cplusplus
 extern "C"
@@ -58,7 +60,7 @@ static const uint8_t PAYLOAD_MARKER = 1;
  * @return  generated pdu.
  */
 coap_pdu_t *CAGeneratePDU(uint32_t code, const CAInfo_t *info, const CAEndpoint_t *endpoint,
-                          coap_list_t **optlist, coap_transport_type *transport);
+                          coap_list_t **optlist, coap_transport_t *transport);
 
 /**
  * extracts request information from received pdu.
@@ -100,7 +102,7 @@ CAResult_t CAGetErrorInfoFromPDU(const coap_pdu_t *pdu, const CAEndpoint_t *endp
  */
 coap_pdu_t *CAGeneratePDUImpl(code_t code, const CAInfo_t *info,
                               const CAEndpoint_t *endpoint, coap_list_t *options,
-                              coap_transport_type *transport);
+                              coap_transport_t *transport);
 
 /**
  * parse the URI and creates the options.
@@ -199,7 +201,8 @@ coap_pdu_t *CAParsePDU(const char *data, uint32_t length, uint32_t *outCode,
  * @param[in]    endpoint            endpoint information.
  * @return  CA_STATUS_OK or ERROR CODES (CAResult_t error codes in cacommon.h).
  */
-CAResult_t CAGetTokenFromPDU(const coap_hdr_t *pdu_hdr, CAInfo_t *outInfo,
+CAResult_t CAGetTokenFromPDU(const coap_hdr_transport_t *pdu_hdr,
+                             CAInfo_t *outInfo,
                              const CAEndpoint_t *endpoint);
 
 /**
index 89efec1..40bd532 100644 (file)
@@ -30,7 +30,7 @@
 #include <stdint.h>
 
 #include "cathreadpool.h"
-#include "camutex.h"
+#include "octhread.h"
 #include "uqueue.h"
 #include "cacommon.h"
 #ifdef __cplusplus
@@ -49,9 +49,9 @@ typedef struct
     /** Thread pool of the thread started. **/
     ca_thread_pool_t threadPool;
     /** mutex for synchronization. **/
-    ca_mutex threadMutex;
+    oc_mutex threadMutex;
     /** conditional mutex for synchronization. **/
-    ca_cond threadCond;
+    oc_cond threadCond;
     /** Thread function to be invoked. **/
     CAThreadTask threadTask;
     /** Data destroy function. **/
index d764e51..904b5da 100644 (file)
@@ -29,7 +29,7 @@
 #include <stdint.h>
 
 #include "cathreadpool.h"
-#include "camutex.h"
+#include "octhread.h"
 #include "uarraylist.h"
 #include "cacommon.h"
 
@@ -74,10 +74,10 @@ typedef struct
     ca_thread_pool_t threadPool;
 
     /** mutex for synchronization. **/
-    ca_mutex threadMutex;
+    oc_mutex threadMutex;
 
     /** conditional mutex for synchronization. **/
-    ca_cond threadCond;
+    oc_cond threadCond;
 
     /** send method for retransmission data. **/
     CADataSendMethod_t dataSendMethod;
index da1a91d..f258711 100644 (file)
@@ -29,7 +29,7 @@
 #include "caadapterinterface.h"
 #include "cathreadpool.h"
 #include "cainterface.h"
-#include "pdu.h"
+#include <coap/pdu.h>
 
 #ifdef __cplusplus
 extern "C"
index 1ce03a7..23b9c46 100644 (file)
@@ -94,7 +94,7 @@ void CATCPPullData();
  * @param[out]   transport    TCP Server address.
  * @param[out]   headerlen    TCP Server port.
  */
-void CAGetTCPHeaderDetails(unsigned char *recvBuffer, coap_transport_type *transport,
+void CAGetTCPHeaderDetails(unsigned char *recvBuffer, coap_transport_t *transport,
                            size_t *headerlen);
 
 /**
diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/SConscript b/resource/csdk/connectivity/lib/libcoap-4.1.1/SConscript
deleted file mode 100644 (file)
index b47c835..0000000
+++ /dev/null
@@ -1,83 +0,0 @@
-##
-# libcoap (share library) build script
-##
-
-Import('env')
-
-libcoap_env = env.Clone()
-
-target_os = env.get('TARGET_OS')
-ca_transport = env.get('TARGET_TRANSPORT')
-with_tcp = env.get('WITH_TCP')
-# As in the source code(C) includes arduino Time library head file(C++)
-# It requires compile the .c with g++
-if target_os == 'arduino':
-       libcoap_env.Replace(CFLAGS = env.get('CXXFLAGS'))
-
-######################################################################
-# Build flags
-######################################################################
-       libcoap_env.PrependUnique(CPPPATH = [
-               './',
-               env.get('ARDUINO_HOME')+'/',
-               env.get('ARDUINO_HOME')+'/hardware/arduino/avr/cores/arduino',
-               env.get('ARDUINO_HOME')+'/hardware/tools/avr/avr/include/',
-               env.get('ARDUINO_HOME')+'/hardware/arduino/avr/variants/mega',
-               env.get('ARDUINO_HOME')+'/libraries/Time/Time',
-               env.get('ARDUINO_HOME')+'/libraries/TimedAction',
-               env.get('ARDUINO_HOME')+'/hardware/arduino/avr/libraries/SPI',
-               env.get('ARDUINO_HOME')+'/libraries/Ethernet/src/utility',
-               ])
-
-if target_os not in ['arduino', 'windows', 'msys_nt']:
-       libcoap_env.AppendUnique(CPPDEFINES = ['WITH_POSIX', '_DEFAULT_SOURCE'])
-       libcoap_env.AppendUnique(CFLAGS = ['-std=gnu99','-fPIC'])
-
-if target_os not in ['windows']:
-       libcoap_env.AppendUnique(CFLAGS = ['-Wall', '-ffunction-sections',
-                       '-fdata-sections', '-fno-exceptions'])
-
-if target_os == 'msys_nt':
-       libcoap_env.AppendUnique(CPPDEFINES = ['_DEFAULT_SOURCE'])
-       libcoap_env.AppendUnique(CFLAGS = ['-std=c99'])
-
-if target_os in ['linux', 'tizen', 'android', 'ios', 'arduino']:
-       if with_tcp == True:
-               libcoap_env.AppendUnique(CPPDEFINES = ['WITH_TCP'])
-
-if target_os in ['linux', 'tizen', 'android', 'arduino']:
-       libcoap_env.AppendUnique(LIBS = ['log'])
-       if (('BLE' in ca_transport) or ('BT' in ca_transport) or ('ALL' in ca_transport)):
-               libcoap_env.AppendUnique(CPPDEFINES = ['WITH_TCP'])
-
-if target_os == 'arduino':
-       libcoap_env.AppendUnique(CPPDEFINES = ['NDEBUG', 'WITH_ARDUINO'])
-
-if target_os in ['darwin', 'ios']:
-       libcoap_env.AppendUnique(CPPDEFINES = ['_DARWIN_C_SOURCE'])
-
-if env.get('LOGGING'):
-       libcoap_env.AppendUnique(CPPDEFINES = ['TB_LOG'])
-
-######################################################################
-# Source files and Target(s)
-######################################################################
-libcoap_src = [
-       'pdu.c',
-       'net.c',
-       'debug.c',
-       'encode.c',
-       'uri.c',
-       'coap_list.c',
-       'resource.c',
-       'hashkey.c',
-       'str.c',
-       'option.c',
-       'async.c',
-       'subscribe.c',
-       'block.c'
-       ]
-
-libcoap = libcoap_env.StaticLibrary('coap', libcoap_src, OBJPREFIX='libcoap_')
-
-libcoap_env.InstallTarget([libcoap], 'coap')
index 5bf5d95..fd2852e 100644 (file)
 
 #ifndef WITHOUT_ASYNC
 
-#include "config.h"
-
-#include "utlist.h"
-
-#include "mem.h"
-#include "debug.h"
-#include "async.h"
+#include "include/coap/config.h"
+#include "include/coap/utlist.h"
+#include "include/coap/mem.h"
+#include "include/coap/debug.h"
+#include "include/coap/async.h"
 
 coap_async_state_t *
-coap_register_async(coap_context_t *context, coap_address_t *peer, coap_pdu_t *request,
-        unsigned char flags, void *data)
-{
+coap_register_async(coap_context_t *context, coap_address_t *peer,
+        coap_pdu_t *request, unsigned char flags, void *data) {
     coap_async_state_t *s;
     coap_tid_t id;
 
     coap_transaction_id(peer, request, &id);
     LL_SEARCH_SCALAR(context->async_state, s, id, id);
 
-    if (s != NULL)
-    {
+    if (s != NULL) {
         /* We must return NULL here as the caller must know that he is
          * responsible for releasing @p data. */
         debug("asynchronous state for transaction %d already registered\n", id);
@@ -41,28 +37,26 @@ coap_register_async(coap_context_t *context, coap_address_t *peer, coap_pdu_t *r
 
     /* store information for handling the asynchronous task */
     s = (coap_async_state_t *) coap_malloc(sizeof(coap_async_state_t) +
-            request->hdr->coap_hdr_udp_t.token_length);
-    if (!s)
-    {
+            request->transport_hdr->udp.token_length);
+    if (!s) {
         coap_log(LOG_CRIT, "coap_register_async: insufficient memory\n");
         return NULL;
     }
 
-    memset(s, 0, sizeof(coap_async_state_t) + request->hdr->coap_hdr_udp_t.token_length);
+    memset(s, 0, sizeof(coap_async_state_t) + request->transport_hdr->udp.token_length);
 
     /* set COAP_ASYNC_CONFIRM according to request's type */
     s->flags = flags & ~COAP_ASYNC_CONFIRM;
-    if (request->hdr->coap_hdr_udp_t.type == COAP_MESSAGE_CON)
+    if (request->transport_hdr->udp.type == COAP_MESSAGE_CON)
         s->flags |= COAP_ASYNC_CONFIRM;
 
     s->appdata = data;
 
     memcpy(&s->peer, peer, sizeof(coap_address_t));
 
-    if (request->hdr->coap_hdr_udp_t.token_length)
-    {
-        s->tokenlen = request->hdr->coap_hdr_udp_t.token_length;
-        memcpy(s->token, request->hdr->coap_hdr_udp_t.token, request->hdr->coap_hdr_udp_t.token_length);
+    if (request->transport_hdr->udp.token_length) {
+        s->tokenlen = request->transport_hdr->udp.token_length;
+        memcpy(s->token, request->transport_hdr->udp.token, request->transport_hdr->udp.token_length);
     }
 
     memcpy(&s->id, &id, sizeof(coap_tid_t));
@@ -75,15 +69,14 @@ coap_register_async(coap_context_t *context, coap_address_t *peer, coap_pdu_t *r
 }
 
 coap_async_state_t *
-coap_find_async(coap_context_t *context, coap_tid_t id)
-{
+coap_find_async(coap_context_t *context, coap_tid_t id) {
     coap_async_state_t *tmp;
     LL_SEARCH_SCALAR(context->async_state, tmp, id, id);
     return tmp;
 }
 
-int coap_remove_async(coap_context_t *context, coap_tid_t id, coap_async_state_t **s)
-{
+int
+coap_remove_async(coap_context_t *context, coap_tid_t id, coap_async_state_t **s) {
     coap_async_state_t *tmp = coap_find_async(context, id);
 
     if (tmp)
@@ -93,8 +86,8 @@ int coap_remove_async(coap_context_t *context, coap_tid_t id, coap_async_state_t
     return tmp != NULL;
 }
 
-void coap_free_async(coap_async_state_t *s)
-{
+void
+coap_free_async(coap_async_state_t *s) {
     if (s && (s->flags & COAP_ASYNC_RELEASE_DATA) != 0)
         coap_free(s->appdata);
     coap_free(s);
index de83a62..d014f3d 100644 (file)
@@ -6,7 +6,7 @@
  * README for terms of use.
  */
 
-#include "config.h"
+#include "include/coap/config.h"
 
 #if defined(HAVE_ASSERT_H) && !defined(assert)
 # include <assert.h>
 #include <stdlib.h>
 #endif
 
-#include "debug.h"
-#include "block.h"
+#include "include/coap/debug.h"
+#include "include/coap/block.h"
 
 #define min(a,b) ((a) < (b) ? (a) : (b))
 
 #ifndef WITHOUT_BLOCK
-unsigned int coap_opt_block_num(const coap_opt_t *block_opt)
-{
+unsigned int
+coap_opt_block_num(const coap_opt_t *block_opt) {
     unsigned int num = 0;
     unsigned short len;
 
     len = coap_opt_length(block_opt);
 
-    if (len == 0)
-    {
+    if (len == 0) {
         return 0;
     }
 
-    if (len > 1)
-    {
-        num = coap_decode_var_bytes(COAP_OPT_VALUE(block_opt), COAP_OPT_LENGTH(block_opt) - 1);
+    if (len > 1) {
+        num = coap_decode_var_bytes(COAP_OPT_VALUE(block_opt),
+                                    COAP_OPT_LENGTH(block_opt) - 1);
     }
 
     return (num << 4) | ((*COAP_OPT_BLOCK_LAST(block_opt) & 0xF0) >> 4);
 }
 
-int coap_get_block(coap_pdu_t *pdu, unsigned short type, coap_block_t *block)
-{
+int
+coap_get_block(coap_pdu_t *pdu, unsigned short type, coap_block_t *block) {
     coap_opt_iterator_t opt_iter;
     coap_opt_t *option;
 
     assert(block);
     memset(block, 0, sizeof(coap_block_t));
 
-    if (pdu && (option = coap_check_option(pdu, type, &opt_iter)))
-    {
+    if (pdu && (option = coap_check_option(pdu, type, &opt_iter)) != NULL) {
         block->szx = COAP_OPT_BLOCK_SZX(option);
         if (COAP_OPT_BLOCK_MORE(option))
             block->m = 1;
@@ -63,24 +61,22 @@ int coap_get_block(coap_pdu_t *pdu, unsigned short type, coap_block_t *block)
     return 0;
 }
 
-int coap_write_block_opt(coap_block_t *block, unsigned short type, coap_pdu_t *pdu,
-        size_t data_length)
-{
+int
+coap_write_block_opt(coap_block_t *block, unsigned short type,
+        coap_pdu_t *pdu, size_t data_length) {
     size_t start, want, avail;
     unsigned char buf[3];
 
     assert(pdu);
 
     /* Block2 */
-    if (type != COAP_OPTION_BLOCK2)
-    {
+    if (type != COAP_OPTION_BLOCK2) {
         warn("coap_write_block_opt: skipped unknown option\n");
         return -1;
     }
 
     start = block->num << (block->szx + 4);
-    if (data_length <= start)
-    {
+    if (data_length <= start) {
         debug("illegal block requested\n");
         return -2;
     }
@@ -89,30 +85,24 @@ int coap_write_block_opt(coap_block_t *block, unsigned short type, coap_pdu_t *p
     want = 1 << (block->szx + 4);
 
     /* check if entire block fits in message */
-    if (want <= avail)
-    {
+    if (want <= avail) {
         block->m = want < data_length - start;
-    }
-    else
-    {
+    } else {
         /* Sender has requested a block that is larger than the remaining
          * space in pdu. This is ok if the remaining data fits into the pdu
          * anyway. The block size needs to be adjusted only if there is more
          * data left that cannot be delivered in this message. */
 
-        if (data_length - start <= avail)
-        {
+        if (data_length - start <= avail) {
 
             /* it's the final block and everything fits in the message */
             block->m = 0;
         }
-        else
-        {
+        else {
             unsigned char szx;
 
             /* we need to decrease the block size */
-            if (avail < 16)
-            { /* bad luck, this is the smallest block size */
+            if (avail < 16) { /* bad luck, this is the smallest block size */
                 debug("not enough space, even the smallest block does not fit");
                 return -3;
             }
@@ -126,21 +116,22 @@ int coap_write_block_opt(coap_block_t *block, unsigned short type, coap_pdu_t *p
 
     /* to re-encode the block option */
     coap_add_option(pdu, type,
-            coap_encode_var_bytes(buf, ((block->num << 4) | (block->m << 3) | block->szx)), buf,
-            coap_udp);
+            coap_encode_var_bytes(buf, ((block->num << 4) | (block->m << 3) | block->szx)), buf);
 
     return 1;
 }
 
-int coap_add_block(coap_pdu_t *pdu, unsigned int len, const unsigned char *data,
-        unsigned int block_num, unsigned char block_szx)
-{
+int
+coap_add_block(coap_pdu_t *pdu, unsigned int len, const unsigned char *data,
+        unsigned int block_num, unsigned char block_szx) {
     size_t start;
     start = block_num << (block_szx + 4);
 
     if (len <= start)
         return 0;
 
-    return coap_add_data(pdu, min(len - start, (unsigned int)(1 << (block_szx + 4))), data + start);
+    return coap_add_data(pdu,
+                         min(len - start, (unsigned int)(1 << (block_szx + 4))),
+                         data + start);
 }
 #endif /* WITHOUT_BLOCK  */
index 73f1595..e95c178 100644 (file)
@@ -6,14 +6,14 @@
  * README for terms of use.
  */
 
-#include "config.h"
+#include "include/coap/config.h"
 
 #include <stdio.h>
 #include <string.h>
 
-#include "debug.h"
-#include "mem.h"
-#include "coap_list.h"
+#include "include/coap/debug.h"
+#include "include/coap/mem.h"
+#include "include/coap/coap_list.h"
 
 int coap_insert(coap_list_t **queue, coap_list_t *node, int (*order)(void *, void *node))
 {
index fc4f1da..215e4d4 100644 (file)
@@ -6,7 +6,7 @@
  * README for terms of use.
  */
 
-#include "config.h"
+#include "include/coap/config.h"
 
 #if defined(HAVE_ASSERT_H) && !defined(assert)
 # include <assert.h>
@@ -25,8 +25,8 @@
 #include <time.h>
 #endif
 
-#include "debug.h"
-#include "net.h"
+#include "include/coap/debug.h"
+#include "include/coap/net.h"
 
 #ifdef WITH_CONTIKI
 # ifndef DEBUG
 
 static coap_log_t maxlog = LOG_WARNING; /* default maximum log level */
 
-coap_log_t coap_get_log_level()
-{
+coap_log_t
+coap_get_log_level() {
     return maxlog;
 }
 
-void coap_set_log_level(coap_log_t level)
-{
+void
+coap_set_log_level(coap_log_t level) {
     maxlog = level;
 }
 
 /* this array has the same order as the type log_t */
-static char *loglevels[] =
-{ "EMRG", "ALRT", "CRIT", "ERR", "WARN", "NOTE", "INFO", "DEBG" };
+static char *loglevels[] = {
+ "EMRG", "ALRT", "CRIT", "ERR", "WARN", "NOTE", "INFO", "DEBG"
+};
 
 #ifdef HAVE_TIME_H
 
-INLINE_API size_t print_timestamp(char *s, size_t len, coap_tick_t t)
-{
+INLINE_API size_t
+print_timestamp(char *s, size_t len, coap_tick_t t) {
     struct tm *tmp;
     time_t now = clock_offset + (t / COAP_TICKS_PER_SECOND);
     tmp = localtime(&now);
@@ -64,8 +65,7 @@ INLINE_API size_t print_timestamp(char *s, size_t len, coap_tick_t t)
 #else /* alternative implementation: just print the timestamp */
 
 INLINE_API size_t
-print_timestamp(char *s, size_t len, coap_tick_t t)
-{
+print_timestamp(char *s, size_t len, coap_tick_t t) {
 #ifdef HAVE_SNPRINTF
     return snprintf(s, len, "%u.%03u",
             (unsigned int)(clock_offset + (t / COAP_TICKS_PER_SECOND)),
@@ -90,8 +90,7 @@ print_timestamp(char *s, size_t len, coap_tick_t t)
  * @return The length of @p s.
  */
 INLINE_API size_t
-strnlen(const char *s, size_t maxlen)
-{
+strnlen(const char *s, size_t maxlen) {
     size_t n = 0;
     while(*s++ && n < maxlen)
     ++n;
@@ -99,9 +98,9 @@ strnlen(const char *s, size_t maxlen)
 }
 #endif /* HAVE_STRNLEN */
 
-unsigned int print_readable(const unsigned char *data, unsigned int len, unsigned char *result,
-        unsigned int buflen, int encode_always)
-{
+unsigned int
+print_readable(const unsigned char *data, unsigned int len, unsigned char *result,
+        unsigned int buflen, int encode_always) {
     const unsigned char hex[] = "0123456789ABCDEF";
     unsigned int cnt = 0;
     assert(data || len == 0);
@@ -109,19 +108,14 @@ unsigned int print_readable(const unsigned char *data, unsigned int len, unsigne
     if (buflen == 0 || len == 0)
         return 0;
 
-    while (len)
-    {
-        if (!encode_always && isprint(*data))
-        {
+    while (len) {
+        if (!encode_always && isprint(*data)) {
             if (cnt == buflen)
                 break;
             *result++ = *data;
             ++cnt;
-        }
-        else
-        {
-            if (cnt + 4 < buflen)
-            {
+        } else {
+            if (cnt + 4 < buflen) {
                 *result++ = '\\';
                 *result++ = 'x';
                 *result++ = hex[(*data & 0xf0) >> 4];
@@ -144,8 +138,8 @@ unsigned int print_readable(const unsigned char *data, unsigned int len, unsigne
 #define min(a,b) ((a) < (b) ? (a) : (b))
 #endif
 
-size_t coap_print_addr(const struct coap_address_t *addr, unsigned char *buf, size_t len)
-{
+size_t
+coap_print_addr(const struct coap_address_t *addr, unsigned char *buf, size_t len) {
 #if defined(HAVE_ARPA_INET_H) || defined(_WIN32)
     const void *addrptr = NULL;
 #if defined(__ANDROID__)
@@ -157,8 +151,7 @@ size_t coap_print_addr(const struct coap_address_t *addr, unsigned char *buf, si
 #endif
     unsigned char *p = buf;
 
-    switch (addr->addr.sa.sa_family)
-    {
+    switch (addr->addr.sa.sa_family) {
         case AF_INET:
             addrptr = &addr->addr.sin.sin_addr;
             port = ntohs(addr->addr.sin.sin_port);
@@ -178,18 +171,15 @@ size_t coap_print_addr(const struct coap_address_t *addr, unsigned char *buf, si
             return min(22, len);
     }
 
-    if (inet_ntop(addr->addr.sa.sa_family, addrptr, (char *) p, len) == 0)
-    {
+    if (inet_ntop(addr->addr.sa.sa_family, addrptr, (char *) p, len) == 0) {
         perror("coap_print_addr");
         return 0;
     }
 
     p += strnlen((char *) p, len);
 
-    if (addr->addr.sa.sa_family == AF_INET6)
-    {
-        if (p < buf + len)
-        {
+    if (addr->addr.sa.sa_family == AF_INET6) {
+        if (p < buf + len) {
             *p++ = ']';
         }
         else
@@ -215,10 +205,8 @@ size_t coap_print_addr(const struct coap_address_t *addr, unsigned char *buf, si
 
     *p++ = '[';
 
-    for (i=0; i < 16; i += 2)
-    {
-        if (i)
-        {
+    for (i=0; i < 16; i += 2) {
+        if (i) {
             *p++ = ':';
         }
         *p++ = hex[(addr->addr.u8[i] & 0xf0) >> 4];
@@ -252,8 +240,8 @@ size_t coap_print_addr(const struct coap_address_t *addr, unsigned char *buf, si
 }
 
 #ifndef WITH_CONTIKI
-void coap_show_pdu(const coap_pdu_t *pdu)
-{
+void
+coap_show_pdu(const coap_pdu_t *pdu) {
 #ifndef WITH_TCP
     unsigned char buf[COAP_MAX_PDU_SIZE]; /* need some space for output creation */
 #else
@@ -263,22 +251,18 @@ void coap_show_pdu(const coap_pdu_t *pdu)
     coap_opt_iterator_t opt_iter;
     coap_opt_t *option;
 
-    fprintf(COAP_DEBUG_FD, "v:%d t:%d tkl:%d c:%d id:%u", pdu->hdr->coap_hdr_udp_t.version,
-            pdu->hdr->coap_hdr_udp_t.type, pdu->hdr->coap_hdr_udp_t.token_length,
-            pdu->hdr->coap_hdr_udp_t.code, ntohs(pdu->hdr->coap_hdr_udp_t.id));
+    fprintf(COAP_DEBUG_FD, "v:%d t:%d tkl:%d c:%d id:%u", pdu->transport_hdr->udp.version,
+            pdu->transport_hdr->udp.type, pdu->transport_hdr->udp.token_length,
+            pdu->transport_hdr->udp.code, ntohs(pdu->transport_hdr->udp.id));
 
     /* show options, if any */
-    coap_option_iterator_init((coap_pdu_t *) pdu, &opt_iter, COAP_OPT_ALL, coap_udp);
+    coap_option_iterator_init((coap_pdu_t *) pdu, &opt_iter, COAP_OPT_ALL);
 
-    while ((option = coap_option_next(&opt_iter)))
-    {
-        if (!have_options)
-        {
+    while ((option = coap_option_next(&opt_iter))) {
+        if (!have_options) {
             have_options = 1;
             fprintf(COAP_DEBUG_FD, " o: [");
-        }
-        else
-        {
+        } else {
             fprintf(COAP_DEBUG_FD, ",");
         }
 
@@ -286,12 +270,9 @@ void coap_show_pdu(const coap_pdu_t *pdu)
                 || opt_iter.type == COAP_OPTION_URI_HOST
                 || opt_iter.type == COAP_OPTION_LOCATION_PATH
                 || opt_iter.type == COAP_OPTION_LOCATION_QUERY
-                || opt_iter.type == COAP_OPTION_URI_PATH || opt_iter.type == COAP_OPTION_URI_QUERY)
-        {
+                || opt_iter.type == COAP_OPTION_URI_PATH || opt_iter.type == COAP_OPTION_URI_QUERY) {
             encode = 0;
-        }
-        else
-        {
+        } else {
             encode = 1;
         }
 
@@ -303,8 +284,7 @@ void coap_show_pdu(const coap_pdu_t *pdu)
     if (have_options)
         fprintf(COAP_DEBUG_FD, " ]");
 
-    if (pdu->data)
-    {
+    if (pdu->data) {
         assert(pdu->data < (unsigned char *) pdu->hdr + pdu->length);
         print_readable(pdu->data, (unsigned char *) pdu->hdr + pdu->length - pdu->data, buf,
                 sizeof(buf), 0);
@@ -317,25 +297,22 @@ void coap_show_pdu(const coap_pdu_t *pdu)
 #else /* WITH_CONTIKI */
 
 void
-coap_show_pdu(const coap_pdu_t *pdu)
-{
+coap_show_pdu(const coap_pdu_t *pdu) {
     unsigned char buf[80]; /* need some space for output creation */
 
     PRINTF("v:%d t:%d oc:%d c:%d id:%u",
-            pdu->hdr->coap_hdr_udp_t.version, pdu->hdr->coap_hdr_udp_t.type,
-            pdu->hdr->coap_hdr_udp_t.optcnt, pdu->hdr->coap_hdr_udp_t.code,
-            uip_ntohs(pdu->hdr->coap_hdr_udp_t.id));
+            pdu->transport_hdr->udp.version, pdu->transport_hdr->udp.type,
+            pdu->transport_hdr->udp.optcnt, pdu->transport_hdr->udp.code,
+            uip_ntohs(pdu->transport_hdr->udp.id));
 
     /* show options, if any */
-    if (pdu->hdr->coap_hdr_udp_t.optcnt)
-    {
+    if (pdu->transport_hdr->udp.optcnt) {
         coap_opt_iterator_t opt_iter;
         coap_opt_t *option;
-        coap_option_iterator_init((coap_pdu_t *)pdu, &opt_iter, COAP_OPT_ALL, coap_udp);
+        coap_option_iterator_init((coap_pdu_t *)pdu, &opt_iter, COAP_OPT_ALL);
 
         PRINTF(" o:");
-        while ((option = coap_option_next(&opt_iter)))
-        {
+        while ((option = coap_option_next(&opt_iter))) {
 
             if (print_readable(COAP_OPT_VALUE(option),
                             COAP_OPT_LENGTH(option),
@@ -344,8 +321,7 @@ coap_show_pdu(const coap_pdu_t *pdu)
         }
     }
 
-    if (pdu->data < (unsigned char *)pdu->hdr + pdu->length)
-    {
+    if (pdu->data < (unsigned char *)pdu->hdr + pdu->length) {
         print_readable(pdu->data,
                 (unsigned char *)pdu->hdr + pdu->length - pdu->data,
                 buf, sizeof(buf), 0 );
@@ -358,16 +334,16 @@ coap_show_pdu(const coap_pdu_t *pdu)
 #endif /* NDEBUG */
 
 #ifdef WITH_ARDUINO
-void coap_log_impl(coap_log_t level, const char *format, ...)
-{
+void
+coap_log_impl(coap_log_t level, const char *format, ...) {
     //TODO: Implement logging functionalities for Arduino
 }
 #endif
 
 #ifndef WITH_ARDUINO
 #ifndef WITH_CONTIKI
-void coap_log_impl(coap_log_t level, const char *format, ...)
-{
+void
+coap_log_impl(coap_log_t level, const char *format, ...) {
     char timebuf[32];
     coap_tick_t now;
     va_list ap;
@@ -392,8 +368,7 @@ void coap_log_impl(coap_log_t level, const char *format, ...)
 }
 #else /* WITH_CONTIKI */
 void
-coap_log_impl(coap_log_t level, const char *format, ...)
-{
+coap_log_impl(coap_log_t level, const char *format, ...) {
     char timebuf[32];
     coap_tick_t now;
     va_list ap;
index a310008..3569bc2 100644 (file)
@@ -6,7 +6,7 @@
  * README for terms of use.
  */
 
-#include "config.h"
+#include "include/coap/config.h"
 
 #if defined(HAVE_ASSERT_H) && !defined(assert)
 # include <assert.h>
@@ -16,9 +16,8 @@
 #  include <stdio.h>
 #endif
 
-#include "config.h"
-#include "encode.h"
-#include "option.h"
+#include "include/coap/encode.h"
+#include "include/coap/option.h"
 
 /* Carsten suggested this when fls() is not available: */
 int coap_fls(unsigned int i)
index 30447e6..129147b 100644 (file)
@@ -6,7 +6,7 @@
  * README for terms of use.
  */
 
-#include "hashkey.h"
+#include "include/coap/hashkey.h"
 
 /* Caution: When changing this, update COAP_DEFAULT_WKC_HASHKEY
  * accordingly (see int coap_hash_path());
 /* Define to 1 if you have the <sys/stat.h> header file. */
 #define HAVE_SYS_STAT_H 1
 
+/* Define to 1 if you have the <sys/types.h> header file. */
+#if !defined(WITH_ARDUINO) && !defined(_WIN32)
+#define HAVE_SYS_TYPES_H 1
+#endif
+
 /* Define to 1 if you have the <sys/unistd.h> header file. */
 #if !defined(WITH_ARDUINO) && !defined(_WIN32)
 #define HAVE_SYS_UNISTD_H 1
@@ -82,7 +82,7 @@ size_t coap_opt_size(const coap_opt_t *opt);
  * @param pdu The PDU containing the options.
  * @return A pointer to the first option if available, or @c NULL otherwise.
  */
-coap_opt_t *options_start(coap_pdu_t *pdu, coap_transport_type transport);
+coap_opt_t *options_start(coap_pdu_t *pdu, coap_transport_t transport);
 
 /**
  * Interprets @p opt as pointer to a CoAP option and advances to
@@ -189,6 +189,26 @@ typedef struct
 } coap_opt_iterator_t;
 
 /**
+ * Initializes the given option iterator @p oi to point to the beginning of the
+ * @p pdu's option list. This function returns @p oi on success, @c NULL
+ * otherwise (i.e. when no options exist). Note that a length check on the
+ * option list must be performed before coap_option_iterator_init() is called.
+ *
+ * @param pdu    The PDU the options of which should be walked through.
+ * @param oi     An iterator object that will be initilized.
+ * @param filter An optional option type filter.
+ *               With @p type != @c COAP_OPT_ALL, coap_option_next()
+ *               will return only options matching this bitmask.
+ *               Fence-post options @c 14, @c 28, @c 42, ... are always
+ *               skipped.
+ *
+ * @return       The iterator object @p oi on success, @c NULL otherwise.
+ */
+coap_opt_iterator_t *coap_option_iterator_init(coap_pdu_t *pdu,
+                                               coap_opt_iterator_t *oi,
+                                               const coap_opt_filter_t filter);
+
+/**
  * Initializes the given option iterator @p oi to point to the
  * beginning of the @p pdu's option list. This function returns @p oi
  * on success, @c NULL otherwise (i.e. when no options exist).
@@ -205,8 +225,8 @@ typedef struct
  *
  * @return The iterator object @p oi on success, @c NULL otherwise.
  */
-coap_opt_iterator_t *coap_option_iterator_init(coap_pdu_t *pdu, coap_opt_iterator_t *oi,
-        const coap_opt_filter_t filter, coap_transport_type transport);
+coap_opt_iterator_t *coap_option_iterator_init2(coap_pdu_t *pdu, coap_opt_iterator_t *oi,
+        const coap_opt_filter_t filter, coap_transport_t transport);
 
 /**
  * Updates the iterator @p oi to point to the next option. This
@@ -6,8 +6,8 @@
  * README for terms of use.
  */
 
-#ifndef _PDU_H_
-#define _PDU_H_
+#ifndef _COAP_PDU_H_
+#define _COAP_PDU_H_
 
 #include "config.h"
 #include "coap_list.h"
 
 #ifndef SHORT_ERROR_RESPONSE
 /**
- * Returns a human-readable response phrase for the specified CoAP
- * response @p code. This function returns @c NULL if not found.
+ * Returns a human-readable response phrase for the specified CoAP response @p
+ * code. This function returns @c NULL if not found.
  *
- * @param code The response code for which the literal phrase should
- * be retrieved.
+ * @param code The response code for which the literal phrase should be
+ *             retrieved.
  *
- * @return A zero-terminated string describing the error, or @c NULL
- * if not found.
+ * @return     A zero-terminated string describing the error, or @c NULL if not
+ *             found.
  */
 char *coap_response_phrase(unsigned char code);
 
@@ -156,9 +156,14 @@ char *coap_response_phrase(unsigned char code);
  * use an unallocated type here and hope for the best. */
 #define COAP_MEDIATYPE_ANY                         0xff /* any media type */
 
-/* CoAP transaction id */
-/*typedef unsigned short coap_tid_t; */
+/**
+  * coap_tid_t is used to store CoAP transaction id, i.e. a hash value
+  * built from the remote transport address and the message id of a
+  * CoAP PDU.  Valid transaction ids are greater or equal zero.
+  */
 typedef int coap_tid_t;
+
+/** Indicates an invalid transaction id. */
 #define COAP_INVALID_TID -1
 
 #define COAP_TCP_HEADER_NO_FIELD    2
@@ -182,100 +187,75 @@ typedef int coap_tid_t;
 #define COAP_OPTION_FIELD_16_BIT     256
 #define COAP_OPTION_FIELD_32_BIT     65536
 
-typedef enum
-{
-    coap_udp = 0,
-    coap_tcp,
-    coap_tcp_8bit,
-    coap_tcp_16bit,
-    coap_tcp_32bit
-} coap_transport_type;
+typedef enum {
+    COAP_UDP = 0,
+    COAP_TCP,
+    COAP_TCP_8BIT,
+    COAP_TCP_16BIT,
+    COAP_TCP_32BIT
+} coap_transport_t;
 
 #ifdef WORDS_BIGENDIAN
-typedef union
-{
-    struct
-    {
-        unsigned int version:2; /* protocol version */
-        unsigned int type:2; /* type flag */
-        unsigned int token_length:4; /* length of Token */
-        unsigned int code:8; /* request method (value 1--10) or response code (value 40-255) */
-        unsigned short id; /* message id */
-        unsigned char token[]; /* the actual token, if any */
-    } coap_hdr_udp_t;
-
-    struct
-    {
-        unsigned char header_data[COAP_TCP_HEADER_NO_FIELD];
-        unsigned char token[]; /* the actual token, if any */
-    } coap_hdr_tcp_t;
-
-    struct
-    {
-        unsigned char header_data[COAP_TCP_HEADER_8_BIT];
-        unsigned char token[]; /* the actual token, if any */
-    } coap_hdr_tcp_8bit_t;
-
-    struct
-    {
-        unsigned char header_data[COAP_TCP_HEADER_16_BIT];
-        unsigned char token[]; /* the actual token, if any */
-    } coap_hdr_tcp_16bit_t;
-
-    struct
-    {
-        unsigned char header_data[6];
-        unsigned char token[]; /* the actual token, if any */
-    } coap_hdr_tcp_32bit_t;
-
-} coap_hdr_t;
+typedef struct {
+  unsigned short version:2;      /* protocol version */
+  unsigned short type:2;         /* type flag */
+  unsigned short token_length:4; /* length of Token */
+  unsigned short code:8;         /* request method (value 1--10) or response
+                                    code (value 40-255) */
+  unsigned short id;             /* message id */
+  unsigned char token[];         /* the actual token, if any */
+} coap_hdr_udp_t;
 #else
-typedef union
-{
-    struct
-    {
-        unsigned short token_length :4; /* length of Token */
-        unsigned short type :2; /* type flag */
-        unsigned short version :2; /* protocol version */
-        unsigned short code :8; /* request method (value 1--10) or response code (value 40-255) */
-        unsigned short id; /* transaction id (network byte order!) */
-        unsigned char token[]; /* the actual token, if any */
-    } coap_hdr_udp_t;
-
-    struct
-    {
-        unsigned char header_data[COAP_TCP_HEADER_NO_FIELD];
-        unsigned char token[]; /* the actual token, if any */
-    } coap_hdr_tcp_t;
-
-    struct
-    {
-        unsigned char header_data[COAP_TCP_HEADER_8_BIT];
-        unsigned char token[]; /* the actual token, if any */
-    } coap_hdr_tcp_8bit_t;
-
-    struct
-    {
-        unsigned char header_data[COAP_TCP_HEADER_16_BIT];
-        unsigned char token[]; /* the actual token, if any */
-    } coap_hdr_tcp_16bit_t;
-
-    struct
-    {
-        unsigned char header_data[COAP_TCP_HEADER_32_BIT];
-        unsigned char token[]; /* the actual token, if any */
-    } coap_hdr_tcp_32bit_t;
-
-} coap_hdr_t;
+typedef struct {
+  unsigned short token_length:4; /* length of Token */
+  unsigned short type:2;         /* type flag */
+  unsigned short version:2;      /* protocol version */
+  unsigned short code:8;         /* request method (value 1--10) or response
+                                    code (value 40-255) */
+  unsigned short id;             /* transaction id (network byte order!) */
+  unsigned char token[];         /* the actual token, if any */
+} coap_hdr_udp_t;
 #endif
 
+typedef struct {
+  unsigned char header_data[COAP_TCP_HEADER_NO_FIELD];
+  unsigned char token[]; /* the actual token, if any */
+} coap_hdr_tcp_t;
+
+typedef struct {
+  unsigned char header_data[COAP_TCP_HEADER_8_BIT];
+  unsigned char token[]; /* the actual token, if any */
+} coap_hdr_tcp_8bit_t;
+
+typedef struct {
+  unsigned char header_data[COAP_TCP_HEADER_16_BIT];
+  unsigned char token[]; /* the actual token, if any */
+} coap_hdr_tcp_16bit_t;
+
+typedef struct {
+  unsigned char header_data[6];
+  unsigned char token[]; /* the actual token, if any */
+} coap_hdr_tcp_32bit_t;
+
+typedef union {
+  coap_hdr_udp_t udp;
+  coap_hdr_tcp_t tcp;
+  coap_hdr_tcp_8bit_t tcp_8bit;
+  coap_hdr_tcp_16bit_t tcp_16bit;
+  coap_hdr_tcp_32bit_t tcp_32bit;
+} coap_hdr_transport_t;
+
+// Typedef for backwards compatibility.
+typedef coap_hdr_udp_t coap_hdr_t;
+
 #define COAP_MESSAGE_IS_EMPTY(MSG)    ((MSG).code == 0)
 #define COAP_MESSAGE_IS_REQUEST(MSG)  (!COAP_MESSAGE_IS_EMPTY(MSG)  \
                        && ((MSG).code < 32))
 #define COAP_MESSAGE_IS_RESPONSE(MSG) ((MSG).code >= 64 && (MSG).code <= 191)
 
-#define COAP_OPT_LONG 0x0F  /* OC == 0b1111 indicates that the option list in a
-                 * CoAP message is limited by 0b11110000 marker */
+#define COAP_OPT_LONG 0x0F  /* OC == 0b1111 indicates that the option list
+                             * in a CoAP message is limited by 0b11110000
+                             * marker */
 
 #define COAP_OPT_END 0xF0   /* end marker */
 
@@ -286,8 +266,7 @@ typedef union
  * coap_list_t.) The option's data will be added to the end of the coap_option
  * structure (see macro COAP_OPTION_DATA).
  */
-typedef struct
-{
+typedef struct {
     unsigned short key; /* the option key (no delta coding) */
     unsigned int length;
 } coap_option;
@@ -296,25 +275,43 @@ typedef struct
 #define COAP_OPTION_LENGTH(option) (option).length
 #define COAP_OPTION_DATA(option) ((unsigned char *)&(option) + sizeof(coap_option))
 
-/** Header structure for CoAP PDUs */
+/**
+ * Header structure for CoAP PDUs
+ */
 
-typedef struct
-{
+typedef struct {
     size_t max_size; /**< allocated storage for options and data */
 
-    coap_hdr_t *hdr;
+    union {
+        coap_hdr_t *hdr;          /**< Address of the first byte of the CoAP message.
+                                   *   This may or may not equal (coap_hdr_t*)(pdu+1)
+                                   *   depending on the memory management
+                                   *   implementation. */
+        coap_hdr_transport_t *transport_hdr; /**< Address of the first byte of the CoAP message.
+                                               *   This may or may not equal (coap_hdr_t*)(pdu+1)
+                                               *   depending on the memory management
+                                               *   implementation. */
+    };
     unsigned short max_delta; /**< highest option number */
     unsigned int length; /**< PDU length (including header, options, data)  */
     unsigned char *data; /**< payload */
 
 #ifdef WITH_LWIP
-    struct pbuf
-            *pbuf; /**< lwIP PBUF. The allocated coap_pdu_t will always reside inside the pbuf's payload, but the pointer has to be kept because no exact offset can be given. This field must not be accessed from outside, because the pbuf's reference count is checked to be 1 when the pbuf is assigned to the pdu, and the pbuf stays exclusive to this pdu. */
+    struct pbuf *pbuf;        /**< lwIP PBUF. The package data will always reside
+                               *    inside the pbuf's payload, but this pointer
+                               *    has to be kept because no exact offset can be
+                               *    given. This field must not be accessed from
+                               *    outside, because the pbuf's reference count
+                               *    is checked to be 1 when the pbuf is assigned
+                               *    to the pdu, and the pbuf stays exclusive to
+                               *    this pdu. */
 #endif
 
 } coap_pdu_t;
 
-/** Options in coap_pdu_t are accessed with the macro COAP_OPTION. */
+/**
+ * Options in coap_pdu_t are accessed with the macro COAP_OPTION.
+ */
 #define COAP_OPTION(node) ((coap_option *)(node)->options)
 #ifdef __cplusplus
 extern "C"
@@ -322,16 +319,16 @@ extern "C"
 #endif
 #ifdef WITH_LWIP
 /**
- * Creates a CoAP PDU from an lwIP @p pbuf, whose reference is passed on to
- * this function.
+ * Creates a CoAP PDU from an lwIP @p pbuf, whose reference is passed on to this
+ * function.
  *
  * The pbuf is checked for being contiguous, for having enough head space for
  * the PDU struct (which is located directly in front of the data, overwriting
  * the old other headers), and for having only one reference. The reference is
  * stored in the PDU and will be freed when the PDU is freed.
  *
- * (For now, these are errors; in future, a new pbuf might be allocated, the
- * data copied and the passed pbuf freed).
+ * (For now, these are fatal errors; in future, a new pbuf might be allocated,
+ * the data copied and the passed pbuf freed).
  *
  * This behaves like coap_pdu_init(0, 0, 0, pbuf->tot_len), and afterwards
  * copying the contents of the pbuf to the pdu.
@@ -343,6 +340,26 @@ coap_pdu_t * coap_pdu_from_pbuf(struct pbuf *pbuf);
 
 /**
  * Creates a new CoAP PDU of given @p size (must be large enough to hold the
+ * basic CoAP message header (coap_hdr_t). The function returns a pointer to the
+ * node coap_pdu_t object on success, or @c NULL on error. The storage allocated
+ * for the result must be released with coap_delete_pdu().
+ *
+ * @param type The type of the PDU (one of COAP_MESSAGE_CON, COAP_MESSAGE_NON,
+ *             COAP_MESSAGE_ACK, COAP_MESSAGE_RST).
+ * @param code The message code.
+ * @param id   The message id to set or COAP_INVALID_TID if unknown.
+ * @param size The number of bytes to allocate for the actual message.
+ *
+ * @return A pointer to the new PDU object or @c NULL on error.
+ */
+coap_pdu_t *
+coap_pdu_init(unsigned char type,
+              unsigned char code,
+              unsigned short id,
+              size_t size);
+
+/**
+ * Creates a new CoAP PDU of given @p size (must be large enough to hold the
  * basic CoAP message header (coap_hdr_t). The function returns a pointer to
  * the node coap_pdu_t object on success, or @c NULL on error. The storage
  * allocated for the result must be released with coap_delete_pdu().
@@ -357,8 +374,16 @@ coap_pdu_t * coap_pdu_from_pbuf(struct pbuf *pbuf);
  * @return A pointer to the new PDU object or @c NULL on error.
  */
 coap_pdu_t *
-coap_pdu_init(unsigned char type, unsigned char code, unsigned short id,
-              size_t size, coap_transport_type transport);
+coap_pdu_init2(unsigned char type, unsigned char code, unsigned short id,
+               size_t size, coap_transport_t transport);
+
+/**
+ * Clears any contents from @p pdu and resets @c version field, @c
+ * length and @c data pointers. @c max_size is set to @p size, any
+ * other field is set to @c 0. Note that @p pdu must be a valid
+ * pointer to a coap_pdu_t object created e.g. by coap_pdu_init().
+ */
+void coap_pdu_clear(coap_pdu_t *pdu, size_t size);
 
 /**
  * Clears any contents from @p pdu and resets @c version field, @c
@@ -366,24 +391,49 @@ coap_pdu_init(unsigned char type, unsigned char code, unsigned short id,
  * other field is set to @c 0. Note that @p pdu must be a valid
  * pointer to a coap_pdu_t object created e.g. by coap_pdu_init().
  */
-void coap_pdu_clear(coap_pdu_t *pdu, size_t size, coap_transport_type transport,
-                    unsigned int length);
+void coap_pdu_clear2(coap_pdu_t *pdu, size_t size, coap_transport_t transport,
+                     unsigned int length);
+
+/**
+ * Creates a new CoAP PDU.
+ * The object is created on the heap and must be released using
+ * coap_delete_pdu();
+ *
+ * @deprecated This function allocates the maximum storage for each
+ * PDU. Use coap_pdu_init() instead.
+ */
+coap_pdu_t *coap_new_pdu(void);
 
 /**
  * Creates a new CoAP PDU. The object is created on the heap and must be released
  * using coap_delete_pdu();
  *
  * @deprecated This function allocates the maximum storage for each
- * PDU. Use coap_pdu_init() instead.
+ * PDU. Use coap_pdu_init2() instead.
  */
-coap_pdu_t *coap_new_pdu(coap_transport_type transport, unsigned int size);
+coap_pdu_t *coap_new_pdu2(coap_transport_t transport, unsigned int size);
 
 void coap_delete_pdu(coap_pdu_t *);
 
 /**
- * Parses @p data into the CoAP PDU structure given in @p result. This
- * function returns @c 0 on error or a number greater than zero on
- * success.
+ * Parses @p data into the CoAP PDU structure given in @p result.
+ * This function returns @c 0 on error or a number greater than zero on success.
+ *
+ * @param data   The raw data to parse as CoAP PDU
+ * @param length The actual size of @p data
+ * @param result The PDU structure to fill. Note that the structure must
+ *               provide space for at least @p length bytes to hold the
+ *               entire CoAP PDU.
+ *
+ * @return A value greater than zero on success or @c 0 on error.
+ */
+int coap_pdu_parse(unsigned char *data,
+                   size_t length,
+                   coap_pdu_t *result);
+
+/**
+ * Parses @p data into the CoAP PDU structure given in @p result.
+ * This function returns @c 0 on error or a number greater than zero on success.
  *
  * @param data   The raw data to parse as CoAP PDU
  * @param length The actual size of @p data
@@ -393,8 +443,8 @@ void coap_delete_pdu(coap_pdu_t *);
  * @param transport The transport type.
  * @return A value greater than zero on success or @c 0 on error.
  */
-int coap_pdu_parse(unsigned char *data, size_t length, coap_pdu_t *pdu,
-                   coap_transport_type transport);
+int coap_pdu_parse2(unsigned char *data, size_t length, coap_pdu_t *pdu,
+                    coap_transport_t transport);
 
 #ifdef WITH_TCP
 /**
@@ -413,7 +463,7 @@ size_t coap_get_total_message_length(const unsigned char *data, size_t size);
  * @param size   payload size of pdu.
  * @return The transport type.
  */
-coap_transport_type coap_get_tcp_header_type_from_size(unsigned int size);
+coap_transport_t coap_get_tcp_header_type_from_size(unsigned int size);
 
 /**
  * Get transport type of coap header for coap over tcp
@@ -422,7 +472,7 @@ coap_transport_type coap_get_tcp_header_type_from_size(unsigned int size);
  * @param legnth   length value of init byte.
 * @return The transport type.
  */
-coap_transport_type coap_get_tcp_header_type_from_initbyte(unsigned int length);
+coap_transport_t coap_get_tcp_header_type_from_initbyte(unsigned int length);
 
 /**
  * Add length of option/payload into 'Len+ byte...' field of coap header
@@ -432,7 +482,7 @@ coap_transport_type coap_get_tcp_header_type_from_initbyte(unsigned int length);
  * @param transport The transport type.
  * @param length  length value of init byte.
  */
-void coap_add_length(const coap_pdu_t *pdu, coap_transport_type transport,
+void coap_add_length(const coap_pdu_t *pdu, coap_transport_t transport,
                      unsigned int length);
 
 /**
@@ -442,7 +492,7 @@ void coap_add_length(const coap_pdu_t *pdu, coap_transport_type transport,
  * @param transport The transport type.
  * @return length value of init byte.
  */
-unsigned int coap_get_length(const coap_pdu_t *pdu, coap_transport_type transport);
+unsigned int coap_get_length(const coap_pdu_t *pdu, coap_transport_t transport);
 
 /**
  * Get the length of option/payload field of coap header for coap over tcp.
@@ -451,7 +501,7 @@ unsigned int coap_get_length(const coap_pdu_t *pdu, coap_transport_type transpor
  * @return transport The transport type.
  */
 unsigned int coap_get_length_from_header(const unsigned char *header,
-                                         coap_transport_type transport);
+                                         coap_transport_t transport);
 
 /**
  * Get length of header including len, TKL, Len+bytes, Code, token bytes for coap over tcp.
@@ -468,7 +518,7 @@ unsigned int coap_get_tcp_header_length(unsigned char *data);
  * @param transport The transport type.
  * @return header length.
  */
-unsigned int coap_get_tcp_header_length_for_transport(coap_transport_type transport);
+unsigned int coap_get_tcp_header_length_for_transport(coap_transport_t transport);
 
 /**
  * Get option length.
@@ -478,7 +528,7 @@ unsigned int coap_get_tcp_header_length_for_transport(coap_transport_type transp
  * @return total option length
  */
 size_t coap_get_opt_header_length(unsigned short key, size_t length);
-#endif
+#endif /* WITH_TCP */
 
 /**
  * Add code in coap header.
@@ -487,7 +537,7 @@ size_t coap_get_opt_header_length(unsigned short key, size_t length);
  * @param transport The transport type.
  * @param code  The message code.
  */
-void coap_add_code(const coap_pdu_t *pdu, coap_transport_type transport,
+void coap_add_code(const coap_pdu_t *pdu, coap_transport_t transport,
                    unsigned int code);
 
 /**
@@ -497,11 +547,29 @@ void coap_add_code(const coap_pdu_t *pdu, coap_transport_type transport,
  * @param transport The transport type.
  * @return The message code.
  */
-unsigned int coap_get_code(const coap_pdu_t *pdu, coap_transport_type transport);
+unsigned int coap_get_code(const coap_pdu_t *pdu, coap_transport_t transport);
+
+/**
+ * Adds token of length @p len to @p pdu.
+ * Adding the token destroys any following contents of the pdu. Hence options
+ * and data must be added after coap_add_token() has been called. In @p pdu,
+ * length is set to @p len + @c 4, and max_delta is set to @c 0.  This funtion
+ * returns @c 0 on error or a value greater than zero on success.
+ *
+ * @param pdu  The PDU where the token is to be added.
+ * @param len  The length of the new token.
+ * @param data The token to add.
+ *
+ * @return A value greater than zero on success, or @c 0 on error.
+ */
+int coap_add_token(coap_pdu_t *pdu,
+                   size_t len,
+                   const unsigned char *data);
+
 /**
  * Adds token of length @p len to @p pdu. Adding the token destroys
  * any following contents of the pdu. Hence options and data must be
- * added after coap_add_token() has been called. In @p pdu, length is
+ * added after coap_add_token2() has been called. In @p pdu, length is
  * set to @p len + @c 4, and max_delta is set to @c 0.  This funtion
  * returns @c 0 on error or a value greater than zero on success.
  *
@@ -511,54 +579,82 @@ unsigned int coap_get_code(const coap_pdu_t *pdu, coap_transport_type transport)
  * @param transport The transport type.
  * @return A value greater than zero on success, or @c 0 on error.
  */
-int coap_add_token(coap_pdu_t *pdu, size_t len, const unsigned char *data,
-                   coap_transport_type transport);
+int coap_add_token2(coap_pdu_t *pdu, size_t len, const unsigned char *data,
+                    coap_transport_t transport);
 
 /**
- * Get token from coap header base on transport type
+ * Get token from coap header
  *
  * @param pdu_hdr  The header pointer of PDU.
- * @param transport The transport type.
  * @param token  out parameter to get token.
  * @param token_length  out parameter to get token length.
  */
-void coap_get_token(const coap_hdr_t *pdu_hdr, coap_transport_type transport,
+void coap_get_token(const coap_hdr_t *pdu_hdr,
                     unsigned char **token, unsigned int *token_length);
 
 /**
+ * Get token from coap header based on transport type
+ *
+ * @param pdu_hdr  The header pointer of PDU.
+ * @param transport The transport type.
+ * @param token  out parameter to get token.
+ * @param token_length  out parameter to get token length.
+ */
+void coap_get_token2(const coap_hdr_transport_t *pdu_hdr, coap_transport_t transport,
+                     unsigned char **token, unsigned int *token_length);
+
+/**
+ * Adds option of given type to pdu that is passed as first parameter. 
+ * coap_add_option() destroys the PDU's data, so coap_add_data() must be called
+ * after all options have been added. As coap_add_token() destroys the options
+ * following the token, the token must be added before coap_add_option() is
+ * called. This function returns the number of bytes written or @c 0 on error.
+ */
+size_t coap_add_option(coap_pdu_t *pdu,
+                       unsigned short type,
+                       unsigned int len,
+                       const unsigned char *data);
+
+/**
  * Adds option of given type to pdu that is passed as first
- * parameter. coap_add_option() destroys the PDU's data, so
+ * parameter. coap_add_option2() destroys the PDU's data, so
  * coap_add_data() must be called after all options have been added.
- * As coap_add_token() destroys the options following the token,
- * the token must be added before coap_add_option() is called.
+ * As coap_add_token2() destroys the options following the token,
+ * the token must be added before coap_add_option2() is called.
  * This function returns the number of bytes written or @c 0 on error.
  */
-size_t coap_add_option(coap_pdu_t *pdu, unsigned short type, unsigned int len,
-        const unsigned char *data, coap_transport_type transport);
+size_t coap_add_option2(coap_pdu_t *pdu, unsigned short type, unsigned int len,
+                        const unsigned char *data, coap_transport_t transport);
 
 /**
- * Adds option of given type to pdu that is passed as first
- * parameter, but does not write a val13ue. It works like coap_add_option with
- * respect to calling sequence (i.e. after token and before data).
- * This function returns a memory address to which the option data has to be
- * written before the PDU can be sent, or @c NULL on error.
+ * Adds option of given type to pdu that is passed as first parameter, but does
+ * not write a value. It works like coap_add_option with respect to calling
+ * sequence (i.e. after token and before data). This function returns a memory
+ * address to which the option data has to be written before the PDU can be
+ * sent, or @c NULL on error.
  */
-unsigned char *coap_add_option_later(coap_pdu_t *pdu, unsigned short type, unsigned int len);
+unsigned char *coap_add_option_later(coap_pdu_t *pdu,
+                                     unsigned short type,
+                                     unsigned int len);
 
 /**
- * Adds given data to the pdu that is passed as first parameter. Note
- * that the PDU's data is destroyed by coap_add_option(). coap_add_data()
- * must be called only once per PDU, otherwise the result is undefined.
+ * Adds given data to the pdu that is passed as first parameter. Note that the
+ * PDU's data is destroyed by coap_add_option(). coap_add_data() must be called
+ * only once per PDU, otherwise the result is undefined.
  */
-int coap_add_data(coap_pdu_t *pdu, unsigned int len, const unsigned char *data);
+int coap_add_data(coap_pdu_t *pdu,
+                  unsigned int len,
+                  const unsigned char *data);
 
 /**
- * Retrieves the length and data pointer of specified PDU. Returns 0 on error
- * or 1 if *len and *data have correct values. Note that these values are
- * destroyed with the pdu.
+ * Retrieves the length and data pointer of specified PDU. Returns 0 on error or
+ * 1 if *len and *data have correct values. Note that these values are destroyed
+ * with the pdu.
  */
-int coap_get_data(const coap_pdu_t *pdu, size_t *len, unsigned char **data);
+int coap_get_data(const coap_pdu_t *pdu,
+                  size_t *len,
+                  unsigned char **data);
 #ifdef __cplusplus
 } /* extern "C" */
 #endif
-#endif /* _PDU_H_ */
+#endif /* _COAP_PDU_H_ */
index 48e0455..d40388f 100644 (file)
@@ -6,7 +6,7 @@
  * README for terms of use.
  */
 
-#include "config.h"
+#include "include/coap/config.h"
 
 #include <ctype.h>
 #include <stdio.h>
 #include <lwip/timers.h>
 #endif
 
-#include "debug.h"
-#include "mem.h"
-#include "str.h"
-#include "async.h"
-#include "resource.h"
-#include "option.h"
-#include "encode.h"
-#include "block.h"
-#include "net.h"
+#include "include/coap/debug.h"
+#include "include/coap/mem.h"
+#include "include/coap/str.h"
+#include "include/coap/async.h"
+#include "include/coap/resource.h"
+#include "include/coap/option.h"
+#include "include/coap/encode.h"
+#include "include/coap/block.h"
+#include "include/coap/net.h"
 
 #if defined(WITH_POSIX) || defined(WITH_ARDUINO) || defined(_WIN32)
 
@@ -510,7 +510,7 @@ int coap_option_check_critical(coap_context_t *ctx, coap_pdu_t *pdu, coap_opt_fi
     coap_opt_iterator_t opt_iter;
     int ok = 1;
 
-    coap_option_iterator_init(pdu, &opt_iter, COAP_OPT_ALL, coap_udp);
+    coap_option_iterator_init(pdu, &opt_iter, COAP_OPT_ALL);
 
     while (coap_option_next(&opt_iter))
     {
@@ -574,7 +574,7 @@ void coap_transaction_id(const coap_address_t *peer, const coap_pdu_t *pdu, coap
     coap_hash((const unsigned char *)&peer->addr, sizeof(peer->addr), h);
 #endif /* WITH_LWIP || WITH_CONTIKI */
 
-    coap_hash((const unsigned char *)&pdu->hdr->coap_hdr_udp_t.id, sizeof(unsigned short), h);
+    coap_hash((const unsigned char *)&pdu->transport_hdr->udp.id, sizeof(unsigned short), h);
 
     *id = ((h[0] << 8) | h[1]) ^ ((h[2] << 8) | h[3]);
 }
@@ -584,10 +584,10 @@ coap_tid_t coap_send_ack(coap_context_t *context, const coap_address_t *dst, coa
     coap_pdu_t *response;
     coap_tid_t result = COAP_INVALID_TID;
 
-    if (request && request->hdr->coap_hdr_udp_t.type == COAP_MESSAGE_CON)
+    if (request && request->transport_hdr->udp.type == COAP_MESSAGE_CON)
     {
-        response = coap_pdu_init(COAP_MESSAGE_ACK, 0, request->hdr->coap_hdr_udp_t.id,
-                                 sizeof(coap_pdu_t), coap_udp);
+        response = coap_pdu_init(COAP_MESSAGE_ACK, 0, request->transport_hdr->udp.id,
+                                 sizeof(coap_pdu_t));
         if (response)
         {
             result = coap_send(context, dst, response);
@@ -748,8 +748,8 @@ coap_tid_t coap_send_message_type(coap_context_t *context, const coap_address_t
 
     if (request)
     {
-        response = coap_pdu_init(type, 0, request->hdr->coap_hdr_udp_t.id,
-                                 sizeof(coap_pdu_t), coap_udp);
+        response = coap_pdu_init(type, 0, request->transport_hdr->udp.id,
+                                 sizeof(coap_pdu_t));
         if (response)
         {
             result = coap_send(context, dst, response);
@@ -851,7 +851,7 @@ coap_tid_t coap_retransmit(coap_context_t *context, coap_queue_t *node)
 
         debug(
                 "** retransmission #%d of transaction %d\n", node->retransmit_cnt,
-                ntohs(node->pdu->hdr->coap_hdr_udp_t.id));
+                ntohs(node->pdu->transport_hdr->udp.id));
 
         node->id = coap_send_impl(context, &node->remote, node->pdu);
         return node->id;
@@ -866,13 +866,13 @@ coap_tid_t coap_retransmit(coap_context_t *context, coap_queue_t *node)
 #ifndef WITHOUT_OBSERVE
     /* Check if subscriptions exist that should be canceled after
      COAP_MAX_NOTIFY_FAILURES */
-    if (node->pdu->hdr->coap_hdr_udp_t.code >= 64)
+    if (node->pdu->transport_hdr->udp.code >= 64)
     {
         str token =
         { 0, NULL };
 
-        token.length = node->pdu->hdr->coap_hdr_udp_t.token_length;
-        token.s = node->pdu->hdr->coap_hdr_udp_t.token;
+        token.length = node->pdu->transport_hdr->udp.token_length;
+        token.s = node->pdu->transport_hdr->udp.token;
 
         coap_handle_failed_notify(context, &node->remote, &token);
     }
@@ -963,7 +963,7 @@ int coap_read(coap_context_t *ctx)
         goto error_early;
     }
 
-    if (pdu->coap_hdr_udp_t.version != COAP_DEFAULT_VERSION)
+    if (pdu->version != COAP_DEFAULT_VERSION)
     {
         debug("coap_read: unknown protocol version\n");
         goto error_early;
@@ -977,7 +977,7 @@ int coap_read(coap_context_t *ctx)
     node->pdu = coap_pdu_from_pbuf(ctx->pending_package);
     ctx->pending_package = NULL;
 #else
-    node->pdu = coap_pdu_init(0, 0, 0, bytes_read, coap_udp);
+    node->pdu = coap_pdu_init(0, 0, 0, bytes_read);
 #endif
     if (!node->pdu)
         goto error;
@@ -986,7 +986,7 @@ int coap_read(coap_context_t *ctx)
     memcpy(&node->local, &dst, sizeof(coap_address_t));
     memcpy(&node->remote, &src, sizeof(coap_address_t));
 
-    if (!coap_pdu_parse((unsigned char *) buf, bytes_read, node->pdu, coap_udp))
+    if (!coap_pdu_parse((unsigned char *) buf, bytes_read, node->pdu))
     {
         warn("discard malformed PDU");
         goto error;
@@ -1091,12 +1091,12 @@ void coap_cancel_all_messages(coap_context_t *context, const coap_address_t *dst
 
     debug("cancel_all_messages\n");
     while (context->sendqueue && coap_address_equals(dst, &context->sendqueue->remote)
-            && token_match(token, token_length, context->sendqueue->pdu->hdr->coap_hdr_udp_t.token,
-                    context->sendqueue->pdu->hdr->coap_hdr_udp_t.token_length))
+            && token_match(token, token_length, context->sendqueue->pdu->transport_hdr->udp.token,
+                    context->sendqueue->pdu->transport_hdr->udp.token_length))
     {
         q = context->sendqueue;
         context->sendqueue = q->next;
-        debug("**** removed transaction %d\n", ntohs(q->pdu->hdr->coap_hdr_udp_t.id));
+        debug("**** removed transaction %d\n", ntohs(q->pdu->transport_hdr->udp.id));
         coap_delete_node(q);
     }
 
@@ -1110,11 +1110,11 @@ void coap_cancel_all_messages(coap_context_t *context, const coap_address_t *dst
     while (q)
     {
         if (coap_address_equals(dst, &q->remote)
-                && token_match(token, token_length, q->pdu->hdr->coap_hdr_udp_t.token,
-                               q->pdu->hdr->coap_hdr_udp_t.token_length))
+                && token_match(token, token_length, q->pdu->transport_hdr->udp.token,
+                               q->pdu->transport_hdr->udp.token_length))
         {
             p->next = q->next;
-            debug("**** removed transaction %d\n", ntohs(q->pdu->hdr->coap_hdr_udp_t.id));
+            debug("**** removed transaction %d\n", ntohs(q->pdu->transport_hdr->udp.id));
             coap_delete_node(q);
             q = p->next;
         }
@@ -1140,7 +1140,7 @@ coap_new_error_response(coap_pdu_t *request, unsigned char code, coap_opt_filter
 {
     coap_opt_iterator_t opt_iter;
     coap_pdu_t *response;
-    size_t size = sizeof(coap_hdr_t) + request->hdr->coap_hdr_udp_t.token_length;
+    size_t size = sizeof(coap_hdr_t) + request->transport_hdr->udp.token_length;
     int type;
     coap_opt_t *option;
     unsigned short opt_type = 0; /* used for calculating delta-storage */
@@ -1156,14 +1156,14 @@ coap_new_error_response(coap_pdu_t *request, unsigned char code, coap_opt_filter
     assert(request);
 
     /* cannot send ACK if original request was not confirmable */
-    type = request->hdr->coap_hdr_udp_t.type == COAP_MESSAGE_CON ? COAP_MESSAGE_ACK : COAP_MESSAGE_NON;
+    type = request->transport_hdr->udp.type == COAP_MESSAGE_CON ? COAP_MESSAGE_ACK : COAP_MESSAGE_NON;
 
     /* Estimate how much space we need for options to copy from
      * request. We always need the Token, for 4.02 the unknown critical
      * options must be included as well. */
     coap_option_clrb(opts, COAP_OPTION_CONTENT_TYPE); /* we do not want this */
 
-    coap_option_iterator_init(request, &opt_iter, opts, coap_udp);
+    coap_option_iterator_init(request, &opt_iter, opts);
 
     /* Add size of each unknown critical option. As known critical
      options as well as elective options are not copied, the delta
@@ -1206,12 +1206,12 @@ coap_new_error_response(coap_pdu_t *request, unsigned char code, coap_opt_filter
     }
 
     /* Now create the response and fill with options and payload data. */
-    response = coap_pdu_init(type, code, request->hdr->coap_hdr_udp_t.id, size, coap_udp);
+    response = coap_pdu_init(type, code, request->transport_hdr->udp.id, size);
     if (response)
     {
         /* copy token */
-        if (!coap_add_token(response, request->hdr->coap_hdr_udp_t.token_length,
-                            request->hdr->coap_hdr_udp_t.token, coap_udp))
+        if (!coap_add_token(response, request->transport_hdr->udp.token_length,
+                            request->transport_hdr->udp.token))
         {
             debug("cannot add token to error response\n");
             coap_delete_pdu(response);
@@ -1219,10 +1219,10 @@ coap_new_error_response(coap_pdu_t *request, unsigned char code, coap_opt_filter
         }
 
         /* copy all options */
-        coap_option_iterator_init(request, &opt_iter, opts, coap_udp);
+        coap_option_iterator_init(request, &opt_iter, opts);
         while ((option = coap_option_next(&opt_iter)))
             coap_add_option(response, opt_iter.type, COAP_OPT_LENGTH(option),
-                    COAP_OPT_VALUE(option), coap_udp);
+                    COAP_OPT_VALUE(option));
 
 #if COAP_ERROR_PHRASE_LENGTH > 0
         /* note that diagnostic messages do not need a Content-Format option. */
@@ -1270,17 +1270,17 @@ wellknown_response(coap_context_t *context, coap_pdu_t *request)
     size_t offset = 0;
 
     resp = coap_pdu_init(
-            request->hdr->coap_hdr_udp_t.type == COAP_MESSAGE_CON ? COAP_MESSAGE_ACK : COAP_MESSAGE_NON,
+            request->transport_hdr->udp.type == COAP_MESSAGE_CON ? COAP_MESSAGE_ACK : COAP_MESSAGE_NON,
             COAP_RESPONSE_CODE(205),
-            request->hdr->coap_hdr_udp_t.id, COAP_MAX_PDU_SIZE, coap_udp);
+            request->transport_hdr->udp.id, COAP_MAX_PDU_SIZE);
     if (!resp)
     {
         debug("wellknown_response: cannot create PDU\n");
         return NULL;
     }
 
-    if (!coap_add_token(resp, request->hdr->coap_hdr_udp_t.token_length,
-                        request->hdr->coap_hdr_udp_t.token, coap_udp))
+    if (!coap_add_token(resp, request->transport_hdr->udp.token_length,
+                        request->transport_hdr->udp.token))
     {
         debug("wellknown_response: cannot add token\n");
         goto error;
@@ -1295,7 +1295,7 @@ wellknown_response(coap_context_t *context, coap_pdu_t *request)
         offset = block.num << (block.szx + 4);
         if (block.szx > 6)
         { /* invalid, MUST lead to 4.00 Bad Request */
-            resp->hdr->coap_hdr_udp_t.code = COAP_RESPONSE_CODE(400);
+            resp->transport_hdr->udp.code = COAP_RESPONSE_CODE(400);
             return resp;
         }
         else if (block.szx > COAP_MAX_BLOCK_SZX)
@@ -1321,7 +1321,7 @@ wellknown_response(coap_context_t *context, coap_pdu_t *request)
      * nothing should go wrong here. */
     assert(coap_encode_var_bytes(buf, COAP_MEDIATYPE_APPLICATION_LINK_FORMAT) == 1);
     coap_add_option(resp, COAP_OPTION_CONTENT_FORMAT,
-            coap_encode_var_bytes(buf, COAP_MEDIATYPE_APPLICATION_LINK_FORMAT), buf, coap_udp);
+            coap_encode_var_bytes(buf, COAP_MEDIATYPE_APPLICATION_LINK_FORMAT), buf);
 
     /* check if Block2 option is required even if not requested */
     if (!need_block2 && (resp->max_size - (size_t) resp->length < wkc_len))
@@ -1379,13 +1379,13 @@ wellknown_response(coap_context_t *context, coap_pdu_t *request)
 
     error:
     /* set error code 5.03 and remove all options and data from response */
-    resp->hdr->coap_hdr_udp_t.code = COAP_RESPONSE_CODE(503);
-    resp->length = sizeof(coap_hdr_t) + resp->hdr->coap_hdr_udp_t.token_length;
+    resp->transport_hdr->udp.code = COAP_RESPONSE_CODE(503);
+    resp->length = sizeof(coap_hdr_t) + resp->transport_hdr->udp.token_length;
     return resp;
 }
 
 #define WANT_WKC(Pdu,Key)                   \
-  (((Pdu)->hdr->coap_hdr_udp_t.code == COAP_REQUEST_GET) && is_wkc(Key))
+  (((Pdu)->transport_hdr->udp.code == COAP_REQUEST_GET) && is_wkc(Key))
 
 void handle_request(coap_context_t *context, coap_queue_t *node, const char* responseData)
 {
@@ -1408,7 +1408,7 @@ void handle_request(coap_context_t *context, coap_queue_t *node, const char* res
          * be the well-known URI. In that case, we generate a default
          * response, otherwise, we return 4.04 */
 
-        switch (node->pdu->hdr->coap_hdr_udp_t.code)
+        switch (node->pdu->transport_hdr->udp.code)
         {
 
             case COAP_REQUEST_GET:
@@ -1448,43 +1448,43 @@ void handle_request(coap_context_t *context, coap_queue_t *node, const char* res
     }
 
     /* the resource was found, check if there is a registered handler */
-    if ((size_t) node->pdu->hdr->coap_hdr_udp_t.code - 1
+    if ((size_t) node->pdu->transport_hdr->udp.code - 1
             < sizeof(resource->handler) / sizeof(coap_method_handler_t))
-        h = resource->handler[node->pdu->hdr->coap_hdr_udp_t.code - 1];
+        h = resource->handler[node->pdu->transport_hdr->udp.code - 1];
 
     if (h)
     {
         debug(
                 "call custom handler for resource 0x%02x%02x%02x%02x\n", key[0], key[1], key[2], key[3]);
         response = coap_pdu_init(
-                node->pdu->hdr->coap_hdr_udp_t.type ==
+                node->pdu->transport_hdr->udp.type ==
                         COAP_MESSAGE_CON ? COAP_MESSAGE_ACK : COAP_MESSAGE_NON,
-                0, node->pdu->hdr->coap_hdr_udp_t.id, COAP_MAX_PDU_SIZE, coap_udp);
+                0, node->pdu->transport_hdr->udp.id, COAP_MAX_PDU_SIZE);
 
         /* Implementation detail: coap_add_token() immediately returns 0
          if response == NULL */
-        if (coap_add_token(response, node->pdu->hdr->coap_hdr_udp_t.token_length,
-                           node->pdu->hdr->coap_hdr_udp_t.token, coap_udp))
+        if (coap_add_token(response, node->pdu->transport_hdr->udp.token_length,
+                           node->pdu->transport_hdr->udp.token))
         {
             str token =
-            { node->pdu->hdr->coap_hdr_udp_t.token_length, node->pdu->hdr->coap_hdr_udp_t.token };
+            { node->pdu->transport_hdr->udp.token_length, node->pdu->transport_hdr->udp.token };
 
             h(context, resource, &node->remote, node->pdu, &token, response);
 
             unsigned char buf[3];
-            response->hdr->coap_hdr_udp_t.code = COAP_RESPONSE_CODE(205);
+            response->transport_hdr->udp.code = COAP_RESPONSE_CODE(205);
             coap_add_option(response, COAP_OPTION_CONTENT_TYPE,
-                    coap_encode_var_bytes(buf, COAP_MEDIATYPE_TEXT_PLAIN), buf, coap_udp);
-            coap_add_option(response, COAP_OPTION_MAXAGE, coap_encode_var_bytes(buf, 0x2ffff), buf, coap_udp);
+                    coap_encode_var_bytes(buf, COAP_MEDIATYPE_TEXT_PLAIN), buf);
+            coap_add_option(response, COAP_OPTION_MAXAGE, coap_encode_var_bytes(buf, 0x2ffff), buf);
             coap_add_data(response, strlen(responseData), (unsigned char *) responseData);
 
-            if (response->hdr->coap_hdr_udp_t.type != COAP_MESSAGE_NON
-                    || (response->hdr->coap_hdr_udp_t.code >= 64 && !coap_is_mcast(&node->local)))
+            if (response->transport_hdr->udp.type != COAP_MESSAGE_NON
+                    || (response->transport_hdr->udp.code >= 64 && !coap_is_mcast(&node->local)))
             {
 
                 if (coap_send(context, &node->remote, response) == COAP_INVALID_TID)
                 {
-                    debug("cannot send response for message %d\n", node->pdu->hdr->coap_hdr_udp_t.id);
+                    debug("cannot send response for message %d\n", node->pdu->transport_hdr->udp.id);
                 }
             }
 
@@ -1562,8 +1562,8 @@ handle_locally(coap_context_t *context __attribute__ ((unused)),
          * get token from sent and try to find a matching resource. Uh!
          */
 
-        COAP_SET_STR(&token, sent->pdu->hdr->coap_hdr_udp_t.token_length,
-                     sent->pdu->hdr->coap_hdr_udp_t.token);
+        COAP_SET_STR(&token, sent->pdu->transport_hdr->udp.token_length,
+                     sent->pdu->transport_hdr->udp.token);
 
 #ifndef WITH_CONTIKI
 #ifdef COAP_RESOURCES_NOHASH
@@ -1609,29 +1609,29 @@ handle_locally(coap_context_t *context __attribute__ ((unused)),
             context->recvqueue = context->recvqueue->next;
             rcvd->next = NULL;
 
-            if (rcvd->pdu->hdr->coap_hdr_udp_t.version != COAP_DEFAULT_VERSION)
+            if (rcvd->pdu->transport_hdr->udp.version != COAP_DEFAULT_VERSION)
             {
-                debug("dropped packet with unknown version %u\n", rcvd->pdu->hdr->coap_hdr_udp_t.version);
+                debug("dropped packet with unknown version %u\n", rcvd->pdu->transport_hdr->udp.version);
                 goto cleanup;
             }
 
-            switch (rcvd->pdu->hdr->coap_hdr_udp_t.type)
+            switch (rcvd->pdu->transport_hdr->udp.type)
             {
                 case COAP_MESSAGE_ACK:
                     /* find transaction in sendqueue to stop retransmission */
                     coap_remove_from_queue(&context->sendqueue, rcvd->id, &sent);
 
-                    if (rcvd->pdu->hdr->coap_hdr_udp_t.code == 0)
+                    if (rcvd->pdu->transport_hdr->udp.code == 0)
                         goto cleanup;
 
                     /* FIXME: if sent code was >= 64 the message might have been a
                      * notification. Then, we must flag the observer to be alive
                      * by setting obs->fail_cnt = 0. */
-                    if (sent && COAP_RESPONSE_CLASS(sent->pdu->hdr->coap_hdr_udp_t.code) == 2)
+                    if (sent && COAP_RESPONSE_CLASS(sent->pdu->transport_hdr->udp.code) == 2)
                     {
                         const str token =
-                        { sent->pdu->hdr->coap_hdr_udp_t.token_length,
-                          sent->pdu->hdr->coap_hdr_udp_t.token };
+                        { sent->pdu->transport_hdr->udp.token_length,
+                          sent->pdu->transport_hdr->udp.token };
 
                         coap_touch_observer(context, &sent->remote, &token);
                     }
@@ -1643,7 +1643,7 @@ handle_locally(coap_context_t *context __attribute__ ((unused)),
                      * have. */
 
                     coap_log(LOG_ALERT, "got RST for message %u\n",
-                             ntohs(rcvd->pdu->hdr->coap_hdr_udp_t.id));
+                             ntohs(rcvd->pdu->transport_hdr->udp.id));
 
                     /* find transaction in sendqueue to stop retransmission */
                     coap_remove_from_queue(&context->sendqueue, rcvd->id, &sent);
@@ -1686,9 +1686,9 @@ handle_locally(coap_context_t *context __attribute__ ((unused)),
              * registered for a request that should be handled locally. */
             if (handle_locally(context, rcvd))
             {
-                if (COAP_MESSAGE_IS_REQUEST(rcvd->pdu->hdr->coap_hdr_udp_t))
+                if (COAP_MESSAGE_IS_REQUEST(rcvd->pdu->transport_hdr->udp))
                     handle_request(context, rcvd, responseData);
-                else if (COAP_MESSAGE_IS_RESPONSE(rcvd->pdu->hdr->coap_hdr_udp_t))
+                else if (COAP_MESSAGE_IS_RESPONSE(rcvd->pdu->transport_hdr->udp))
                     handle_response(context, sent, rcvd);
                 else
                 {
index 60bb865..13efdac 100644 (file)
@@ -7,7 +7,7 @@
  * README for terms of use.
  */
 
-#include "config.h"
+#include "include/coap/config.h"
 
 #if defined(HAVE_ASSERT_H) && !defined(assert)
 # include <assert.h>
 #include <stdio.h>
 #include <string.h>
 
-#include "option.h"
-#include "debug.h"
-#include "pdu.h"
+#include "include/coap/option.h"
+#include "include/coap/debug.h"
+#include "include/coap/pdu.h"
 
 coap_opt_t *
-options_start(coap_pdu_t *pdu, coap_transport_type transport)
+options_start(coap_pdu_t *pdu, coap_transport_t transport)
 {
     if (pdu && pdu->hdr)
     {
-        if (coap_udp == transport && (pdu->hdr->coap_hdr_udp_t.token +
-                pdu->hdr->coap_hdr_udp_t.token_length
+        if (COAP_UDP == transport && (pdu->transport_hdr->udp.token +
+                pdu->transport_hdr->udp.token_length
                 < (unsigned char *) pdu->hdr + pdu->length))
         {
-            coap_opt_t *opt = pdu->hdr->coap_hdr_udp_t.token +
-                    pdu->hdr->coap_hdr_udp_t.token_length;
+            coap_opt_t *opt = pdu->transport_hdr->udp.token +
+                    pdu->transport_hdr->udp.token_length;
             return (*opt == COAP_PAYLOAD_START) ? NULL : opt;
         }
 #ifdef WITH_TCP
-        else if(coap_tcp == transport && (pdu->hdr->coap_hdr_tcp_t.token +
-                ((pdu->hdr->coap_hdr_tcp_t.header_data[0]) & 0x0f)
+        else if(COAP_TCP == transport && (pdu->transport_hdr->tcp.token +
+                ((pdu->transport_hdr->tcp.header_data[0]) & 0x0f)
                 < (unsigned char *) pdu->hdr + pdu->length))
         {
-            coap_opt_t *opt = pdu->hdr->coap_hdr_tcp_t.token +
-                    ((pdu->hdr->coap_hdr_tcp_t.header_data[0]) & 0x0f);
+            coap_opt_t *opt = pdu->transport_hdr->tcp.token +
+                    ((pdu->transport_hdr->tcp.header_data[0]) & 0x0f);
             return (*opt == COAP_PAYLOAD_START) ? NULL : opt;
         }
 #endif
@@ -138,7 +138,14 @@ size_t coap_opt_parse(const coap_opt_t *opt, size_t length, coap_option_t *resul
 
 coap_opt_iterator_t *
 coap_option_iterator_init(coap_pdu_t *pdu, coap_opt_iterator_t *oi,
-                          const coap_opt_filter_t filter, coap_transport_type transport)
+                          const coap_opt_filter_t filter)
+{
+    return coap_option_iterator_init2(pdu, oi, filter, COAP_UDP);
+}
+
+coap_opt_iterator_t *
+coap_option_iterator_init2(coap_pdu_t *pdu, coap_opt_iterator_t *oi,
+                           const coap_opt_filter_t filter, coap_transport_t transport)
 {
     assert(pdu);
     assert(pdu->hdr);
@@ -152,34 +159,34 @@ coap_option_iterator_init(coap_pdu_t *pdu, coap_opt_iterator_t *oi,
     switch(transport)
     {
 #ifdef WITH_TCP
-        case coap_tcp:
-            token_length = (pdu->hdr->coap_hdr_tcp_t.header_data[0]) & 0x0f;
+        case COAP_TCP:
+            token_length = (pdu->transport_hdr->tcp.header_data[0]) & 0x0f;
             headerSize = COAP_TCP_HEADER_NO_FIELD;
             break;
-        case coap_tcp_8bit:
-            token_length = (pdu->hdr->coap_hdr_tcp_8bit_t.header_data[0]) & 0x0f;
+        case COAP_TCP_8BIT:
+            token_length = (pdu->transport_hdr->tcp_8bit.header_data[0]) & 0x0f;
             headerSize = COAP_TCP_HEADER_8_BIT;
             break;
-        case coap_tcp_16bit:
-            token_length = (pdu->hdr->coap_hdr_tcp_16bit_t.header_data[0]) & 0x0f;
+        case COAP_TCP_16BIT:
+            token_length = (pdu->transport_hdr->tcp_16bit.header_data[0]) & 0x0f;
             headerSize = COAP_TCP_HEADER_16_BIT;
             break;
-        case coap_tcp_32bit:
-            token_length = pdu->hdr->coap_hdr_tcp_32bit_t.header_data[0] & 0x0f;
+        case COAP_TCP_32BIT:
+            token_length = pdu->transport_hdr->tcp_32bit.header_data[0] & 0x0f;
             headerSize = COAP_TCP_HEADER_32_BIT;
             break;
 #endif
         default:
-            token_length = pdu->hdr->coap_hdr_udp_t.token_length;
-            headerSize = sizeof(pdu->hdr->coap_hdr_udp_t);
+            token_length = pdu->transport_hdr->udp.token_length;
+            headerSize = sizeof(pdu->transport_hdr->udp);
             break;
     }
 
     oi->next_option = (unsigned char *) pdu->hdr + headerSize + token_length;
 
-    if (coap_udp == transport)
+    if (COAP_UDP == transport)
     {
-        if ((unsigned char *) &(pdu->hdr->coap_hdr_udp_t) + pdu->length <= oi->next_option)
+        if ((unsigned char *) &(pdu->transport_hdr->udp) + pdu->length <= oi->next_option)
         {
             oi->bad = 1;
             return NULL;
@@ -188,7 +195,7 @@ coap_option_iterator_init(coap_pdu_t *pdu, coap_opt_iterator_t *oi,
 #ifdef WITH_TCP
     else
     {
-        if ((unsigned char *) &(pdu->hdr->coap_hdr_tcp_t) + pdu->length <= oi->next_option)
+        if ((unsigned char *) &(pdu->transport_hdr->tcp) + pdu->length <= oi->next_option)
         {
             oi->bad = 1;
             return NULL;
@@ -283,7 +290,7 @@ coap_check_option(coap_pdu_t *pdu, unsigned char type, coap_opt_iterator_t *oi)
     coap_option_filter_clear(f);
     coap_option_setb(f, type);
 
-    coap_option_iterator_init(pdu, oi, f, coap_udp);
+    coap_option_iterator_init(pdu, oi, f);
 
     return coap_option_next(oi);
 }
index dec32b5..d2ca93e 100644 (file)
@@ -6,7 +6,7 @@
  * README for terms of use.
  */
 
-#include "config.h"
+#include "include/coap/config.h"
 
 #if defined(HAVE_ASSERT_H) && !defined(assert)
 # include <assert.h>
 #include <winsock2.h>
 #endif
 
-#include "debug.h"
-#include "pdu.h"
-#include "option.h"
-#include "encode.h"
+#include "include/coap/debug.h"
+#include "include/coap/pdu.h"
+#include "include/coap/option.h"
+#include "include/coap/encode.h"
 
 #ifdef WITH_ARDUINO
 #include "util.h"
@@ -47,10 +47,15 @@ coap_pdu_resources_init()
     memb_init(&pdu_storage);
 }
 #else /* WITH_CONTIKI */
-#include "mem.h"
+#include "include/coap/mem.h"
 #endif /* WITH_CONTIKI */
 
-void coap_pdu_clear(coap_pdu_t *pdu, size_t size, coap_transport_type transport, unsigned int length)
+void coap_pdu_clear(coap_pdu_t *pdu, size_t size)
+{
+    coap_pdu_clear2(pdu, size, COAP_UDP, 0);
+}
+
+void coap_pdu_clear2(coap_pdu_t *pdu, size_t size, coap_transport_t transport, unsigned int length)
 {
     assert(pdu);
 
@@ -58,11 +63,11 @@ void coap_pdu_clear(coap_pdu_t *pdu, size_t size, coap_transport_type transport,
     pdu->max_size = size;
     pdu->hdr = (coap_hdr_t *) ((unsigned char *) pdu + sizeof(coap_pdu_t));
 
-    if (coap_udp == transport)
+    if (COAP_UDP == transport)
     {
-        pdu->hdr->coap_hdr_udp_t.version = COAP_DEFAULT_VERSION;
+        pdu->transport_hdr->udp.version = COAP_DEFAULT_VERSION;
         /* data is NULL unless explicitly set by coap_add_data() */
-        pdu->length = sizeof(pdu->hdr->coap_hdr_udp_t);
+        pdu->length = sizeof(pdu->transport_hdr->udp);
     }
 #ifdef WITH_TCP
     else
@@ -103,7 +108,14 @@ coap_pdu_from_pbuf(struct pbuf *pbuf)
 
 coap_pdu_t *
 coap_pdu_init(unsigned char type, unsigned char code, unsigned short id,
-              size_t size, coap_transport_type transport)
+              size_t size)
+{
+    return coap_pdu_init2(type, code, id, size, COAP_UDP);
+}
+
+coap_pdu_t *
+coap_pdu_init2(unsigned char type, unsigned char code, unsigned short id,
+               size_t size, coap_transport_t transport)
 {
     coap_pdu_t *pdu;
 #ifdef WITH_LWIP
@@ -113,20 +125,20 @@ coap_pdu_init(unsigned char type, unsigned char code, unsigned short id,
     unsigned int length = 0;
     switch(transport)
     {
-        case coap_udp:
-            length = sizeof(pdu->hdr->coap_hdr_udp_t);
+        case COAP_UDP:
+            length = sizeof(pdu->transport_hdr->udp);
             break;
 #ifdef WITH_TCP
-        case coap_tcp:
+        case COAP_TCP:
             length = COAP_TCP_HEADER_NO_FIELD;
             break;
-        case coap_tcp_8bit:
+        case COAP_TCP_8BIT:
             length = COAP_TCP_HEADER_8_BIT;
             break;
-        case coap_tcp_16bit:
+        case COAP_TCP_16BIT:
             length = COAP_TCP_HEADER_16_BIT;
             break;
-        case coap_tcp_32bit:
+        case COAP_TCP_32BIT:
             length = COAP_TCP_HEADER_32_BIT;
             break;
 #endif
@@ -165,31 +177,31 @@ coap_pdu_init(unsigned char type, unsigned char code, unsigned short id,
 #endif
     if (pdu)
     {
-        coap_pdu_clear(pdu, size, transport, length);
+        coap_pdu_clear2(pdu, size, transport, length);
 
         switch(transport)
         {
-            case coap_udp:
-                pdu->hdr->coap_hdr_udp_t.id = id;
-                pdu->hdr->coap_hdr_udp_t.type = type;
-                pdu->hdr->coap_hdr_udp_t.code = code;
+            case COAP_UDP:
+                pdu->transport_hdr->udp.id = id;
+                pdu->transport_hdr->udp.type = type;
+                pdu->transport_hdr->udp.code = code;
                 break;
 #ifdef WITH_TCP
-            case coap_tcp:
-                pdu->hdr->coap_hdr_tcp_t.header_data[0] = 0;
-                pdu->hdr->coap_hdr_tcp_t.header_data[1] = code;
+            case COAP_TCP:
+                pdu->transport_hdr->tcp.header_data[0] = 0;
+                pdu->transport_hdr->tcp.header_data[1] = code;
                 break;
-            case coap_tcp_8bit:
-                pdu->hdr->coap_hdr_tcp_8bit_t.header_data[0] = COAP_TCP_LENGTH_FIELD_NUM_8_BIT << 4;
-                pdu->hdr->coap_hdr_tcp_8bit_t.header_data[2] = code;
+            case COAP_TCP_8BIT:
+                pdu->transport_hdr->tcp_8bit.header_data[0] = COAP_TCP_LENGTH_FIELD_NUM_8_BIT << 4;
+                pdu->transport_hdr->tcp_8bit.header_data[2] = code;
                 break;
-            case coap_tcp_16bit:
-                pdu->hdr->coap_hdr_tcp_16bit_t.header_data[0] = COAP_TCP_LENGTH_FIELD_NUM_16_BIT << 4;
-                pdu->hdr->coap_hdr_tcp_16bit_t.header_data[3] = code;
+            case COAP_TCP_16BIT:
+                pdu->transport_hdr->tcp_16bit.header_data[0] = COAP_TCP_LENGTH_FIELD_NUM_16_BIT << 4;
+                pdu->transport_hdr->tcp_16bit.header_data[3] = code;
                 break;
-            case coap_tcp_32bit:
-                pdu->hdr->coap_hdr_tcp_32bit_t.header_data[0] = COAP_TCP_LENGTH_FIELD_NUM_32_BIT << 4;
-                pdu->hdr->coap_hdr_tcp_32bit_t.header_data[5] = code;
+            case COAP_TCP_32BIT:
+                pdu->transport_hdr->tcp_32bit.header_data[0] = COAP_TCP_LENGTH_FIELD_NUM_32_BIT << 4;
+                pdu->transport_hdr->tcp_32bit.header_data[5] = code;
                 break;
 #endif
             default:
@@ -204,7 +216,7 @@ coap_pdu_init(unsigned char type, unsigned char code, unsigned short id,
 }
 
 coap_pdu_t *
-coap_new_pdu(coap_transport_type transport, unsigned int size)
+coap_new_pdu2(coap_transport_t transport, unsigned int size)
 {
 #ifndef WITH_TCP
     (void)size;
@@ -212,22 +224,22 @@ coap_new_pdu(coap_transport_type transport, unsigned int size)
     coap_pdu_t *pdu;
 
 #ifndef WITH_CONTIKI
-    pdu = coap_pdu_init(0, 0,
-                        ntohs(COAP_INVALID_TID),
+    pdu = coap_pdu_init2(0, 0,
+                         ntohs(COAP_INVALID_TID),
 #ifndef WITH_TCP
-                        COAP_MAX_PDU_SIZE,
+                         COAP_MAX_PDU_SIZE,
 #else
-                        size,
+                         size,
 #endif
-                        transport);
+                         transport);
 #else /* WITH_CONTIKI */
-    pdu = coap_pdu_init(0, 0, uip_ntohs(COAP_INVALID_TID),
+    pdu = coap_pdu_init2(0, 0, uip_ntohs(COAP_INVALID_TID),
 #ifndef WITH_TCP
-                        COAP_MAX_PDU_SIZE,
+                         COAP_MAX_PDU_SIZE,
 #else
-                        size,
+                         size,
 #endif
-                        transport);
+                         transport);
 #endif /* WITH_CONTIKI */
 
 #ifndef NDEBUG
@@ -260,7 +272,7 @@ size_t coap_get_total_message_length(const unsigned char *data, size_t size)
         return 0;
     }
 
-    coap_transport_type transport = coap_get_tcp_header_type_from_initbyte(
+    coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(
             ((unsigned char *)data)[0] >> 4);
     size_t optPaylaodLen = coap_get_length_from_header((unsigned char *)data,
                                                         transport);
@@ -269,78 +281,78 @@ size_t coap_get_total_message_length(const unsigned char *data, size_t size)
     return headerLen + optPaylaodLen;
 }
 
-coap_transport_type coap_get_tcp_header_type_from_size(unsigned int size)
+coap_transport_t coap_get_tcp_header_type_from_size(unsigned int size)
 {
     if (size < COAP_TCP_LENGTH_FIELD_8_BIT)
     {
-        return coap_tcp;
+        return COAP_TCP;
     }
     else if (size < COAP_TCP_LENGTH_FIELD_16_BIT)
     {
-        return coap_tcp_8bit;
+        return COAP_TCP_8BIT;
     }
     else if (size < COAP_TCP_LENGTH_FIELD_32_BIT)
     {
-        return coap_tcp_16bit;
+        return COAP_TCP_16BIT;
     }
-    else //if (size - COAP_TCP_LENGTH_FIELD_32_BIT < ULONG_MAX) always true due to range of data types
+    else
     {
-        return coap_tcp_32bit;
+        return COAP_TCP_32BIT;
     }
 }
 
-coap_transport_type coap_get_tcp_header_type_from_initbyte(unsigned int length)
+coap_transport_t coap_get_tcp_header_type_from_initbyte(unsigned int length)
 {
-    coap_transport_type type;
+    coap_transport_t type;
     switch(length)
     {
         case COAP_TCP_LENGTH_FIELD_NUM_8_BIT:
-            type = coap_tcp_8bit;
+            type = COAP_TCP_8BIT;
             break;
         case COAP_TCP_LENGTH_FIELD_NUM_16_BIT:
-            type = coap_tcp_16bit;
+            type = COAP_TCP_16BIT;
             break;
         case COAP_TCP_LENGTH_FIELD_NUM_32_BIT:
-            type = coap_tcp_32bit;
+            type = COAP_TCP_32BIT;
             break;
         default:
-            type = coap_tcp;
+            type = COAP_TCP;
     }
     return type;
 }
 
-void coap_add_length(const coap_pdu_t *pdu, coap_transport_type transport, unsigned int length)
+void coap_add_length(const coap_pdu_t *pdu, coap_transport_t transport, unsigned int length)
 {
     assert(pdu);
 
     switch(transport)
     {
-        case coap_tcp:
-            pdu->hdr->coap_hdr_tcp_t.header_data[0] = length << 4;
+        case COAP_TCP:
+            pdu->transport_hdr->tcp.header_data[0] = length << 4;
             break;
-        case coap_tcp_8bit:
+        case COAP_TCP_8BIT:
             if (length > COAP_TCP_LENGTH_FIELD_8_BIT)
             {
-                pdu->hdr->coap_hdr_tcp_8bit_t.header_data[1] =
+                pdu->transport_hdr->tcp_8bit.header_data[1] =
                         length - COAP_TCP_LENGTH_FIELD_8_BIT;
             }
             break;
-        case coap_tcp_16bit:
+        case COAP_TCP_16BIT:
             if (length > COAP_TCP_LENGTH_FIELD_16_BIT)
             {
                 unsigned int total_length = length - COAP_TCP_LENGTH_FIELD_16_BIT;
-                pdu->hdr->coap_hdr_tcp_16bit_t.header_data[1] = (total_length >> 8) & 0x0000ff;
-                pdu->hdr->coap_hdr_tcp_16bit_t.header_data[2] = total_length & 0x000000ff;
+                pdu->transport_hdr->tcp_16bit.header_data[1] = (total_length >> 8) & 0x0000ff;
+                pdu->transport_hdr->tcp_16bit.header_data[2] = total_length & 0x000000ff;
             }
             break;
-        case coap_tcp_32bit:
+        case COAP_TCP_32BIT:
             if (length > COAP_TCP_LENGTH_FIELD_32_BIT)
             {
                 unsigned int total_length = length - COAP_TCP_LENGTH_FIELD_32_BIT;
-                pdu->hdr->coap_hdr_tcp_32bit_t.header_data[1] = total_length >> 24;
-                pdu->hdr->coap_hdr_tcp_32bit_t.header_data[2] = (total_length >> 16) & 0x00ff;
-                pdu->hdr->coap_hdr_tcp_32bit_t.header_data[3] = (total_length >> 8) & 0x0000ff;
-                pdu->hdr->coap_hdr_tcp_32bit_t.header_data[4] = total_length & 0x000000ff;
+                pdu->transport_hdr->tcp_32bit.header_data[1] = total_length >> 24;
+                pdu->transport_hdr->tcp_32bit.header_data[2] = (total_length >> 16) & 0x00ff;
+                pdu->transport_hdr->tcp_32bit.header_data[3] = (total_length >> 8) & 0x0000ff;
+                pdu->transport_hdr->tcp_32bit.header_data[4] = total_length & 0x000000ff;
             }
             break;
         default:
@@ -348,7 +360,7 @@ void coap_add_length(const coap_pdu_t *pdu, coap_transport_type transport, unsig
     }
 }
 
-unsigned int coap_get_length_from_header(const unsigned char *header, coap_transport_type transport)
+unsigned int coap_get_length_from_header(const unsigned char *header, coap_transport_t transport)
 {
     assert(header);
 
@@ -356,17 +368,17 @@ unsigned int coap_get_length_from_header(const unsigned char *header, coap_trans
     unsigned int length_field_data = 0;
     switch(transport)
     {
-        case coap_tcp:
+        case COAP_TCP:
             length = header[0] >> 4;
             break;
-        case coap_tcp_8bit:
+        case COAP_TCP_8BIT:
             length = header[1] + COAP_TCP_LENGTH_FIELD_8_BIT;
             break;
-        case coap_tcp_16bit:
+        case COAP_TCP_16BIT:
             length_field_data = (header[1] << 8 | header[2]);
             length = length_field_data + COAP_TCP_LENGTH_FIELD_16_BIT;
             break;
-        case coap_tcp_32bit:
+        case COAP_TCP_32BIT:
             length_field_data = header[1] << 24 | header[2] << 16 | header[3] << 8 | header[4];
             length = length_field_data + COAP_TCP_LENGTH_FIELD_32_BIT;
             break;
@@ -377,7 +389,7 @@ unsigned int coap_get_length_from_header(const unsigned char *header, coap_trans
     return length;
 }
 
-unsigned int coap_get_length(const coap_pdu_t *pdu, coap_transport_type transport)
+unsigned int coap_get_length(const coap_pdu_t *pdu, coap_transport_t transport)
 {
     assert(pdu);
 
@@ -385,24 +397,24 @@ unsigned int coap_get_length(const coap_pdu_t *pdu, coap_transport_type transpor
     unsigned int length_field_data = 0;
     switch(transport)
     {
-        case coap_tcp:
-            length = pdu->hdr->coap_hdr_tcp_t.header_data[0] >> 4;
+        case COAP_TCP:
+            length = pdu->transport_hdr->tcp.header_data[0] >> 4;
             break;
-        case coap_tcp_8bit:
-            length = pdu->hdr->coap_hdr_tcp_8bit_t.header_data[1] + COAP_TCP_LENGTH_FIELD_8_BIT;
+        case COAP_TCP_8BIT:
+            length = pdu->transport_hdr->tcp_8bit.header_data[1] + COAP_TCP_LENGTH_FIELD_8_BIT;
             break;
-        case coap_tcp_16bit:
+        case COAP_TCP_16BIT:
             length_field_data =
-                    pdu->hdr->coap_hdr_tcp_16bit_t.header_data[1] << 8 |
-                    pdu->hdr->coap_hdr_tcp_16bit_t.header_data[2];
+                    pdu->transport_hdr->tcp_16bit.header_data[1] << 8 |
+                    pdu->transport_hdr->tcp_16bit.header_data[2];
             length = length_field_data + COAP_TCP_LENGTH_FIELD_16_BIT;
             break;
-        case coap_tcp_32bit:
+        case COAP_TCP_32BIT:
             length_field_data =
-                    pdu->hdr->coap_hdr_tcp_32bit_t.header_data[1] << 24 |
-                    pdu->hdr->coap_hdr_tcp_32bit_t.header_data[2] << 16 |
-                    pdu->hdr->coap_hdr_tcp_32bit_t.header_data[3] << 8 |
-                    pdu->hdr->coap_hdr_tcp_32bit_t.header_data[4];
+                    pdu->transport_hdr->tcp_32bit.header_data[1] << 24 |
+                    pdu->transport_hdr->tcp_32bit.header_data[2] << 16 |
+                    pdu->transport_hdr->tcp_32bit.header_data[3] << 8 |
+                    pdu->transport_hdr->tcp_32bit.header_data[4];
             length = length_field_data + COAP_TCP_LENGTH_FIELD_32_BIT;
             break;
         default:
@@ -417,7 +429,7 @@ unsigned int coap_get_tcp_header_length(unsigned char *data)
     assert(data);
 
     unsigned int tokenLength =  data[0] & 0x0f;
-    coap_transport_type transport =
+    coap_transport_t transport =
             coap_get_tcp_header_type_from_initbyte(data[0] >> 4);
     unsigned int length = 0;
 
@@ -425,21 +437,21 @@ unsigned int coap_get_tcp_header_length(unsigned char *data)
     return length;
 }
 
-unsigned int coap_get_tcp_header_length_for_transport(coap_transport_type transport)
+unsigned int coap_get_tcp_header_length_for_transport(coap_transport_t transport)
 {
     unsigned int length = 0;
     switch(transport)
     {
-        case coap_tcp:
+        case COAP_TCP:
             length = COAP_TCP_HEADER_NO_FIELD;
             break;
-        case coap_tcp_8bit:   /* len(4bit) + TKL(4bit) + Len+bytes(1byte) + Code(1byte) */
+        case COAP_TCP_8BIT:   /* len(4bit) + TKL(4bit) + Len+bytes(1byte) + Code(1byte) */
             length = COAP_TCP_HEADER_8_BIT;
             break;
-        case coap_tcp_16bit:  /* len(4bit) + TKL(4bit) + Len+bytes(2byte) + Code(1byte) */
+        case COAP_TCP_16BIT:  /* len(4bit) + TKL(4bit) + Len+bytes(2byte) + Code(1byte) */
             length = COAP_TCP_HEADER_16_BIT;
             break;
-        case coap_tcp_32bit:  /* len(4bit) + TKL(4bit) + Len+bytes(4byte) + Code(1byte) */
+        case COAP_TCP_32BIT:  /* len(4bit) + TKL(4bit) + Len+bytes(4byte) + Code(1byte) */
             length = COAP_TCP_HEADER_32_BIT;
             break;
         default:
@@ -493,27 +505,27 @@ size_t coap_get_opt_header_length(unsigned short key, size_t length)
 
 #endif
 
-void coap_add_code(const coap_pdu_t *pdu, coap_transport_type transport, unsigned int code)
+void coap_add_code(const coap_pdu_t *pdu, coap_transport_t transport, unsigned int code)
 {
     assert(pdu);
 
     switch(transport)
     {
-        case coap_udp:
-            pdu->hdr->coap_hdr_udp_t.code = COAP_RESPONSE_CODE(code);
+        case COAP_UDP:
+            pdu->transport_hdr->udp.code = COAP_RESPONSE_CODE(code);
             break;
 #ifdef WITH_TCP
-        case coap_tcp:
-            pdu->hdr->coap_hdr_tcp_t.header_data[1] = COAP_RESPONSE_CODE(code);
+        case COAP_TCP:
+            pdu->transport_hdr->tcp.header_data[1] = COAP_RESPONSE_CODE(code);
             break;
-        case coap_tcp_8bit:
-            pdu->hdr->coap_hdr_tcp_8bit_t.header_data[2] = COAP_RESPONSE_CODE(code);
+        case COAP_TCP_8BIT:
+            pdu->transport_hdr->tcp_8bit.header_data[2] = COAP_RESPONSE_CODE(code);
             break;
-        case coap_tcp_16bit:
-            pdu->hdr->coap_hdr_tcp_16bit_t.header_data[3] = COAP_RESPONSE_CODE(code);
+        case COAP_TCP_16BIT:
+            pdu->transport_hdr->tcp_16bit.header_data[3] = COAP_RESPONSE_CODE(code);
             break;
-        case coap_tcp_32bit:
-            pdu->hdr->coap_hdr_tcp_32bit_t.header_data[5] = COAP_RESPONSE_CODE(code);
+        case COAP_TCP_32BIT:
+            pdu->transport_hdr->tcp_32bit.header_data[5] = COAP_RESPONSE_CODE(code);
             break;
 #endif
         default:
@@ -521,28 +533,28 @@ void coap_add_code(const coap_pdu_t *pdu, coap_transport_type transport, unsigne
     }
 }
 
-unsigned int coap_get_code(const coap_pdu_t *pdu, coap_transport_type transport)
+unsigned int coap_get_code(const coap_pdu_t *pdu, coap_transport_t transport)
 {
     assert(pdu);
 
     unsigned int code = 0;
     switch(transport)
     {
-        case coap_udp:
-            code = pdu->hdr->coap_hdr_udp_t.code;
+        case COAP_UDP:
+            code = pdu->transport_hdr->udp.code;
             break;
 #ifdef WITH_TCP
-        case coap_tcp:
-            code = pdu->hdr->coap_hdr_tcp_t.header_data[1];
+        case COAP_TCP:
+            code = pdu->transport_hdr->tcp.header_data[1];
             break;
-        case coap_tcp_8bit:
-            code = pdu->hdr->coap_hdr_tcp_8bit_t.header_data[2];
+        case COAP_TCP_8BIT:
+            code = pdu->transport_hdr->tcp_8bit.header_data[2];
             break;
-        case coap_tcp_16bit:
-            code = pdu->hdr->coap_hdr_tcp_16bit_t.header_data[3];
+        case COAP_TCP_16BIT:
+            code = pdu->transport_hdr->tcp_16bit.header_data[3];
             break;
-        case coap_tcp_32bit:
-            code = pdu->hdr->coap_hdr_tcp_32bit_t.header_data[5];
+        case COAP_TCP_32BIT:
+            code = pdu->transport_hdr->tcp_32bit.header_data[5];
             break;
 #endif
         default:
@@ -551,8 +563,13 @@ unsigned int coap_get_code(const coap_pdu_t *pdu, coap_transport_type transport)
     return code;
 }
 
-int coap_add_token(coap_pdu_t *pdu, size_t len, const unsigned char *data,
-                   coap_transport_type transport)
+int coap_add_token(coap_pdu_t *pdu, size_t len, const unsigned char *data)
+{
+    return coap_add_token2(pdu, len, data, COAP_UDP);
+}
+
+int coap_add_token2(coap_pdu_t *pdu, size_t len, const unsigned char *data,
+                    coap_transport_t transport)
 {
     const size_t HEADERLENGTH = len + 4;
     /* must allow for pdu == NULL as callers may rely on this */
@@ -562,34 +579,34 @@ int coap_add_token(coap_pdu_t *pdu, size_t len, const unsigned char *data,
     unsigned char* token = NULL;
     switch(transport)
     {
-        case coap_udp:
-            pdu->hdr->coap_hdr_udp_t.token_length = len;
-            token = pdu->hdr->coap_hdr_udp_t.token;
+        case COAP_UDP:
+            pdu->transport_hdr->udp.token_length = len;
+            token = pdu->transport_hdr->udp.token;
             pdu->length = HEADERLENGTH;
             break;
 #ifdef WITH_TCP
-        case coap_tcp:
-            pdu->hdr->coap_hdr_tcp_t.header_data[0] =
-                    pdu->hdr->coap_hdr_tcp_t.header_data[0] | len;
-            token = pdu->hdr->coap_hdr_tcp_t.token;
+        case COAP_TCP:
+            pdu->transport_hdr->tcp.header_data[0] =
+                    pdu->transport_hdr->tcp.header_data[0] | len;
+            token = pdu->transport_hdr->tcp.token;
             pdu->length = len + COAP_TCP_HEADER_NO_FIELD;
             break;
-        case coap_tcp_8bit:
-            pdu->hdr->coap_hdr_tcp_8bit_t.header_data[0] =
-                    pdu->hdr->coap_hdr_tcp_8bit_t.header_data[0] | len;
-            token = pdu->hdr->coap_hdr_tcp_8bit_t.token;
+        case COAP_TCP_8BIT:
+            pdu->transport_hdr->tcp_8bit.header_data[0] =
+                    pdu->transport_hdr->tcp_8bit.header_data[0] | len;
+            token = pdu->transport_hdr->tcp_8bit.token;
             pdu->length = len + COAP_TCP_HEADER_8_BIT;
             break;
-        case coap_tcp_16bit:
-            pdu->hdr->coap_hdr_tcp_16bit_t.header_data[0] =
-                    pdu->hdr->coap_hdr_tcp_16bit_t.header_data[0] | len;
-            token = pdu->hdr->coap_hdr_tcp_16bit_t.token;
+        case COAP_TCP_16BIT:
+            pdu->transport_hdr->tcp_16bit.header_data[0] =
+                    pdu->transport_hdr->tcp_16bit.header_data[0] | len;
+            token = pdu->transport_hdr->tcp_16bit.token;
             pdu->length = len + COAP_TCP_HEADER_16_BIT;
             break;
-        case coap_tcp_32bit:
-            pdu->hdr->coap_hdr_tcp_32bit_t.header_data[0] =
-                    pdu->hdr->coap_hdr_tcp_32bit_t.header_data[0] | len;
-            token = pdu->hdr->coap_hdr_tcp_32bit_t.token;
+        case COAP_TCP_32BIT:
+            pdu->transport_hdr->tcp_32bit.header_data[0] =
+                    pdu->transport_hdr->tcp_32bit.header_data[0] | len;
+            token = pdu->transport_hdr->tcp_32bit.token;
             pdu->length = len + COAP_TCP_HEADER_32_BIT;
             break;
 #endif
@@ -608,35 +625,41 @@ int coap_add_token(coap_pdu_t *pdu, size_t len, const unsigned char *data,
     return 1;
 }
 
-void coap_get_token(const coap_hdr_t *pdu_hdr, coap_transport_type transport,
+void coap_get_token(const coap_hdr_t *pdu_hdr,
                     unsigned char **token, unsigned int *token_length)
 {
+    coap_get_token2((const coap_hdr_transport_t *)pdu_hdr, COAP_UDP, token, token_length);
+}
+
+void coap_get_token2(const coap_hdr_transport_t *pdu_hdr, coap_transport_t transport,
+                     unsigned char **token, unsigned int *token_length)
+{
     assert(pdu_hdr);
     assert(token);
     assert(token_length);
 
     switch(transport)
     {
-        case coap_udp:
-            *token_length = pdu_hdr->coap_hdr_udp_t.token_length;
-            *token = (unsigned char *)pdu_hdr->coap_hdr_udp_t.token;
+        case COAP_UDP:
+            *token_length = pdu_hdr->udp.token_length;
+            *token = (unsigned char *)pdu_hdr->udp.token;
             break;
 #ifdef WITH_TCP
-        case coap_tcp:
-            *token_length = (pdu_hdr->coap_hdr_tcp_t.header_data[0]) & 0x0f;
-            *token = (unsigned char *)pdu_hdr->coap_hdr_tcp_t.token;
+        case COAP_TCP:
+            *token_length = (pdu_hdr->tcp.header_data[0]) & 0x0f;
+            *token = (unsigned char *)pdu_hdr->tcp.token;
             break;
-        case coap_tcp_8bit:
-            *token_length = (pdu_hdr->coap_hdr_tcp_8bit_t.header_data[0]) & 0x0f;
-            *token = (unsigned char *)pdu_hdr->coap_hdr_tcp_8bit_t.token;
+        case COAP_TCP_8BIT:
+            *token_length = (pdu_hdr->tcp_8bit.header_data[0]) & 0x0f;
+            *token = (unsigned char *)pdu_hdr->tcp_8bit.token;
             break;
-        case coap_tcp_16bit:
-            *token_length = (pdu_hdr->coap_hdr_tcp_16bit_t.header_data[0]) & 0x0f;
-            *token = (unsigned char *)pdu_hdr->coap_hdr_tcp_16bit_t.token;
+        case COAP_TCP_16BIT:
+            *token_length = (pdu_hdr->tcp_16bit.header_data[0]) & 0x0f;
+            *token = (unsigned char *)pdu_hdr->tcp_16bit.token;
             break;
-        case coap_tcp_32bit:
-            *token_length = (pdu_hdr->coap_hdr_tcp_32bit_t.header_data[0]) & 0x0f;
-            *token = (unsigned char *)pdu_hdr->coap_hdr_tcp_32bit_t.token;
+        case COAP_TCP_32BIT:
+            *token_length = (pdu_hdr->tcp_32bit.header_data[0]) & 0x0f;
+            *token = (unsigned char *)pdu_hdr->tcp_32bit.token;
             break;
 #endif
         default:
@@ -644,9 +667,15 @@ void coap_get_token(const coap_hdr_t *pdu_hdr, coap_transport_type transport,
     }
 }
 
-/** @FIXME de-duplicate code with coap_add_option_later */
 size_t coap_add_option(coap_pdu_t *pdu, unsigned short type, unsigned int len,
-        const unsigned char *data, coap_transport_type transport)
+                       const unsigned char *data)
+{
+    return coap_add_option2(pdu, type, len, data, COAP_UDP);
+}
+
+/** @FIXME de-duplicate code with coap_add_option_later */
+size_t coap_add_option2(coap_pdu_t *pdu, unsigned short type, unsigned int len,
+                        const unsigned char *data, coap_transport_t transport)
 {
     size_t optsize;
     coap_opt_t *opt;
@@ -656,28 +685,28 @@ size_t coap_add_option(coap_pdu_t *pdu, unsigned short type, unsigned int len,
 
     if (type < pdu->max_delta)
     {
-        warn("coap_add_option: options are not in correct order\n");
+        warn("coap_add_option2: options are not in correct order\n");
         return 0;
     }
 
     switch(transport)
     {
 #ifdef WITH_TCP
-        case coap_tcp:
-            opt = (unsigned char *) &(pdu->hdr->coap_hdr_tcp_t) + pdu->length;
+        case COAP_TCP:
+            opt = (unsigned char *) &(pdu->transport_hdr->tcp) + pdu->length;
             break;
-        case coap_tcp_8bit:
-            opt = (unsigned char *) &(pdu->hdr->coap_hdr_tcp_8bit_t) + pdu->length;
+        case COAP_TCP_8BIT:
+            opt = (unsigned char *) &(pdu->transport_hdr->tcp_8bit) + pdu->length;
             break;
-        case coap_tcp_16bit:
-            opt = (unsigned char *) &(pdu->hdr->coap_hdr_tcp_16bit_t) + pdu->length;
+        case COAP_TCP_16BIT:
+            opt = (unsigned char *) &(pdu->transport_hdr->tcp_16bit) + pdu->length;
             break;
-        case coap_tcp_32bit:
-            opt = (unsigned char *) &(pdu->hdr->coap_hdr_tcp_32bit_t) + pdu->length;
+        case COAP_TCP_32BIT:
+            opt = (unsigned char *) &(pdu->transport_hdr->tcp_32bit) + pdu->length;
             break;
 #endif
         default:
-            opt = (unsigned char *) &(pdu->hdr->coap_hdr_udp_t) + pdu->length;
+            opt = (unsigned char *) &(pdu->transport_hdr->udp) + pdu->length;
             break;
     }
 
@@ -686,7 +715,7 @@ size_t coap_add_option(coap_pdu_t *pdu, unsigned short type, unsigned int len,
 
     if (!optsize)
     {
-        warn("coap_add_option: cannot add option\n");
+        warn("coap_add_option2: cannot add option\n");
         /* error */
         return 0;
     }
@@ -699,7 +728,7 @@ size_t coap_add_option(coap_pdu_t *pdu, unsigned short type, unsigned int len,
     return optsize;
 }
 
-/** @FIXME de-duplicate code with coap_add_option */
+/** @FIXME de-duplicate code with coap_add_option2 */
 unsigned char*
 coap_add_option_later(coap_pdu_t *pdu, unsigned short type, unsigned int len)
 {
@@ -851,8 +880,13 @@ static size_t next_option_safe(coap_opt_t **optp, size_t *length, coap_option_t*
     return optsize;
 }
 
-int coap_pdu_parse(unsigned char *data, size_t length, coap_pdu_t *pdu,
-                   coap_transport_type transport)
+int coap_pdu_parse(unsigned char *data, size_t length, coap_pdu_t *pdu)
+{
+    return coap_pdu_parse2(data, length, pdu, COAP_UDP);
+}
+
+int coap_pdu_parse2(unsigned char *data, size_t length, coap_pdu_t *pdu,
+                    coap_transport_t transport)
 {
     assert(data);
     assert(pdu);
@@ -866,9 +900,9 @@ int coap_pdu_parse(unsigned char *data, size_t length, coap_pdu_t *pdu,
 
     unsigned int headerSize = 0;
 
-    if (coap_udp == transport)
+    if (COAP_UDP == transport)
     {
-        headerSize = sizeof(pdu->hdr->coap_hdr_udp_t);
+        headerSize = sizeof(pdu->transport_hdr->udp);
     }
 #ifdef WITH_TCP
     else
@@ -887,44 +921,44 @@ int coap_pdu_parse(unsigned char *data, size_t length, coap_pdu_t *pdu,
 #ifdef WITH_TCP
     switch(transport)
     {
-        case coap_udp:
+        case COAP_UDP:
             break;
-        case coap_tcp:
+        case COAP_TCP:
             for (size_t i = 0 ; i < headerSize ; i++)
             {
-                pdu->hdr->coap_hdr_tcp_t.header_data[i] = data[i];
+                pdu->transport_hdr->tcp.header_data[i] = data[i];
             }
 
             tokenLength = data[0] & 0x0f;
-            opt = (unsigned char *) (&(pdu->hdr->coap_hdr_tcp_t) + 1) + tokenLength;
+            opt = (unsigned char *) (&(pdu->transport_hdr->tcp) + 1) + tokenLength;
             break;
-        case coap_tcp_8bit:
+        case COAP_TCP_8BIT:
             for (size_t i = 0 ; i < headerSize ; i++)
             {
-                pdu->hdr->coap_hdr_tcp_8bit_t.header_data[i] = data[i];
+                pdu->transport_hdr->tcp_8bit.header_data[i] = data[i];
             }
 
             tokenLength = data[0] & 0x0f;
-            opt = (unsigned char *) (&(pdu->hdr->coap_hdr_tcp_8bit_t))
+            opt = (unsigned char *) (&(pdu->transport_hdr->tcp_8bit))
                     + tokenLength + COAP_TCP_HEADER_8_BIT;
             break;
-        case coap_tcp_16bit:
+        case COAP_TCP_16BIT:
             for (size_t i = 0 ; i < headerSize ; i++)
             {
-                pdu->hdr->coap_hdr_tcp_16bit_t.header_data[i] = data[i];
+                pdu->transport_hdr->tcp_16bit.header_data[i] = data[i];
             }
 
             tokenLength = data[0] & 0x0f;
-            opt = (unsigned char *) (&(pdu->hdr->coap_hdr_tcp_16bit_t) + 1) + tokenLength;
+            opt = (unsigned char *) (&(pdu->transport_hdr->tcp_16bit) + 1) + tokenLength;
             break;
-        case coap_tcp_32bit:
+        case COAP_TCP_32BIT:
             for (size_t i = 0 ; i < headerSize ; i++)
             {
-                pdu->hdr->coap_hdr_tcp_32bit_t.header_data[i] = data[i];
+                pdu->transport_hdr->tcp_32bit.header_data[i] = data[i];
             }
 
             tokenLength = data[0] & 0x0f;
-            opt = ((unsigned char *) &(pdu->hdr->coap_hdr_tcp_32bit_t)) +
+            opt = ((unsigned char *) &(pdu->transport_hdr->tcp_32bit)) +
                     headerSize + tokenLength;
             break;
         default:
@@ -933,43 +967,43 @@ int coap_pdu_parse(unsigned char *data, size_t length, coap_pdu_t *pdu,
 #endif
     pdu->length = length;
 
-    if (coap_udp == transport)
+    if (COAP_UDP == transport)
     {
-        pdu->hdr->coap_hdr_udp_t.version = data[0] >> 6;
-        pdu->hdr->coap_hdr_udp_t.type = (data[0] >> 4) & 0x03;
-        pdu->hdr->coap_hdr_udp_t.token_length = data[0] & 0x0f;
-        pdu->hdr->coap_hdr_udp_t.code = data[1];
+        pdu->transport_hdr->udp.version = data[0] >> 6;
+        pdu->transport_hdr->udp.type = (data[0] >> 4) & 0x03;
+        pdu->transport_hdr->udp.token_length = data[0] & 0x0f;
+        pdu->transport_hdr->udp.code = data[1];
         pdu->data = NULL;
 
-        tokenLength = pdu->hdr->coap_hdr_udp_t.token_length;
+        tokenLength = pdu->transport_hdr->udp.token_length;
 
         /* sanity checks */
-        if (pdu->hdr->coap_hdr_udp_t.code == 0)
+        if (pdu->transport_hdr->udp.code == 0)
         {
             if (length != headerSize || tokenLength)
             {
-                debug("coap_pdu_parse: empty message is not empty\n");
+                debug("coap_pdu_parse2: empty message is not empty\n");
                 goto discard;
             }
         }
 
         if (length < headerSize + tokenLength || tokenLength > 8)
         {
-            debug("coap_pdu_parse: invalid Token\n");
+            debug("coap_pdu_parse2: invalid Token\n");
             goto discard;
         }
 
-        memcpy(&pdu->hdr->coap_hdr_udp_t.id, data + 2, 2);
+        memcpy(&pdu->transport_hdr->udp.id, data + 2, 2);
 
         /* Finally calculate beginning of data block and thereby check integrity
          * of the PDU structure. */
 
         /* append data (including the Token) to pdu structure */
-        memcpy(&(pdu->hdr->coap_hdr_udp_t) + 1, data + headerSize, length - headerSize);
+        memcpy(&(pdu->transport_hdr->udp) + 1, data + headerSize, length - headerSize);
 
         /* skip header + token */
         length -= (tokenLength + headerSize);
-        opt = (unsigned char *) (&(pdu->hdr->coap_hdr_udp_t) + 1) + tokenLength;
+        opt = (unsigned char *) (&(pdu->transport_hdr->udp) + 1) + tokenLength;
     }
 #ifdef WITH_TCP
     else // common for tcp header setting
@@ -978,7 +1012,7 @@ int coap_pdu_parse(unsigned char *data, size_t length, coap_pdu_t *pdu,
 
         if (length < headerSize + tokenLength || tokenLength > 8)
         {
-            debug("coap_pdu_parse: invalid Token\n");
+            debug("coap_pdu_parse2: invalid Token\n");
             goto discard;
         }
         /* Finally calculate beginning of data block and thereby check integrity
@@ -999,7 +1033,7 @@ int coap_pdu_parse(unsigned char *data, size_t length, coap_pdu_t *pdu,
         memset(&option, 0, sizeof(coap_option_t));
         if (!next_option_safe(&opt, (size_t *) &length, &option))
         {
-            debug("coap_pdu_parse: drop\n");
+            debug("coap_pdu_parse2: drop\n");
             goto discard;
         }
     }
@@ -1013,7 +1047,7 @@ int coap_pdu_parse(unsigned char *data, size_t length, coap_pdu_t *pdu,
 
         if (!length)
         {
-            debug("coap_pdu_parse: message ending in payload start marker\n");
+            debug("coap_pdu_parse2: message ending in payload start marker\n");
             goto discard;
         }
 
index 3af2f0c..dc619e2 100644 (file)
@@ -6,19 +6,19 @@
  * README for terms of use.
  */
 
-#include "config.h"
-#include "net.h"
-#include "debug.h"
-#include "resource.h"
-#include "subscribe.h"
+#include "include/coap/config.h"
+#include "include/coap/net.h"
+#include "include/coap/debug.h"
+#include "include/coap/resource.h"
+#include "include/coap/subscribe.h"
 
 #ifdef WITH_LWIP
-#include "utlist.h"
+#include "include/coap/utlist.h"
 /* mem.h is only needed for the string free calls for
  * COAP_ATTR_FLAGS_RELEASE_NAME / COAP_ATTR_FLAGS_RELEASE_VALUE /
  * COAP_RESOURCE_FLAGS_RELEASE_URI. not sure what those lines should actually
  * do on lwip. */
-#include "mem.h"
+#include "include/coap/mem.h"
 
 #include <lwip/memp.h>
 
@@ -28,8 +28,8 @@
 
 #endif
 #if defined(WITH_POSIX) || defined(WITH_ARDUINO) || defined(_WIN32)
-#include "utlist.h"
-#include "mem.h"
+#include "include/coap/utlist.h"
+#include "include/coap/mem.h"
 
 #define COAP_MALLOC_TYPE(Type) \
   ((coap_##Type##_t *)coap_malloc(sizeof(coap_##Type##_t)))
@@ -471,7 +471,7 @@ void coap_hash_request_uri(const coap_pdu_t *request, coap_key_t key)
     coap_option_filter_clear(filter);
     coap_option_setb(filter, COAP_OPTION_URI_PATH);
 
-    coap_option_iterator_init((coap_pdu_t *) request, &opt_iter, filter, coap_udp);
+    coap_option_iterator_init((coap_pdu_t *) request, &opt_iter, filter);
     while ((option = coap_option_next(&opt_iter)))
         coap_hash(COAP_OPT_VALUE(option), COAP_OPT_LENGTH(option), key);
 }
@@ -766,7 +766,7 @@ static void coap_notify_observers(coap_context_t *context, coap_resource_t *r)
             coap_tid_t tid = COAP_INVALID_TID;
             obs->dirty = 0;
             /* initialize response */
-            response = coap_pdu_init(COAP_MESSAGE_CON, 0, 0, COAP_MAX_PDU_SIZE, coap_udp);
+            response = coap_pdu_init(COAP_MESSAGE_CON, 0, 0, COAP_MAX_PDU_SIZE);
             if (!response)
             {
                 obs->dirty = 1;
@@ -775,7 +775,7 @@ static void coap_notify_observers(coap_context_t *context, coap_resource_t *r)
                 continue;
             }
 
-            if (!coap_add_token(response, obs->token_length, obs->token, coap_udp))
+            if (!coap_add_token(response, obs->token_length, obs->token))
             {
                 obs->dirty = 1;
                 r->partiallydirty = 1;
@@ -787,19 +787,19 @@ static void coap_notify_observers(coap_context_t *context, coap_resource_t *r)
             token.length = obs->token_length;
             token.s = obs->token;
 
-            response->hdr->coap_hdr_udp_t.id = coap_new_message_id(context);
+            response->transport_hdr->udp.id = coap_new_message_id(context);
             if (obs->non && obs->non_cnt < COAP_OBS_MAX_NON)
             {
-                response->hdr->coap_hdr_udp_t.type = COAP_MESSAGE_NON;
+                response->transport_hdr->udp.type = COAP_MESSAGE_NON;
             }
             else
             {
-                response->hdr->coap_hdr_udp_t.type = COAP_MESSAGE_CON;
+                response->transport_hdr->udp.type = COAP_MESSAGE_CON;
             }
             /* fill with observer-specific data */
             h(context, r, &obs->subscriber, NULL, &token, response);
 
-            if (response->hdr->coap_hdr_udp_t.type == COAP_MESSAGE_CON)
+            if (response->transport_hdr->udp.type == COAP_MESSAGE_CON)
             {
                 tid = coap_send_confirmed(context, &obs->subscriber, response);
                 obs->non_cnt = 0;
@@ -810,7 +810,7 @@ static void coap_notify_observers(coap_context_t *context, coap_resource_t *r)
                 obs->non_cnt++;
             }
 
-            if (COAP_INVALID_TID == tid || response->hdr->coap_hdr_udp_t.type != COAP_MESSAGE_CON)
+            if (COAP_INVALID_TID == tid || response->transport_hdr->udp.type != COAP_MESSAGE_CON)
                 coap_delete_pdu(response);
             if (COAP_INVALID_TID == tid)
             {
index 950803d..c615456 100644 (file)
@@ -6,13 +6,13 @@
  * README for terms of use.
  */
 
-#include "config.h"
+#include "include/coap/config.h"
 
 #include <stdio.h>
 
-#include "debug.h"
-#include "mem.h"
-#include "str.h"
+#include "include/coap/debug.h"
+#include "include/coap/mem.h"
+#include "include/coap/str.h"
 
 str *coap_new_string(size_t size)
 {
index f168d96..3a031e2 100644 (file)
@@ -7,7 +7,7 @@
  * README for terms of use.
  */
 
-#include "config.h"
+#include "include/coap/config.h"
 
 #if defined(HAVE_ASSERT_H) && !defined(assert)
 # include <assert.h>
 
 /* #include "resource.h" */
 
-#include "mem.h"
-#include "encode.h"
-#include "debug.h"
-#include "subscribe.h"
+#include "include/coap/mem.h"
+#include "include/coap/encode.h"
+#include "include/coap/debug.h"
+#include "include/coap/subscribe.h"
 
 void coap_subscription_init(coap_subscription_t *s)
 {
@@ -51,9 +51,9 @@ notify(coap_context_t *context, coap_resource_t *res,
     if ( !context || !res || !sub || !(pdu = coap_new_pdu()) )
     return;
 
-    pdu->hdr->coap_hdr_udp_t.type = COAP_MESSAGE_CON;
-    pdu->hdr->coap_hdr_udp_t.id = rand(); /* use a random transaction id */
-    pdu->hdr->coap_hdr_udp_t.code = code;
+    pdu->hdr->type = COAP_MESSAGE_CON;
+    pdu->hdr->id = rand(); /* use a random transaction id */
+    pdu->hdr->code = code;
 
     /* FIXME: content-type and data (how about block?) */
     if (res->uri->host.length)
index d496e72..5e70b81 100644 (file)
@@ -6,7 +6,7 @@
  * README for terms of use.
  */
 
-#include "config.h"
+#include "include/coap/config.h"
 
 #if defined(HAVE_ASSERT_H) && !defined(assert)
 # include <assert.h>
 #include <string.h>
 #include <ctype.h>
 
-#include "mem.h"
-#include "debug.h"
-#include "pdu.h"
-#include "option.h"
-#include "uri.h"
+#include "include/coap/mem.h"
+#include "include/coap/debug.h"
+#include "include/coap/pdu.h"
+#include "include/coap/option.h"
+#include "include/coap/uri.h"
 /**
  * A length-safe version of strchr(). This function returns a pointer
  * to the first occurrence of @p c  in @p s, or @c NULL if not found.
index 6063875..77e96f2 100644 (file)
@@ -1,7 +1,6 @@
 ##
 # CA build script
 ##
-
 import os.path
 
 Import('env')
@@ -10,6 +9,7 @@ ca_os = env.get('TARGET_OS')
 ca_transport = env.get('TARGET_TRANSPORT')
 secured = env.get('SECURED')
 with_ra = env.get ('WITH_RA')
+with_ra_ibb = env.get('WITH_RA_IBB')
 with_tcp = env.get('WITH_TCP')
 src_dir = env.get('SRC_DIR')
 root_dir = os.pardir
@@ -22,8 +22,17 @@ ca_path = os.curdir
 print"Reading ca script %s"%ca_transport
 
 env.PrependUnique(CPPPATH = [ os.path.join(root_dir, 'api') ])
+
+with_upstream_libcoap = env.get('WITH_UPSTREAM_LIBCOAP')
+if with_upstream_libcoap == '1':
+       # For bring up purposes only, we manually copy the forked version to where the unforked version is downloaded.
+       env.AppendUnique(CPPPATH = [os.path.join('#extlibs', 'libcoap', 'libcoap', 'include')])
+       env.AppendUnique(CPPDEFINES = ['WITH_UPSTREAM_LIBCOAP'])
+else:
+       # For bring up purposes only, the forked version will live here.
+       env.AppendUnique(CPPPATH = [ os.path.join(root_dir, 'lib', 'libcoap-4.1.1', 'include')])
+
 env.AppendUnique(CPPPATH = [ os.path.join(root_dir, 'inc'),
-                             os.path.join(root_dir, 'lib', 'libcoap-4.1.1'),
                              os.path.join(src_dir, 'resource', 'csdk', 'logger', 'include'),
                              os.path.join(root_dir, 'common', 'inc'),
                              os.path.join(root_dir, 'util', 'inc') ])
@@ -74,6 +83,7 @@ if env.get('DTLS_WITH_X509') == '1':
        env.AppendUnique(CA_SRC = pkix_src)
 
 if ((secured == '1') and (with_tcp == True)):
+       env.AppendUnique(CPPPATH = [os.path.join(src_dir, 'resource', 'csdk', 'security', 'include')])
        env.AppendUnique(CPPDEFINES = ['__WITH_TLS__'])
        tls_path = 'extlibs/mbedtls';
        tls_headers_path = 'mbedtls/include';
@@ -81,17 +91,24 @@ if ((secured == '1') and (with_tcp == True)):
                env.SConscript(os.path.join(root_dir, tls_path + '/SConscript'))
                env.AppendUnique(CPPPATH = [os.path.join(root_dir, tls_path + '/' + tls_headers_path)])
        else:
-               env.SConscript('#' + tls_path + '/SConscript')
+               if ca_os != 'android':
+                       env.SConscript('#' + tls_path + '/SConscript')
                env.AppendUnique(CPPPATH = ['#' + tls_path + '/' + tls_headers_path])
                env.AppendUnique(CA_SRC = [os.path.join(ca_path, 'adapter_util/ca_adapter_net_tls.c')])
 
 ca_common_src = None
 
+if with_ra_ibb:
+       env.SConscript('#extlibs/wksxmppxep/SConscript')
+
 if env.get('ROUTING') == 'GW':
        env.AppendUnique(CPPDEFINES = ['ROUTING_GATEWAY'])
 elif env.get('ROUTING') == 'EP':
        env.AppendUnique(CPPDEFINES = ['ROUTING_EP'])
 
+if env.get('WITH_PROXY'):
+       env.AppendUnique(CPPDEFINES = ['WITH_CHPROXY'])
+
 if ca_os == 'arduino':
        env.AppendUnique(CPPDEFINES = ['SINGLE_THREAD'])
        env.AppendUnique(CPPDEFINES = ['WITH_ARDUINO'])
@@ -195,7 +212,7 @@ if env.get('LOGGING'):
 if ca_os == 'android':
        lib_env.AppendUnique(LINKFLAGS = ['-Wl,-soname,libconnectivity_abstraction.so'])
 
-if ca_os in ['android', 'tizen', 'linux']:
+if ca_os in ['android', 'tizen', 'linux', 'yocto']:
        lib_env.AppendUnique(LIBS = ['coap'])
        if lib_env.get('SECURED') == '1':
                lib_env.AppendUnique(LIBS = ['tinydtls'])
@@ -204,6 +221,7 @@ if ca_os in ['android', 'tizen', 'linux']:
                lib_env.AppendUnique(LIBS = ['rt'])
                if ((lib_env.get('SECURED') == '1') and ((lib_env.get('WITH_TCP')) or (lib_env.get('WITH_CLOUD')))):
                        lib_env.AppendUnique(LIBS = ['mbedtls','mbedx509','mbedcrypto'])
+
        calib = lib_env.SharedLibrary('connectivity_abstraction', env.get('CA_SRC'))
 elif ca_os in ['msys_nt', 'windows']:
        lib_env.AppendUnique(LIBS = ['coap', 'mswsock', 'ws2_32', 'iphlpapi', 'logger'])
@@ -213,5 +231,6 @@ elif ca_os in ['msys_nt', 'windows']:
        calib = lib_env.StaticLibrary('connectivity_abstraction', env.get('CA_SRC'))
 else:
        calib = lib_env.StaticLibrary('connectivity_abstraction', lib_env.get('CA_SRC'))
+
 lib_env.InstallTarget(calib, 'connectivity_abstraction')
 lib_env.UserInstallTargetLib(calib, 'connectivity_abstraction')
index faade61..53c8fe8 100644 (file)
@@ -21,6 +21,7 @@
 #define _GNU_SOURCE
 
 #include <stddef.h>
+#include <stdbool.h>
 #include "ca_adapter_net_tls.h"
 #include "cacommon.h"
 #include "caipinterface.h"
@@ -85,7 +86,7 @@
  * @def MMBED_TLS_DEBUG_LEVEL
  * @brief Logging level for mbedTLS library
  */
-#define MBED_TLS_DEBUG_LEVEL (4) // Verbose
+#define MBED_TLS_DEBUG_LEVEL (4)
 
 /**
  * @def TLS_MSG_BUF_LEN
  */
 #define MASTER_SECRET_LEN (48)
 
+/**@def TLS_CLOSE_NOTIFY(peer, ret)
+ *
+ * Notifies of existing \a peer about closing TLS connection.
+ *
+ * @param[in] peer remote peer
+ * @param[in] ret used internaly
+ */
 #define TLS_CLOSE_NOTIFY(peer, ret)                                                                \
 do                                                                                                 \
 {                                                                                                  \
     ret = mbedtls_ssl_close_notify(&peer->ssl);                                                    \
 } while (MBEDTLS_ERR_SSL_WANT_WRITE == ret)
 
+/**@def TLS_RET_HANDSHAKE_RES(peer)
+ *
+ * Sets handshake result for callback.
+ *
+ * @param[in] peer remote peer
+ */
 #define TLS_RET_HANDSHAKE_RES(peer)                                                                \
 if (g_tlsHandshakeCallback)                                                                        \
 {                                                                                                  \
     CAErrorInfo_t errorInfo = {.result = CA_STATUS_FAILED};                                        \
     g_tlsHandshakeCallback(&peer->sep.endpoint, &errorInfo);                                       \
 }
-
-#define TLS_CHECK_HANDSHAKE_FAIL(peer, ret, str, mutex, error)                                     \
+/**@def TLS_CHECK_HANDSHAKE_FAIL(peer, ret, str, mutex, error, msg)
+ *
+ * Checks handshake result and send allert if needed.
+ *
+ * @param[in] peer remote peer
+ * @param[in] ret error code
+ * @param[in] str debug string
+ * @param[in] mutex ca mutex
+ * @param[in] return error code
+ * @param[in] msg allert message
+ */
+#define TLS_CHECK_HANDSHAKE_FAIL(peer, ret, str, mutex, error, msg)                                \
 if (0 != ret && MBEDTLS_ERR_SSL_WANT_READ != ret &&  MBEDTLS_ERR_SSL_WANT_WRITE != ret)            \
 {                                                                                                  \
     OIC_LOG_V(ERROR, NET_TLS_TAG, "%s: -0x%x", str, -ret);                                         \
-    TLS_CLOSE_NOTIFY(peer, ret);                                                                   \
+    if ((int) MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE != (int) ret &&                                  \
+        (int) MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY != (int) ret &&                                    \
+        (int) MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO != (int) ret)                                    \
+    {                                                                                              \
+        mbedtls_ssl_send_alert_message(&peer->ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, msg);            \
+    }                                                                                              \
     TLS_RET_HANDSHAKE_RES(peer);                                                                   \
     removePeerFromList(&peer->sep.endpoint);                                                       \
     if (mutex)                                                                                     \
     {                                                                                              \
-        ca_mutex_unlock(g_tlsContextMutex);                                                        \
+        oc_mutex_unlock(g_tlsContextMutex);                                                        \
     }                                                                                              \
+    OIC_LOG_V(DEBUG, NET_TLS_TAG, "Out %s", __func__);                                             \
     return error;                                                                                  \
 }
 
@@ -159,14 +189,58 @@ int tlsCipher[ADAPTER_CIPHER_MAX][2] =
     {MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256, 0}
 };
 
+static int g_cipherSuitesList[2 + 1];
+
 mbedtls_ecp_group_id curve[ADAPTER_CURVE_MAX][2] =
 {
     {MBEDTLS_ECP_DP_SECP256R1, 0}
 };
 
-//TODO add description
 static PkiInfo_t g_pkiInfo = {{NULL, 0}, {NULL, 0}, {NULL, 0}, {NULL, 0}};
 
+typedef struct  {
+    int code;
+    int alert;
+} CrtVerifyAlert_t;
+
+static const CrtVerifyAlert_t crtVerifyAlerts[] = {
+    {MBEDTLS_X509_BADCERT_EXPIRED,       MBEDTLS_SSL_ALERT_MSG_CERT_EXPIRED},
+    {MBEDTLS_X509_BADCERT_REVOKED,       MBEDTLS_SSL_ALERT_MSG_CERT_REVOKED},
+    {MBEDTLS_X509_BADCERT_CN_MISMATCH,   MBEDTLS_SSL_ALERT_MSG_CERT_UNKNOWN},
+    {MBEDTLS_X509_BADCERT_NOT_TRUSTED,   MBEDTLS_SSL_ALERT_MSG_UNKNOWN_CA},
+    {MBEDTLS_X509_BADCRL_NOT_TRUSTED,    MBEDTLS_SSL_ALERT_MSG_UNKNOWN_CA},
+    {MBEDTLS_X509_BADCRL_EXPIRED,        MBEDTLS_SSL_ALERT_MSG_INSUFFICIENT_SECURITY},
+    {MBEDTLS_X509_BADCERT_MISSING,       MBEDTLS_SSL_ALERT_MSG_NO_CERT},
+    {MBEDTLS_X509_BADCERT_SKIP_VERIFY,   MBEDTLS_SSL_ALERT_MSG_INSUFFICIENT_SECURITY},
+    {MBEDTLS_X509_BADCERT_OTHER,         MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR},
+    {MBEDTLS_X509_BADCERT_FUTURE,        MBEDTLS_SSL_ALERT_MSG_BAD_CERT},
+    {MBEDTLS_X509_BADCRL_FUTURE,         MBEDTLS_SSL_ALERT_MSG_INSUFFICIENT_SECURITY},
+    {MBEDTLS_X509_BADCERT_KEY_USAGE,     MBEDTLS_SSL_ALERT_MSG_BAD_CERT},
+    {MBEDTLS_X509_BADCERT_EXT_KEY_USAGE, MBEDTLS_SSL_ALERT_MSG_BAD_CERT},
+    {MBEDTLS_X509_BADCERT_NS_CERT_TYPE,  MBEDTLS_SSL_ALERT_MSG_BAD_CERT},
+    {MBEDTLS_X509_BADCERT_BAD_MD,        MBEDTLS_SSL_ALERT_MSG_BAD_CERT},
+    {MBEDTLS_X509_BADCERT_BAD_PK,        MBEDTLS_SSL_ALERT_MSG_BAD_CERT},
+    {MBEDTLS_X509_BADCERT_BAD_KEY,       MBEDTLS_SSL_ALERT_MSG_BAD_CERT},
+    {MBEDTLS_X509_BADCRL_BAD_MD,         MBEDTLS_SSL_ALERT_MSG_BAD_CERT},
+    {MBEDTLS_X509_BADCRL_BAD_PK,         MBEDTLS_SSL_ALERT_MSG_BAD_CERT},
+    {MBEDTLS_X509_BADCRL_BAD_KEY,        MBEDTLS_SSL_ALERT_MSG_BAD_CERT},
+    {0, 0}
+};
+
+static int getAlertCode(uint32_t flags)
+{
+    const CrtVerifyAlert_t *cur;
+
+    for (cur = crtVerifyAlerts; cur->alert != 0 ; cur++)
+    {
+        if (flags & cur->code)
+        {
+            return cur->alert;
+        }
+    }
+    return 0;
+}
+
 #ifndef NDEBUG
 /**
  * Pass a message to the OIC logger.
@@ -220,6 +294,8 @@ typedef struct TlsContext
     AdapterCipher_t cipher;
     TlsCallbacks_t adapterCallbacks[MAX_SUPPORTED_ADAPTERS];
     mbedtls_x509_crl crl;
+    bool cipherFlag[2];
+    int selectedCipher;
 
 } TlsContext_t;
 
@@ -234,7 +310,11 @@ static TlsContext_t * g_caTlsContext = NULL;
  * @brief callback to get TLS credentials (same as for DTLS)
  */
 static CAGetDTLSPskCredentialsHandler g_getCredentialsCallback = NULL;
-
+/**
+ * @var g_getCerdentilTypesCallback
+ * @brief callback to get different credential types from SRM
+ */
+static CAgetCredentialTypesHandler g_getCredentialTypesCallback = NULL;
 /**
  * @var g_getPkixInfoCallback
  *
@@ -246,7 +326,7 @@ static CAgetPkixInfoHandler g_getPkixInfoCallback = NULL;
  * @var g_dtlsContextMutex
  * @brief Mutex to synchronize access to g_caTlsContext.
  */
-static ca_mutex g_tlsContextMutex = NULL;
+static oc_mutex g_tlsContextMutex = NULL;
 
 /**
  * @var g_tlsHandshakeCallback
@@ -255,7 +335,7 @@ static ca_mutex g_tlsContextMutex = NULL;
 static CAErrorCallback g_tlsHandshakeCallback = NULL;
 
 /**
- * Data structure for holding the data to be rceived.
+ * Data structure for holding the data to be received.
  */
 typedef struct TlsRecBuf
 {
@@ -291,6 +371,12 @@ void CAsetPkixInfoCallback(CAgetPkixInfoHandler infoCallback)
     g_getPkixInfoCallback = infoCallback;
     OIC_LOG_V(DEBUG, NET_TLS_TAG, "Out %s", __func__);
 }
+void CAsetCredentialTypesCallback(CAgetCredentialTypesHandler credTypesCallback)
+{
+    OIC_LOG_V(DEBUG, NET_TLS_TAG, "In %s", __func__);
+    g_getCredentialTypesCallback = credTypesCallback;
+    OIC_LOG_V(DEBUG, NET_TLS_TAG, "Out %s", __func__);
+}
 /**
  * Write callback.
  *
@@ -334,17 +420,36 @@ static int recvTls(void * tep, unsigned char * data, size_t dataLen)
     memcpy(data, recBuf->buff + recBuf->loaded, retLen);
     recBuf->loaded += retLen;
 
-    OIC_LOG_BUFFER(DEBUG, NET_TLS_TAG, data, retLen);
     OIC_LOG_V(DEBUG, NET_TLS_TAG, "Out %s", __func__);
     return (int)retLen;
 }
 
-//TODO add description
+/**
+ * Parse chain of X.509 certificates.
+ *
+ * @param[out] crt     container for X.509 certificates
+ * @param[in]  data    buffer with X.509 certificates. Certificates may be in either in PEM
+                       or DER format in a jumble. Each PEM certificate must be NULL-terminated.
+ * @param[in]  buflen  buffer length
+ *
+ * @return  0 on success, -1 on error
+ */
 static int parseChain(mbedtls_x509_crt * crt, const unsigned char * buf, int buflen)
 {
     VERIFY_NON_NULL_RET(crt, NET_TLS_TAG, "Param crt is NULL" , -1);
     VERIFY_NON_NULL_RET(buf, NET_TLS_TAG, "Param buf is NULL" , -1);
 
+    char pemCertHeader[] = {
+        0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x42, 0x45, 0x47, 0x49, 0x4e, 0x20, 0x43, 0x45, 0x52,
+        0x54, 0x49, 0x46, 0x49, 0x43, 0x41, 0x54, 0x45, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d
+    };
+    char pemCertFooter[] = {
+        0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x45, 0x4e, 0x44, 0x20, 0x43, 0x45, 0x52, 0x54, 0x49,
+        0x46, 0x49, 0x43, 0x41, 0x54, 0x45, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x0a, 0x00
+    };
+    size_t pemCertHeaderLen = sizeof(pemCertHeader);
+    size_t pemCertFooterLen = sizeof(pemCertFooter);
+
     int pos = 0;
     int len = 0;
     int ret = 0;
@@ -355,7 +460,7 @@ static int parseChain(mbedtls_x509_crt * crt, const unsigned char * buf, int buf
             len = (((int) buf[pos+2]) << 8) | buf[pos+3];
             if (pos + len < buflen)
             {
-                ret = mbedtls_x509_crt_parse_der(crt, buf+pos, len+4);
+                ret = mbedtls_x509_crt_parse_der(crt, buf+pos, len + 4); 
                 if( 0 != ret)
                 {
                     OIC_LOG_V(ERROR, NET_TLS_TAG, "mbedtls_x509_crt_parse returned -0x%x", -ret);
@@ -364,6 +469,19 @@ static int parseChain(mbedtls_x509_crt * crt, const unsigned char * buf, int buf
             }
             pos += len + 4;
         }
+        else if (0 == memcmp(buf + pos, pemCertHeader, pemCertHeaderLen))
+        {
+            void * endPos = NULL;
+            endPos = memmem(&(buf[pos]), buflen - pos, pemCertFooter, pemCertFooterLen);
+            if (NULL == endPos)
+            {
+                OIC_LOG(ERROR, NET_TLS_TAG, "Error: end of PEM certificate not found.");
+                return -1;
+            }
+            len = (char*)endPos - ((char*)(buf + pos)) + pemCertFooterLen;
+            ret = mbedtls_x509_crt_parse(crt, buf, len);
+            pos += len;
+        }
         else
         {
              OIC_LOG_V(ERROR, NET_TLS_TAG, "mbedtls_x509_crt_parse returned -0x%x", -ret);
@@ -372,64 +490,67 @@ static int parseChain(mbedtls_x509_crt * crt, const unsigned char * buf, int buf
     }
     return 0;
 }
-//TODO add description
+//Loads PKIX related information from SRM
 static int loadX509()
 {
     OIC_LOG_V(DEBUG, NET_TLS_TAG, "In %s", __func__);
     VERIFY_NON_NULL_RET(g_getPkixInfoCallback, NET_TLS_TAG, "PKIX info callback is NULL", -1);
-
+    bool loadOwnCred = true;
     g_getPkixInfoCallback(&g_pkiInfo);
 
-    int ret = parseChain(&g_caTlsContext->ca, g_pkiInfo.ca.data, g_pkiInfo.ca.len);
-    if(0 != ret)
+    // optional
+    int ret = parseChain(&g_caTlsContext->crt, g_pkiInfo.crt.data, g_pkiInfo.crt.len);
+    if (0 != ret)
     {
-        OIC_LOG(ERROR, NET_TLS_TAG, "CA chain parsing error");
-        OIC_LOG_V(DEBUG, NET_TLS_TAG, "Out %s", __func__);
-        return -1;
+        OIC_LOG(WARNING, NET_TLS_TAG, "Own certificate chain parsing error");
+        goto required;
     }
-    ret = parseChain(&g_caTlsContext->crt, g_pkiInfo.crt.data, g_pkiInfo.crt.len);
-    if(0 != ret)
+    ret =  mbedtls_pk_parse_key(&g_caTlsContext->pkey, g_pkiInfo.key.data, g_pkiInfo.key.len,
+                                                                               NULL, 0);
+    if (0 != ret)
     {
-        OIC_LOG(ERROR, NET_TLS_TAG, "Own certificate chain parsing error");
-        OIC_LOG_V(DEBUG, NET_TLS_TAG, "Out %s", __func__);
-        return -1;
+        OIC_LOG(WARNING, NET_TLS_TAG, "Key parsing error");
+        goto required;
     }
 
-    ret =  mbedtls_pk_parse_key(&g_caTlsContext->pkey, g_pkiInfo.key.data, g_pkiInfo.key.len,
-                                                                                           NULL, 0);
-    if(0 != ret)
+    ret = mbedtls_ssl_conf_own_cert(&g_caTlsContext->serverConf, &g_caTlsContext->crt,
+                                                                 &g_caTlsContext->pkey);
+    if (0 != ret)
     {
-        OIC_LOG(ERROR, NET_TLS_TAG, "Key parsing error");
-        OIC_LOG_V(DEBUG, NET_TLS_TAG, "Out %s", __func__);
-        return -1;
+        OIC_LOG(WARNING, NET_TLS_TAG, "Own certificate parsing error");
+        goto required;
     }
-    ret = mbedtls_x509_crl_parse_der(&g_caTlsContext->crl, g_pkiInfo.crl.data, g_pkiInfo.crl.len);
+    ret = mbedtls_ssl_conf_own_cert( &g_caTlsContext->clientConf, &g_caTlsContext->crt,
+                                                                  &g_caTlsContext->pkey);
     if(0 != ret)
     {
-        OIC_LOG(ERROR, NET_TLS_TAG, "CRL parsing error");
-        OIC_LOG_V(DEBUG, NET_TLS_TAG, "Out %s", __func__);
-        //TODO
-        //return -1;
+        OIC_LOG(WARNING, NET_TLS_TAG, "Own certificate configuration error");
+        goto required;
     }
 
-    mbedtls_ssl_conf_ca_chain(&g_caTlsContext->clientConf, &g_caTlsContext->ca, NULL);
-    mbedtls_ssl_conf_ca_chain(&g_caTlsContext->serverConf, &g_caTlsContext->ca, NULL);
+    required:
 
-    ret = mbedtls_ssl_conf_own_cert(&g_caTlsContext->serverConf, &g_caTlsContext->crt,
-                                                                             &g_caTlsContext->pkey);
+    ret = parseChain(&g_caTlsContext->ca, g_pkiInfo.ca.data, g_pkiInfo.ca.len);
     if(0 != ret)
     {
-        OIC_LOG(ERROR, NET_TLS_TAG, "Certificate parsing error");
+        OIC_LOG(ERROR, NET_TLS_TAG, "CA chain parsing error");
         OIC_LOG_V(DEBUG, NET_TLS_TAG, "Out %s", __func__);
         return -1;
     }
-    ret = mbedtls_ssl_conf_own_cert( &g_caTlsContext->clientConf, &g_caTlsContext->crt,
-                                                                             &g_caTlsContext->pkey);
+
+    ret = mbedtls_x509_crl_parse_der(&g_caTlsContext->crl, g_pkiInfo.crl.data, g_pkiInfo.crl.len);
     if(0 != ret)
     {
-        OIC_LOG(ERROR, NET_TLS_TAG, "Certificate parsing error");
-        OIC_LOG_V(DEBUG, NET_TLS_TAG, "Out %s", __func__);
-        return -1;
+        OIC_LOG(WARNING, NET_TLS_TAG, "CRL parsing error");
+        mbedtls_ssl_conf_ca_chain(&g_caTlsContext->clientConf, &g_caTlsContext->ca, NULL);
+        mbedtls_ssl_conf_ca_chain(&g_caTlsContext->serverConf, &g_caTlsContext->ca, NULL);
+    }
+    else
+    {
+        mbedtls_ssl_conf_ca_chain(&g_caTlsContext->clientConf, &g_caTlsContext->ca,
+                                                                              &g_caTlsContext->crl);
+        mbedtls_ssl_conf_ca_chain(&g_caTlsContext->serverConf, &g_caTlsContext->ca,
+                                                                              &g_caTlsContext->crl);
     }
 
     OIC_LOG_V(DEBUG, NET_TLS_TAG, "Out %s", __func__);
@@ -612,18 +733,18 @@ CAResult_t CAcloseTlsConnection(const CAEndpoint_t *endpoint)
     OIC_LOG_V(DEBUG, NET_TLS_TAG, "In %s", __func__);
     VERIFY_NON_NULL_RET(endpoint, NET_TLS_TAG, "Param endpoint is NULL" , CA_STATUS_INVALID_PARAM);
 
-    ca_mutex_lock(g_tlsContextMutex);
+    oc_mutex_lock(g_tlsContextMutex);
     if (NULL == g_caTlsContext)
     {
         OIC_LOG(ERROR, NET_TLS_TAG, "Context is NULL");
-        ca_mutex_unlock(g_tlsContextMutex);
+        oc_mutex_unlock(g_tlsContextMutex);
         return CA_STATUS_FAILED;
     }
     TlsEndPoint_t * tep = getTlsPeer(endpoint);
     if (NULL == tep)
     {
         OIC_LOG(ERROR, NET_TLS_TAG, "Session does not exist");
-        ca_mutex_unlock(g_tlsContextMutex);
+        oc_mutex_unlock(g_tlsContextMutex);
         return CA_STATUS_FAILED;
     }
     /* No error checking, the connection might be closed already */
@@ -635,7 +756,7 @@ CAResult_t CAcloseTlsConnection(const CAEndpoint_t *endpoint)
     while (MBEDTLS_ERR_SSL_WANT_WRITE == ret);
 
     removePeerFromList(&tep->sep.endpoint);
-    ca_mutex_unlock(g_tlsContextMutex);
+    oc_mutex_unlock(g_tlsContextMutex);
 
     OIC_LOG_V(DEBUG, NET_TLS_TAG, "Out %s", __func__);
     return CA_STATUS_OK;
@@ -697,20 +818,69 @@ static TlsEndPoint_t * newTlsEndPoint(const CAEndpoint_t * endpoint, mbedtls_ssl
 static int initPskIdentity(mbedtls_ssl_config * config)
 {
     uint8_t idBuf[UUID_LENGTH] = {0};
+    OIC_LOG_V(DEBUG, NET_TLS_TAG, "In %s", __func__);
     VERIFY_NON_NULL_RET(config, NET_TLS_TAG, "Param config is NULL" , -1);
 
     if (0 > g_getCredentialsCallback(CA_DTLS_PSK_IDENTITY, NULL, 0, idBuf, UUID_LENGTH))
     {
         OIC_LOG(ERROR, NET_TLS_TAG, "Identity not found");
+        OIC_LOG_V(DEBUG, NET_TLS_TAG, "Out %s", __func__);
         return -1;
     }
     if (0 != mbedtls_ssl_conf_psk(config, idBuf, 0, idBuf, UUID_LENGTH))
     {
         OIC_LOG(ERROR, NET_TLS_TAG, "Identity initialization failed!");
+        OIC_LOG_V(DEBUG, NET_TLS_TAG, "Out %s", __func__);
         return -1;
     }
+    OIC_LOG_V(DEBUG, NET_TLS_TAG, "Out %s", __func__);
     return 0;
 }
+static void setupCipher(mbedtls_ssl_config * config)
+{
+    OIC_LOG_V(DEBUG, NET_TLS_TAG, "In %s", __func__);
+    if (NULL == g_getCredentialTypesCallback)
+    {
+        OIC_LOG(ERROR, NET_TLS_TAG, "Param callback is null");
+        return;
+    }
+
+    g_getCredentialTypesCallback(g_caTlsContext->cipherFlag);
+    // Retrieve the PSK credential from SRM
+    // PIN OTM if (true == g_caTlsContext->cipherFlag[0] && 0 != initPskIdentity(config))
+    if (0 != initPskIdentity(config))
+    {
+        OIC_LOG(ERROR, NET_TLS_TAG, "PSK identity initialization failed!");
+    }
+
+    // Retrieve the ECC credential from SRM
+    if (true == g_caTlsContext->cipherFlag[1] || ADAPTER_TLS_RSA_WITH_AES_256_CBC_SHA == g_caTlsContext->cipher)
+    {
+        int ret = loadX509();
+        if (0 != ret)
+        {
+            OIC_LOG(ERROR, NET_TLS_TAG, "Failed to init X.509");
+        }
+    }
+    if (ADAPTER_CIPHER_MAX == g_caTlsContext->cipher)
+    {
+        int index = 0;
+        memset(g_cipherSuitesList, 0, sizeof(g_cipherSuitesList));
+        if (true == g_caTlsContext->cipherFlag[1])
+        {
+            g_cipherSuitesList[index] = MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8;
+            index ++;
+        }
+        if (true == g_caTlsContext->cipherFlag[0])
+        {
+           g_cipherSuitesList[index] = MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256;
+        }
+
+        mbedtls_ssl_conf_ciphersuites(config, g_cipherSuitesList);
+    }
+
+    OIC_LOG_V(DEBUG, NET_TLS_TAG, "Out %s", __func__);
+}
 /**
  * Initiate TLS handshake with endpoint.
  *
@@ -726,13 +896,7 @@ static TlsEndPoint_t * initiateTlsHandshake(const CAEndpoint_t *endpoint)
     OIC_LOG_V(DEBUG, NET_TLS_TAG, "In %s", __func__);
     VERIFY_NON_NULL_RET(endpoint, NET_TLS_TAG, "Param endpoint is NULL" , NULL);
 
-    // Retrieve the credentials blob from security module
-    if (ADAPTER_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256 == g_caTlsContext->cipher &&
-            0 != initPskIdentity(&g_caTlsContext->clientConf))
-    {
-        OIC_LOG(ERROR, NET_TLS_TAG, "Client PSK identity initialization failed!");
-        return NULL;
-    }
+
 
     tep = newTlsEndPoint(endpoint, &g_caTlsContext->clientConf);
     if (NULL == tep)
@@ -741,17 +905,8 @@ static TlsEndPoint_t * initiateTlsHandshake(const CAEndpoint_t *endpoint)
         return NULL;
     }
 
-    if (ADAPTER_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 == g_caTlsContext->cipher ||
-        ADAPTER_TLS_RSA_WITH_AES_256_CBC_SHA == g_caTlsContext->cipher)
-    {
-        ret = loadX509();
-        if (0 != ret)
-        {
-            OIC_LOG(ERROR, NET_TLS_TAG, "Failed to init X.509");
-            deleteTlsEndPoint(tep);
-            return NULL;
-        }
-    }
+    //Load allowed SVR suites from SVR DB
+    setupCipher(&g_caTlsContext->clientConf);
 
     OIC_LOG_V(DEBUG, NET_TLS_TAG, "Add %s:%d", tep->sep.endpoint.addr, tep->sep.endpoint.port);
     ret = u_arraylist_add(g_caTlsContext->peerList, (void *) tep);
@@ -769,7 +924,7 @@ static TlsEndPoint_t * initiateTlsHandshake(const CAEndpoint_t *endpoint)
         {
             break;
         }
-        TLS_CHECK_HANDSHAKE_FAIL(tep, ret, "Handshake error", 0, NULL);
+        TLS_CHECK_HANDSHAKE_FAIL(tep, ret, "Handshake error", 0, NULL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE);
     }
     OIC_LOG_V(DEBUG, NET_TLS_TAG, "Out %s", __func__);
     return tep;
@@ -783,7 +938,7 @@ void CAdeinitTlsAdapter()
     VERIFY_NON_NULL_VOID(g_tlsContextMutex, NET_TLS_TAG, "context mutex is NULL");
 
     //Lock tlsContext mutex
-    ca_mutex_lock(g_tlsContextMutex);
+    oc_mutex_lock(g_tlsContextMutex);
 
     // Clear all lists
     deletePeerList();
@@ -801,8 +956,8 @@ void CAdeinitTlsAdapter()
     g_caTlsContext = NULL;
 
     // Unlock tlsContext mutex and de-initialize it
-    ca_mutex_unlock(g_tlsContextMutex);
-    ca_mutex_free(g_tlsContextMutex);
+    oc_mutex_unlock(g_tlsContextMutex);
+    oc_mutex_free(g_tlsContextMutex);
     g_tlsContextMutex = NULL;
 
     OIC_LOG_V(DEBUG, NET_TLS_TAG, "Out %s ", __func__);
@@ -815,7 +970,7 @@ CAResult_t CAinitTlsAdapter()
     // Initialize mutex for tlsContext
     if (NULL == g_tlsContextMutex)
     {
-        g_tlsContextMutex = ca_mutex_new();
+        g_tlsContextMutex = oc_mutex_new();
         VERIFY_NON_NULL_RET(g_tlsContextMutex, NET_TLS_TAG, "malloc failed",
                             CA_MEMORY_ALLOC_FAILED);
     }
@@ -826,14 +981,14 @@ CAResult_t CAinitTlsAdapter()
     }
 
     // Lock tlsContext mutex and create tlsContext
-    ca_mutex_lock(g_tlsContextMutex);
+    oc_mutex_lock(g_tlsContextMutex);
     g_caTlsContext = (TlsContext_t *)OICCalloc(1, sizeof(TlsContext_t));
 
     if (NULL == g_caTlsContext)
     {
         OIC_LOG(ERROR, NET_TLS_TAG, "Context malloc failed");
-        ca_mutex_unlock(g_tlsContextMutex);
-        ca_mutex_free(g_tlsContextMutex);
+        oc_mutex_unlock(g_tlsContextMutex);
+        oc_mutex_free(g_tlsContextMutex);
         g_tlsContextMutex = NULL;
         return CA_MEMORY_ALLOC_FAILED;
     }
@@ -846,8 +1001,8 @@ CAResult_t CAinitTlsAdapter()
         OIC_LOG(ERROR, NET_TLS_TAG, "peerList initialization failed!");
         OICFree(g_caTlsContext);
         g_caTlsContext = NULL;
-        ca_mutex_unlock(g_tlsContextMutex);
-        ca_mutex_free(g_tlsContextMutex);
+        oc_mutex_unlock(g_tlsContextMutex);
+        oc_mutex_free(g_tlsContextMutex);
         g_tlsContextMutex = NULL;
         return CA_STATUS_FAILED;
     }
@@ -872,7 +1027,7 @@ CAResult_t CAinitTlsAdapter()
     if(urandomFd == -1)
     {
         OIC_LOG(ERROR, NET_TLS_TAG, "Fails open /dev/urandom!");
-        ca_mutex_unlock(g_tlsContextMutex);
+        oc_mutex_unlock(g_tlsContextMutex);
         CAdeinitTlsAdapter();
         return CA_STATUS_FAILED;
     }
@@ -880,7 +1035,7 @@ CAResult_t CAinitTlsAdapter()
     {
         OIC_LOG(ERROR, NET_TLS_TAG, "Fails read from /dev/urandom!");
         close(urandomFd);
-        ca_mutex_unlock(g_tlsContextMutex);
+        oc_mutex_unlock(g_tlsContextMutex);
         CAdeinitTlsAdapter();
         return CA_STATUS_FAILED;
     }
@@ -893,7 +1048,7 @@ CAResult_t CAinitTlsAdapter()
                                   &g_caTlsContext->entropy, seed, sizeof(SEED)))
     {
         OIC_LOG(ERROR, NET_TLS_TAG, "Seed initialization failed!");
-        ca_mutex_unlock(g_tlsContextMutex);
+        oc_mutex_unlock(g_tlsContextMutex);
         CAdeinitTlsAdapter();
         return CA_STATUS_FAILED;
     }
@@ -906,7 +1061,7 @@ CAResult_t CAinitTlsAdapter()
                                     MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_PRESET_DEFAULT) != 0)
     {
         OIC_LOG(ERROR, NET_TLS_TAG, "Client config initialization failed!");
-        ca_mutex_unlock(g_tlsContextMutex);
+        oc_mutex_unlock(g_tlsContextMutex);
         CAdeinitTlsAdapter();
         return CA_STATUS_FAILED;
     }
@@ -933,7 +1088,7 @@ CAResult_t CAinitTlsAdapter()
                                     MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_PRESET_DEFAULT) != 0)
     {
         OIC_LOG(ERROR, NET_TLS_TAG, "Server config initialization failed!");
-        ca_mutex_unlock(g_tlsContextMutex);
+        oc_mutex_unlock(g_tlsContextMutex);
         CAdeinitTlsAdapter();
         return CA_STATUS_FAILED;
     }
@@ -952,8 +1107,8 @@ CAResult_t CAinitTlsAdapter()
     mbedtls_debug_set_threshold(MBED_TLS_DEBUG_LEVEL);
 #endif
 
-    // set default cipher to PSK
-    CAsetTlsCipherSuite(MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256);
+    // set default cipher
+    g_caTlsContext->cipher = ADAPTER_CIPHER_MAX;
 
     // init X.509
     mbedtls_x509_crt_init(&g_caTlsContext->ca);
@@ -961,7 +1116,7 @@ CAResult_t CAinitTlsAdapter()
     mbedtls_pk_init(&g_caTlsContext->pkey);
     mbedtls_x509_crl_init(&g_caTlsContext->crl);
 
-    ca_mutex_unlock(g_tlsContextMutex);
+    oc_mutex_unlock(g_tlsContextMutex);
 
     OIC_LOG_V(DEBUG, NET_TLS_TAG, "Out %s", __func__);
     return CA_STATUS_OK;
@@ -1026,11 +1181,11 @@ CAResult_t CAencryptTls(const CAEndpoint_t *endpoint,
 
     OIC_LOG_V(DEBUG, NET_TLS_TAG, "Data to be encrypted dataLen [%d]", dataLen);
 
-    ca_mutex_lock(g_tlsContextMutex);
+    oc_mutex_lock(g_tlsContextMutex);
     if(NULL == g_caTlsContext)
     {
         OIC_LOG(ERROR, NET_TLS_TAG, "Context is NULL");
-        ca_mutex_unlock(g_tlsContextMutex);
+        oc_mutex_unlock(g_tlsContextMutex);
         return CA_STATUS_FAILED;
     }
 
@@ -1042,7 +1197,7 @@ CAResult_t CAencryptTls(const CAEndpoint_t *endpoint,
     if (NULL == tep)
     {
         OIC_LOG(ERROR, NET_TLS_TAG, "TLS handshake failed");
-        ca_mutex_unlock(g_tlsContextMutex);
+        oc_mutex_unlock(g_tlsContextMutex);
         return CA_STATUS_FAILED;
     }
 
@@ -1059,7 +1214,7 @@ CAResult_t CAencryptTls(const CAEndpoint_t *endpoint,
                 g_tlsHandshakeCallback(&tep->sep.endpoint, &errorInfo);
             }
             removePeerFromList(&tep->sep.endpoint);
-            ca_mutex_unlock(g_tlsContextMutex);
+            oc_mutex_unlock(g_tlsContextMutex);
             return CA_STATUS_FAILED;
         }
     }
@@ -1069,12 +1224,12 @@ CAResult_t CAencryptTls(const CAEndpoint_t *endpoint,
         if (NULL == msg || !u_arraylist_add(tep->cacheList, (void *) msg))
         {
             OIC_LOG(ERROR, NET_TLS_TAG, "u_arraylist_add failed!");
-            ca_mutex_unlock(g_tlsContextMutex);
+            oc_mutex_unlock(g_tlsContextMutex);
             return CA_STATUS_FAILED;
         }
     }
 
-    ca_mutex_unlock(g_tlsContextMutex);
+    oc_mutex_unlock(g_tlsContextMutex);
 
     OIC_LOG_V(DEBUG, NET_TLS_TAG, "Out %s", __func__);
     return CA_STATUS_OK;
@@ -1194,20 +1349,14 @@ CAResult_t CAdecryptTls(const CASecureEndpoint_t *sep, uint8_t *data, uint32_t d
     VERIFY_NON_NULL_RET(sep, NET_TLS_TAG, "endpoint is NULL" , CA_STATUS_INVALID_PARAM);
     VERIFY_NON_NULL_RET(data, NET_TLS_TAG, "Param data is NULL" , CA_STATUS_INVALID_PARAM);
 
-    ca_mutex_lock(g_tlsContextMutex);
+    oc_mutex_lock(g_tlsContextMutex);
     if (NULL == g_caTlsContext)
     {
         OIC_LOG(ERROR, NET_TLS_TAG, "Context is NULL");
-        ca_mutex_unlock(g_tlsContextMutex);
+        oc_mutex_unlock(g_tlsContextMutex);
         return CA_STATUS_FAILED;
     }
 
-    if (ADAPTER_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256 == g_caTlsContext->cipher &&
-            0 != initPskIdentity(&g_caTlsContext->serverConf))
-    {
-        ca_mutex_unlock(g_tlsContextMutex);
-        return CA_STATUS_FAILED;
-    }
 
     TlsEndPoint_t * peer = getTlsPeer(&sep->endpoint);
     if (NULL == peer)
@@ -1216,33 +1365,22 @@ CAResult_t CAdecryptTls(const CASecureEndpoint_t *sep, uint8_t *data, uint32_t d
         if (NULL == peer)
         {
             OIC_LOG(ERROR, NET_TLS_TAG, "Malloc failed!");
-            ca_mutex_unlock(g_tlsContextMutex);
+            oc_mutex_unlock(g_tlsContextMutex);
             return CA_STATUS_FAILED;
         }
-
-        if (ADAPTER_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 == g_caTlsContext->cipher ||
-            ADAPTER_TLS_RSA_WITH_AES_256_CBC_SHA == g_caTlsContext->cipher)
-        {
-            ret = loadX509();
-            if (0 != ret)
-            {
-                OIC_LOG(ERROR, NET_TLS_TAG, "Failed to init X.509");
-                deleteTlsEndPoint(peer);
-                ca_mutex_unlock(g_tlsContextMutex);
-                return CA_STATUS_FAILED;
-            }
-        }
+        //Load allowed SVR suites from SVR DB
+        setupCipher(&g_caTlsContext->serverConf);
 
         ret = u_arraylist_add(g_caTlsContext->peerList, (void *) peer);
         if (!ret)
         {
             OIC_LOG(ERROR, NET_TLS_TAG, "u_arraylist_add failed!");
             OICFree(peer);
-            ca_mutex_unlock(g_tlsContextMutex);
+            oc_mutex_unlock(g_tlsContextMutex);
             return CA_STATUS_FAILED;
         }
     }
-    OIC_LOG_BUFFER(DEBUG, NET_TLS_TAG, data, dataLen);
+
     peer->recBuf.buff = data;
     peer->recBuf.len = dataLen;
     peer->recBuf.loaded = 0;
@@ -1256,10 +1394,18 @@ CAResult_t CAdecryptTls(const CASecureEndpoint_t *sep, uint8_t *data, uint32_t d
         {
             break;
         }
-        TLS_CHECK_HANDSHAKE_FAIL(peer, ret, "Handshake error", 1, CA_STATUS_FAILED);
+        uint32_t flags = mbedtls_ssl_get_verify_result(&peer->ssl);
+        if (0 != flags)
+        {
+            OIC_LOG_BUFFER(ERROR, NET_TLS_TAG, &flags, sizeof(flags));
+            TLS_CHECK_HANDSHAKE_FAIL(peer, flags, "Cert verification failed", 1,
+                                                     CA_STATUS_FAILED, getAlertCode(flags));
+        }
+        TLS_CHECK_HANDSHAKE_FAIL(peer, ret, "Handshake error", 1, CA_STATUS_FAILED, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE);
         if (MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC == peer->ssl.state)
         {
             memcpy(peer->master, peer->ssl.session_negotiate->master, sizeof(peer->master));
+            g_caTlsContext->selectedCipher = peer->ssl.session_negotiate->ciphersuite;
         }
 
         if (MBEDTLS_SSL_HANDSHAKE_OVER == peer->ssl.state)
@@ -1275,29 +1421,26 @@ CAResult_t CAdecryptTls(const CASecureEndpoint_t *sep, uint8_t *data, uint32_t d
             }
             else
             {
-                if (ADAPTER_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 == g_caTlsContext->cipher)
+                if (MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 == g_caTlsContext->selectedCipher)
                 {
                     char uuid[UUID_LENGTH * 2 + 5] = {0};
                     void * uuidPos = NULL;
                     void * userIdPos = NULL;
                     const mbedtls_x509_crt * peerCert = mbedtls_ssl_get_peer_cert(&peer->ssl);
                     ret = (NULL == peerCert ? -1 : 0);
-                    TLS_CHECK_HANDSHAKE_FAIL(peer, ret, "Failed to retrieve subject",
-                                                                               1, CA_STATUS_FAILED);
-                    ret = mbedtls_ssl_get_verify_result(&peer->ssl);
-                    TLS_CHECK_HANDSHAKE_FAIL(peer, ret, "Failed to retrieve subject",
-                                                                               1, CA_STATUS_FAILED);
+                    TLS_CHECK_HANDSHAKE_FAIL(peer, ret, "Failed to retrieve cert", 1,
+                                                CA_STATUS_FAILED, MBEDTLS_SSL_ALERT_MSG_NO_CERT);
                     uuidPos = memmem((void *) peerCert->subject_raw.p, peerCert->subject_raw.len,
                                                      (void *) UUID_PREFIX, sizeof(UUID_PREFIX) - 1);
 
                     ret = (NULL == uuidPos ? -1 : 0);
-                    TLS_CHECK_HANDSHAKE_FAIL(peer, ret, "Failed to retrieve subject",
-                                                                               1, CA_STATUS_FAILED);
+                    TLS_CHECK_HANDSHAKE_FAIL(peer, ret, "Failed to retrieve subject", 1,
+                                        CA_STATUS_FAILED, MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT);
 
                     memcpy(uuid, uuidPos + sizeof(UUID_PREFIX) - 1, UUID_LENGTH * 2 + 4);
                     ret = ConvertStrToUuid(uuid, &peer->sep.identity);
-                    TLS_CHECK_HANDSHAKE_FAIL(peer, ret, "Failed to convert subject",
-                                                                               1, CA_STATUS_FAILED);
+                    TLS_CHECK_HANDSHAKE_FAIL(peer, ret, "Failed to convert subject", 1,
+                                        CA_STATUS_FAILED, MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT);
 
                     userIdPos = memmem((void *) peerCert->subject_raw.p, peerCert->subject_raw.len,
                                                  (void *) USERID_PREFIX, sizeof(USERID_PREFIX) - 1);
@@ -1305,16 +1448,16 @@ CAResult_t CAdecryptTls(const CASecureEndpoint_t *sep, uint8_t *data, uint32_t d
                     {
                         memcpy(uuid, userIdPos + sizeof(USERID_PREFIX) - 1, UUID_LENGTH * 2 + 4);
                         ret = ConvertStrToUuid(uuid, &peer->sep.userId);
-                        TLS_CHECK_HANDSHAKE_FAIL(peer, ret,
-                                 "Failed to convert subject alternative name", 1, CA_STATUS_FAILED);
+                        TLS_CHECK_HANDSHAKE_FAIL(peer, ret, "Failed to convert subject alt name", 1,
+                                          CA_STATUS_FAILED, MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT);
                     }
                     else
                     {
-                        OIC_LOG(DEBUG, NET_TLS_TAG, "Subject alternative name not found");
+                        OIC_LOG(WARNING, NET_TLS_TAG, "Subject alternative name not found");
                     }
                 }
             }
-            ca_mutex_unlock(g_tlsContextMutex);
+            oc_mutex_unlock(g_tlsContextMutex);
             OIC_LOG_V(DEBUG, NET_TLS_TAG, "Out %s", __func__);
             return CA_STATUS_OK;
         }
@@ -1331,7 +1474,7 @@ CAResult_t CAdecryptTls(const CASecureEndpoint_t *sep, uint8_t *data, uint32_t d
         {
             OIC_LOG(INFO, NET_TLS_TAG, "Connection was closed gracefully");
             removePeerFromList(&peer->sep.endpoint);
-            ca_mutex_unlock(g_tlsContextMutex);
+            oc_mutex_unlock(g_tlsContextMutex);
             return CA_STATUS_OK;
         }
 
@@ -1344,14 +1487,14 @@ CAResult_t CAdecryptTls(const CASecureEndpoint_t *sep, uint8_t *data, uint32_t d
                 g_tlsHandshakeCallback(&peer->sep.endpoint, &errorInfo);
             }
             removePeerFromList(&peer->sep.endpoint);
-            ca_mutex_unlock(g_tlsContextMutex);
+            oc_mutex_unlock(g_tlsContextMutex);
             return CA_STATUS_FAILED;
         }
 
         g_caTlsContext->adapterCallbacks[0].recvCallback(&peer->sep, decryptBuffer, ret);
     }
 
-    ca_mutex_unlock(g_tlsContextMutex);
+    oc_mutex_unlock(g_tlsContextMutex);
     OIC_LOG_V(DEBUG, NET_TLS_TAG, "Out %s", __func__);
     return CA_STATUS_OK;
 }
@@ -1363,11 +1506,11 @@ void CAsetTlsAdapterCallbacks(CAPacketReceivedCallback recvCallback,
     OIC_LOG_V(DEBUG, NET_TLS_TAG, "In %s", __func__);
     VERIFY_NON_NULL_VOID(sendCallback, NET_TLS_TAG, "sendCallback is NULL");
     VERIFY_NON_NULL_VOID(recvCallback, NET_TLS_TAG, "recvCallback is NULL");
-    ca_mutex_lock(g_tlsContextMutex);
+    oc_mutex_lock(g_tlsContextMutex);
     if (NULL == g_caTlsContext)
     {
         OIC_LOG(ERROR, NET_TLS_TAG, "Context is NULL");
-        ca_mutex_unlock(g_tlsContextMutex);
+        oc_mutex_unlock(g_tlsContextMutex);
         return;
     }
 
@@ -1378,17 +1521,20 @@ void CAsetTlsAdapterCallbacks(CAPacketReceivedCallback recvCallback,
         g_caTlsContext->adapterCallbacks[0].sendCallback = sendCallback;
     }
 
-    ca_mutex_unlock(g_tlsContextMutex);
+    oc_mutex_unlock(g_tlsContextMutex);
     OIC_LOG_V(DEBUG, NET_TLS_TAG, "Out %s", __func__);
 }
 
 CAResult_t CAsetTlsCipherSuite(const uint32_t cipher)
 {
     OIC_LOG_V(DEBUG, NET_TLS_TAG, "In %s", __func__);
+    VERIFY_NON_NULL_RET(g_getCredentialTypesCallback, NET_TLS_TAG, "Param callback is null", CA_STATUS_FAILED);
+    g_getCredentialTypesCallback(g_caTlsContext->cipherFlag);
     switch(cipher)
     {
         case MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA:
         {
+            //todo check that Cred with RSA cert exists
             mbedtls_ssl_conf_ciphersuites(&g_caTlsContext->clientConf,
                                          tlsCipher[ADAPTER_TLS_RSA_WITH_AES_256_CBC_SHA]);
             mbedtls_ssl_conf_ciphersuites(&g_caTlsContext->serverConf,
@@ -1398,6 +1544,11 @@ CAResult_t CAsetTlsCipherSuite(const uint32_t cipher)
         }
         case MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8:
         {
+            if (false == g_caTlsContext->cipherFlag[1])
+            {
+                OIC_LOG(ERROR, NET_TLS_TAG, "No Credential for ECC");
+                return CA_STATUS_FAILED;
+            }
             mbedtls_ssl_conf_ciphersuites(&g_caTlsContext->clientConf,
                                          tlsCipher[ADAPTER_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8]);
             mbedtls_ssl_conf_ciphersuites(&g_caTlsContext->serverConf,
@@ -1416,6 +1567,13 @@ CAResult_t CAsetTlsCipherSuite(const uint32_t cipher)
         }
         case MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256:
         {
+#if 0 // PIN OTM
+            if (false == g_caTlsContext->cipherFlag[0])
+            {
+                OIC_LOG(ERROR, NET_TLS_TAG, "No Credential for PSK");
+                return CA_STATUS_FAILED;
+            }
+#endif
             mbedtls_ssl_conf_ciphersuites(&g_caTlsContext->clientConf,
                                           tlsCipher[ADAPTER_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256]);
             mbedtls_ssl_conf_ciphersuites(&g_caTlsContext->serverConf,
@@ -1439,13 +1597,13 @@ CAResult_t CAinitiateTlsHandshake(const CAEndpoint_t *endpoint)
     CAResult_t res = CA_STATUS_OK;
     OIC_LOG_V(DEBUG, NET_TLS_TAG, "In %s", __func__);
     VERIFY_NON_NULL_RET(endpoint, NET_TLS_TAG, "Param endpoint is NULL" , CA_STATUS_INVALID_PARAM);
-    ca_mutex_lock(g_tlsContextMutex);
+    oc_mutex_lock(g_tlsContextMutex);
     if (NULL == initiateTlsHandshake(endpoint))
     {
         OIC_LOG(ERROR, NET_TLS_TAG, "TLS handshake failed");
         res = CA_STATUS_FAILED;
     }
-    ca_mutex_unlock(g_tlsContextMutex);
+    oc_mutex_unlock(g_tlsContextMutex);
     OIC_LOG_V(DEBUG, NET_TLS_TAG, "Out %s", __func__);
     return res;
 }
@@ -1459,11 +1617,11 @@ CAResult_t CAtlsGenerateOwnerPSK(const CAEndpoint_t *endpoint,
     VERIFY_NON_NULL_RET(ownerPSK, NET_TLS_TAG, "ownerPSK is NULL", CA_STATUS_INVALID_PARAM);
     VERIFY_NON_NULL_RET(deviceID, NET_TLS_TAG, "rsrcID is NULL", CA_STATUS_INVALID_PARAM);
 
-    ca_mutex_lock(g_tlsContextMutex);
+    oc_mutex_lock(g_tlsContextMutex);
     if (NULL == g_caTlsContext)
     {
         OIC_LOG(ERROR, NET_TLS_TAG, "Context is NULL");
-        ca_mutex_unlock(g_tlsContextMutex);
+        oc_mutex_unlock(g_tlsContextMutex);
         OIC_LOG_V(DEBUG, NET_TLS_TAG, "Out %s", __func__);
         return CA_STATUS_FAILED;
     }
@@ -1471,7 +1629,7 @@ CAResult_t CAtlsGenerateOwnerPSK(const CAEndpoint_t *endpoint,
     if (NULL == tep)
     {
         OIC_LOG(ERROR, NET_TLS_TAG, "Session does not exist");
-        ca_mutex_unlock(g_tlsContextMutex);
+        oc_mutex_unlock(g_tlsContextMutex);
         return CA_STATUS_FAILED;
     }
 
@@ -1481,13 +1639,13 @@ CAResult_t CAtlsGenerateOwnerPSK(const CAEndpoint_t *endpoint,
                                        MBEDTLS_MD_SHA1, MBEDTLS_PKCS12_DERIVE_KEY, 1))
     {
         OIC_LOG(ERROR, NET_TLS_TAG, "Failed to generate key");
-        ca_mutex_unlock(g_tlsContextMutex);
+        oc_mutex_unlock(g_tlsContextMutex);
         OIC_LOG_V(DEBUG, NET_TLS_TAG, "Out %s", __func__);
         return CA_STATUS_FAILED;
     }
     OIC_LOG_V(DEBUG, NET_TLS_TAG, "PSK: ");
     OIC_LOG_BUFFER(DEBUG, NET_TLS_TAG, tep->master, sizeof(tep->master));
-    ca_mutex_unlock(g_tlsContextMutex);
+    oc_mutex_unlock(g_tlsContextMutex);
 
     OIC_LOG_V(DEBUG, NET_TLS_TAG, "Out %s", __func__);
     return CA_STATUS_OK;
index f960fab..1a2070c 100644 (file)
@@ -17,7 +17,7 @@
  * limitations under the License.
  *
  ******************************************************************/
-#include "platform_features.h"
+#include "iotivity_config.h"
 #include "caadapternetdtls.h"
 #include "cacommon.h"
 #include "caipinterface.h"
@@ -69,7 +69,7 @@ static stCADtlsContext_t *g_caDtlsContext = NULL;
  * @var g_dtlsContextMutex
  * @brief Mutex to synchronize access to g_caDtlsContext.
  */
-static ca_mutex g_dtlsContextMutex = NULL;
+static oc_mutex g_dtlsContextMutex = NULL;
 
 /**
  * @var g_getCredentialsCallback
@@ -628,11 +628,11 @@ void CADTLSSetAdapterCallbacks(CAPacketReceivedCallback recvCallback,
                                CATransportAdapter_t type)
 {
     OIC_LOG(DEBUG, NET_DTLS_TAG, "IN");
-    ca_mutex_lock(g_dtlsContextMutex);
+    oc_mutex_lock(g_dtlsContextMutex);
     if (NULL == g_caDtlsContext)
     {
         OIC_LOG(ERROR, NET_DTLS_TAG, "Context is NULL");
-        ca_mutex_unlock(g_dtlsContextMutex);
+        oc_mutex_unlock(g_dtlsContextMutex);
         return;
     }
 
@@ -643,7 +643,7 @@ void CADTLSSetAdapterCallbacks(CAPacketReceivedCallback recvCallback,
         g_caDtlsContext->adapterCallbacks[0].sendCallback = sendCallback;
     }
 
-    ca_mutex_unlock(g_dtlsContextMutex);
+    oc_mutex_unlock(g_dtlsContextMutex);
 
     OIC_LOG(DEBUG, NET_DTLS_TAG, "OUT");
 }
@@ -683,15 +683,15 @@ CAResult_t CADtlsSelectCipherSuite(const dtls_cipher_t cipher)
 {
     OIC_LOG(DEBUG, NET_DTLS_TAG, "IN CADtlsSelectCipherSuite");
 
-    ca_mutex_lock(g_dtlsContextMutex);
+    oc_mutex_lock(g_dtlsContextMutex);
     if (NULL == g_caDtlsContext)
     {
         OIC_LOG(ERROR, NET_DTLS_TAG, "Context is NULL");
-        ca_mutex_unlock(g_dtlsContextMutex);
+        oc_mutex_unlock(g_dtlsContextMutex);
         return CA_STATUS_FAILED;
     }
     dtls_select_cipher(g_caDtlsContext->dtlsContext, cipher);
-    ca_mutex_unlock(g_dtlsContextMutex);
+    oc_mutex_unlock(g_dtlsContextMutex);
 
     OIC_LOG_V(DEBUG, NET_DTLS_TAG, "Selected cipher suite is 0x%02X%02X\n",
         ((uint8_t*)(&cipher))[1], ((uint8_t*)(&cipher))[0]);
@@ -704,16 +704,16 @@ CAResult_t CADtlsEnableAnonECDHCipherSuite(const bool enable)
 {
     OIC_LOG(DEBUG, NET_DTLS_TAG, "IN CADtlsEnablesAnonEcdh");
 
-    ca_mutex_lock(g_dtlsContextMutex);
+    oc_mutex_lock(g_dtlsContextMutex);
     if (NULL == g_caDtlsContext)
     {
         OIC_LOG(ERROR, NET_DTLS_TAG, "Context is NULL");
-        ca_mutex_unlock(g_dtlsContextMutex);
+        oc_mutex_unlock(g_dtlsContextMutex);
         return CA_STATUS_FAILED;
     }
     dtls_enables_anon_ecdh(g_caDtlsContext->dtlsContext,
         enable == true ? DTLS_CIPHER_ENABLE : DTLS_CIPHER_DISABLE);
-    ca_mutex_unlock(g_dtlsContextMutex);
+    oc_mutex_unlock(g_dtlsContextMutex);
     OIC_LOG_V(DEBUG, NET_DTLS_TAG, "TLS_ECDH_anon_WITH_AES_128_CBC_SHA_256  is %s",
         enable ? "enabled" : "disabled");
 
@@ -737,22 +737,22 @@ CAResult_t CADtlsInitiateHandshake(const CAEndpoint_t *endpoint)
     dst.ifIndex = 0;
     dst.size = CASizeOfAddrInfo(&dst);
 
-    ca_mutex_lock(g_dtlsContextMutex);
+    oc_mutex_lock(g_dtlsContextMutex);
     if(NULL == g_caDtlsContext)
     {
         OIC_LOG(ERROR, NET_DTLS_TAG, "Context is NULL");
-        ca_mutex_unlock(g_dtlsContextMutex);
+        oc_mutex_unlock(g_dtlsContextMutex);
         return CA_STATUS_FAILED;
     }
 
     if(0 > dtls_connect(g_caDtlsContext->dtlsContext, (session_t*)(&dst)))
     {
         OIC_LOG(ERROR, NET_DTLS_TAG, "Failed to connect");
-        ca_mutex_unlock(g_dtlsContextMutex);
+        oc_mutex_unlock(g_dtlsContextMutex);
         return CA_STATUS_FAILED;
     }
 
-    ca_mutex_unlock(g_dtlsContextMutex);
+    oc_mutex_unlock(g_dtlsContextMutex);
 
     OIC_LOG(DEBUG, NET_DTLS_TAG, "OUT CADtlsInitiateHandshake");
 
@@ -774,22 +774,22 @@ CAResult_t CADtlsClose(const CAEndpoint_t *endpoint)
     dst.ifIndex = 0;
     dst.size = CASizeOfAddrInfo(&dst);
 
-    ca_mutex_lock(g_dtlsContextMutex);
+    oc_mutex_lock(g_dtlsContextMutex);
     if (NULL == g_caDtlsContext)
     {
         OIC_LOG(ERROR, NET_DTLS_TAG, "Context is NULL");
-        ca_mutex_unlock(g_dtlsContextMutex);
+        oc_mutex_unlock(g_dtlsContextMutex);
         return CA_STATUS_FAILED;
     }
 
     if (0 > dtls_close(g_caDtlsContext->dtlsContext, (session_t*)(&dst)))
     {
         OIC_LOG(ERROR, NET_DTLS_TAG, "Failed to close the session");
-        ca_mutex_unlock(g_dtlsContextMutex);
+        oc_mutex_unlock(g_dtlsContextMutex);
         return CA_STATUS_FAILED;
     }
 
-    ca_mutex_unlock(g_dtlsContextMutex);
+    oc_mutex_unlock(g_dtlsContextMutex);
 
     OIC_LOG(DEBUG, NET_DTLS_TAG, "OUT CADtlsDisconnect");
 
@@ -815,11 +815,11 @@ CAResult_t CADtlsGenerateOwnerPSK(const CAEndpoint_t *endpoint,
     dst.ifIndex = 0;
     dst.size = CASizeOfAddrInfo(&dst);
 
-    ca_mutex_lock(g_dtlsContextMutex);
+    oc_mutex_lock(g_dtlsContextMutex);
     if (NULL == g_caDtlsContext)
     {
         OIC_LOG(ERROR, NET_DTLS_TAG, "Context is NULL");
-        ca_mutex_unlock(g_dtlsContextMutex);
+        oc_mutex_unlock(g_dtlsContextMutex);
         return CA_STATUS_FAILED;
     }
 
@@ -828,10 +828,10 @@ CAResult_t CADtlsGenerateOwnerPSK(const CAEndpoint_t *endpoint,
                  provServerDeviceID, provServerDeviceIDLen, ownerPSK, ownerPSKSize))
     {
         OIC_LOG(ERROR, NET_DTLS_TAG, "Failed to DTLS PRF");
-        ca_mutex_unlock(g_dtlsContextMutex);
+        oc_mutex_unlock(g_dtlsContextMutex);
         return CA_STATUS_FAILED;
     }
-    ca_mutex_unlock(g_dtlsContextMutex);
+    oc_mutex_unlock(g_dtlsContextMutex);
 
     OIC_LOG(DEBUG, NET_DTLS_TAG, "OUT CADtlsGenerateOwnerPSK");
 
@@ -1031,17 +1031,17 @@ static void CAStartRetransmit()
         //clear previous timer
         unregisterTimer(timerId);
 
-        ca_mutex_lock(g_dtlsContextMutex);
+        oc_mutex_lock(g_dtlsContextMutex);
 
         //stop retransmission if context is invalid
         if(NULL == g_caDtlsContext)
         {
             OIC_LOG(ERROR, NET_DTLS_TAG, "Context is NULL. Stop retransmission");
-            ca_mutex_unlock(g_dtlsContextMutex);
+            oc_mutex_unlock(g_dtlsContextMutex);
             return;
         }
         dtls_check_retransmit(g_caDtlsContext->dtlsContext, NULL);
-        ca_mutex_unlock(g_dtlsContextMutex);
+        oc_mutex_unlock(g_dtlsContextMutex);
     }
     //start new timer
     registerTimer(RETRANSMISSION_TIME, &timerId, CAStartRetransmit);
@@ -1054,7 +1054,7 @@ CAResult_t CAAdapterNetDtlsInit()
     // Initialize mutex for DtlsContext
     if (NULL == g_dtlsContextMutex)
     {
-        g_dtlsContextMutex = ca_mutex_new();
+        g_dtlsContextMutex = oc_mutex_new();
         VERIFY_NON_NULL_RET(g_dtlsContextMutex, NET_DTLS_TAG, "malloc failed",
             CA_MEMORY_ALLOC_FAILED);
     }
@@ -1065,14 +1065,14 @@ CAResult_t CAAdapterNetDtlsInit()
     }
 
     // Lock DtlsContext mutex and create DtlsContext
-    ca_mutex_lock(g_dtlsContextMutex);
+    oc_mutex_lock(g_dtlsContextMutex);
     g_caDtlsContext = (stCADtlsContext_t *)OICCalloc(1, sizeof(stCADtlsContext_t));
 
     if (NULL == g_caDtlsContext)
     {
         OIC_LOG(ERROR, NET_DTLS_TAG, "Context malloc failed");
-        ca_mutex_unlock(g_dtlsContextMutex);
-        ca_mutex_free(g_dtlsContextMutex);
+        oc_mutex_unlock(g_dtlsContextMutex);
+        oc_mutex_free(g_dtlsContextMutex);
         return CA_MEMORY_ALLOC_FAILED;
     }
 
@@ -1089,8 +1089,8 @@ CAResult_t CAAdapterNetDtlsInit()
         CAFreePeerInfoList();
         OICFree(g_caDtlsContext);
         g_caDtlsContext = NULL;
-        ca_mutex_unlock(g_dtlsContextMutex);
-        ca_mutex_free(g_dtlsContextMutex);
+        oc_mutex_unlock(g_dtlsContextMutex);
+        oc_mutex_free(g_dtlsContextMutex);
         return CA_STATUS_FAILED;
     }
 
@@ -1103,7 +1103,7 @@ CAResult_t CAAdapterNetDtlsInit()
     if (NULL ==  g_caDtlsContext->dtlsContext)
     {
         OIC_LOG(ERROR, NET_DTLS_TAG, "dtls_new_context failed");
-        ca_mutex_unlock(g_dtlsContextMutex);
+        oc_mutex_unlock(g_dtlsContextMutex);
         CAAdapterNetDtlsDeInit();
         return CA_STATUS_FAILED;
     }
@@ -1120,7 +1120,7 @@ CAResult_t CAAdapterNetDtlsInit()
     g_caDtlsContext->callbacks.is_x509_active = CAIsX509Active;
 #endif //__WITH_X509__*
     dtls_set_handler(g_caDtlsContext->dtlsContext, &(g_caDtlsContext->callbacks));
-    ca_mutex_unlock(g_dtlsContextMutex);
+    oc_mutex_unlock(g_dtlsContextMutex);
 
     CAStartRetransmit();
 
@@ -1136,7 +1136,7 @@ void CAAdapterNetDtlsDeInit()
     VERIFY_NON_NULL_VOID(g_dtlsContextMutex, NET_DTLS_TAG, "context mutex is NULL");
 
     //Lock DtlsContext mutex
-    ca_mutex_lock(g_dtlsContextMutex);
+    oc_mutex_lock(g_dtlsContextMutex);
 
     // Clear all lists
     CAFreePeerInfoList();
@@ -1151,8 +1151,8 @@ void CAAdapterNetDtlsDeInit()
     g_caDtlsContext = NULL;
 
     // Unlock DtlsContext mutex and de-initialize it
-    ca_mutex_unlock(g_dtlsContextMutex);
-    ca_mutex_free(g_dtlsContextMutex);
+    oc_mutex_unlock(g_dtlsContextMutex);
+    oc_mutex_free(g_dtlsContextMutex);
     g_dtlsContextMutex = NULL;
 
     OIC_LOG(DEBUG, NET_DTLS_TAG, "OUT");
@@ -1183,11 +1183,11 @@ CAResult_t CAAdapterNetDtlsEncrypt(const CAEndpoint_t *endpoint,
     addrInfo.ifIndex = 0;
     addrInfo.size = CASizeOfAddrInfo(&addrInfo);
 
-    ca_mutex_lock(g_dtlsContextMutex);
+    oc_mutex_lock(g_dtlsContextMutex);
     if(NULL == g_caDtlsContext)
     {
         OIC_LOG(ERROR, NET_DTLS_TAG, "Context is NULL");
-        ca_mutex_unlock(g_dtlsContextMutex);
+        oc_mutex_unlock(g_dtlsContextMutex);
         return CA_STATUS_FAILED;
     }
 
@@ -1198,7 +1198,7 @@ CAResult_t CAAdapterNetDtlsEncrypt(const CAEndpoint_t *endpoint,
         if (NULL == message)
         {
             OIC_LOG(ERROR, NET_DTLS_TAG, "calloc failed!");
-            ca_mutex_unlock(g_dtlsContextMutex);
+            oc_mutex_unlock(g_dtlsContextMutex);
             return CA_MEMORY_ALLOC_FAILED;
         }
 
@@ -1207,7 +1207,7 @@ CAResult_t CAAdapterNetDtlsEncrypt(const CAEndpoint_t *endpoint,
         {
             OIC_LOG(ERROR, NET_DTLS_TAG, "calloc failed!");
             OICFree(message);
-            ca_mutex_unlock(g_dtlsContextMutex);
+            oc_mutex_unlock(g_dtlsContextMutex);
             return CA_MEMORY_ALLOC_FAILED;
         }
         memcpy(message->data, data, dataLen);
@@ -1221,11 +1221,11 @@ CAResult_t CAAdapterNetDtlsEncrypt(const CAEndpoint_t *endpoint,
             CAFreeCacheMsg(message);
         }
         OIC_LOG_V(DEBUG, NET_DTLS_TAG, "OUT Initiating Dtls session [%d]", result);
-        ca_mutex_unlock(g_dtlsContextMutex);
+        oc_mutex_unlock(g_dtlsContextMutex);
         return result;
     }
 
-    ca_mutex_unlock(g_dtlsContextMutex);
+    oc_mutex_unlock(g_dtlsContextMutex);
 
     if (ret != DTLS_OK)
     {
@@ -1249,16 +1249,16 @@ CAResult_t CAAdapterNetDtlsDecrypt(const CASecureEndpoint_t *sep,
     addrInfo.ifIndex = 0;
     addrInfo.size = CASizeOfAddrInfo(&addrInfo);
 
-    ca_mutex_lock(g_dtlsContextMutex);
+    oc_mutex_lock(g_dtlsContextMutex);
     if (NULL == g_caDtlsContext)
     {
         OIC_LOG(ERROR, NET_DTLS_TAG, "Context is NULL");
-        ca_mutex_unlock(g_dtlsContextMutex);
+        oc_mutex_unlock(g_dtlsContextMutex);
         return CA_STATUS_FAILED;
     }
 
     eDtlsRet_t ret = CAAdapterNetDtlsDecryptInternal(&addrInfo, data, dataLen);
-    ca_mutex_unlock(g_dtlsContextMutex);
+    oc_mutex_unlock(g_dtlsContextMutex);
 
     if (DTLS_OK == ret || DTLS_HS_MSG == ret)
     {
index 888885b..8355886 100644 (file)
@@ -18,6 +18,7 @@
  *
  ******************************************************************/
 
+#include "iotivity_config.h"
 #include "caadapterutils.h"
 
 #include <string.h>
index 64af936..dc51dd4 100644 (file)
@@ -56,12 +56,12 @@ static void CASetBits(uint8_t *x, unsigned p, unsigned n, unsigned v)
         OIC_LOG(ERROR, TAG, "set bits - lower err");
         return;
     }
-    else if(~(unsigned)(~0<<n) < v)
+    else if(~(unsigned)(~0u<<n) < v)
     {
         OIC_LOG(ERROR, TAG, "set bits - upper err");
         return;
     }
-    *x = (*x & (~(~0 << (p-n+1)))) | (*x & (~0 << (p+1))) | ((v & ~(~0 << n)) << (p-n+1));
+    *x = (*x & (~(~0u << (p-n+1)))) | (*x & (~0u << (p+1))) | ((v & ~(~0u << n)) << (p-n+1));
 }
 
 /**
@@ -76,7 +76,7 @@ static void CASetBits(uint8_t *x, unsigned p, unsigned n, unsigned v)
  */
 static uint8_t CAGetBits(uint8_t x, unsigned p, unsigned n)
 {
-    return (x >> (p + 1 - n)) & ~(~0 << n);
+    return (x >> (p + 1 - n)) & ~(~0u << n);
 }
 
 CAResult_t CAGenerateVariableForFragmentation(size_t dataLength,
@@ -127,8 +127,7 @@ CAResult_t CAGenerateHeader(uint8_t *header,
 
     if (sourcePort > CA_SUPPORTED_BLE_MAX_PORT ||
         sourcePort < CA_SUPPORTED_BLE_MIN_PORT ||
-        destPort > CA_SUPPORTED_BLE_MAX_PORT ||
-        destPort < CA_BLE_MULTICAST_PORT)
+        destPort > CA_SUPPORTED_BLE_MAX_PORT)
     {
         OIC_LOG_V(ERROR, TAG, "source port(%d) or destination port(%d) is invalid number!!",
                 sourcePort, destPort);
@@ -196,10 +195,10 @@ CAResult_t CAMakeRemainDataSegment(uint8_t *dataSegment,
     VERIFY_NON_NULL(dataSegment, TAG, "dataSegment is NULL");
     VERIFY_NON_NULL(dataHeader, TAG, "dataHeader is NULL");
 
-    uint8_t *cur_pos = data +
+    const uint8_t *cur_pos = data +
         (CA_SUPPORTED_BLE_MTU_SIZE - CA_BLE_HEADER_SIZE - CA_BLE_LENGTH_HEADER_SIZE +
          (index * (CA_SUPPORTED_BLE_MTU_SIZE - CA_BLE_HEADER_SIZE)));
-    if (cur_pos == NULL)
+    if (NULL == cur_pos)
     {
         OIC_LOG(ERROR, TAG, "data is NULL");
         return CA_STATUS_FAILED;
index 6a674ae..cc7a58b 100644 (file)
@@ -29,7 +29,7 @@
 #include "oic_malloc.h"
 #include "oic_string.h"
 #include "cathreadpool.h" /* for thread pool */
-#include "camutex.h"
+#include "octhread.h"
 #include "uarraylist.h"
 #include "caadapterutils.h"
 #include "caremotehandler.h"
@@ -57,13 +57,13 @@ static jobject g_context;
  * @var g_mutexStateList
  * @brief Mutex to synchronize device state list
  */
-static ca_mutex g_mutexStateList = NULL;
+static oc_mutex g_mutexStateList = NULL;
 
 /**
  * @var g_mutexObjectList
  * @brief Mutex to synchronize device object list
  */
-static ca_mutex g_mutexObjectList = NULL;
+static oc_mutex g_mutexObjectList = NULL;
 
 /**
  * @var g_edrErrorHandler
@@ -71,27 +71,6 @@ static ca_mutex g_mutexObjectList = NULL;
  */
 static CAEDRErrorHandleCallback g_edrErrorHandler = NULL;
 
-typedef struct send_data
-{
-    char* address;
-    char* data;
-    uint32_t id;
-} data_t;
-
-/**
- @brief Thread context information for unicast, multicast and secured unicast server
- */
-typedef struct
-{
-    bool *stopFlag;
-    CAAdapterServerType_t type;
-} CAAdapterReceiveThreadContext_t;
-
-typedef struct
-{
-    bool *stopFlag;
-} CAAdapterAcceptThreadContext_t;
-
 /**
  * implement for BT-EDR adapter common method
  */
@@ -302,20 +281,20 @@ static void CAEDRDestroyMutex()
 {
     if (g_mutexStateList)
     {
-        ca_mutex_free(g_mutexStateList);
+        oc_mutex_free(g_mutexStateList);
         g_mutexStateList = NULL;
     }
 
     if (g_mutexObjectList)
     {
-        ca_mutex_free(g_mutexObjectList);
+        oc_mutex_free(g_mutexObjectList);
         g_mutexObjectList = NULL;
     }
 }
 
 static CAResult_t CAEDRCreateMutex()
 {
-    g_mutexStateList = ca_mutex_new();
+    g_mutexStateList = oc_mutex_new();
     if (!g_mutexStateList)
     {
         OIC_LOG(ERROR, TAG, "Failed to created mutex!");
@@ -324,7 +303,7 @@ static CAResult_t CAEDRCreateMutex()
         return CA_STATUS_FAILED;
     }
 
-    g_mutexObjectList = ca_mutex_new();
+    g_mutexObjectList = oc_mutex_new();
     if (!g_mutexObjectList)
     {
         OIC_LOG(ERROR, TAG, "Failed to created mutex!");
@@ -376,13 +355,13 @@ CAResult_t CAEDRInitialize()
     }
     (*env)->DeleteLocalRef(env, jni_address);
 
-    ca_mutex_lock(g_mutexStateList);
+    oc_mutex_lock(g_mutexStateList);
     CAEDRNativeCreateDeviceStateList();
-    ca_mutex_unlock(g_mutexStateList);
+    oc_mutex_unlock(g_mutexStateList);
 
-    ca_mutex_lock(g_mutexObjectList);
+    oc_mutex_lock(g_mutexObjectList);
     CAEDRNativeCreateDeviceSocketList();
-    ca_mutex_unlock(g_mutexObjectList);
+    oc_mutex_unlock(g_mutexObjectList);
 
     if (isAttached)
     {
@@ -1064,16 +1043,16 @@ CAResult_t CAEDRNativeConnect(JNIEnv *env, const char *address)
         (*env)->DeleteLocalRef(env, jni_obj_BTSocket);
         return CA_STATUS_FAILED;
     }
-    ca_mutex_lock(g_mutexObjectList);
+    oc_mutex_lock(g_mutexObjectList);
     CAEDRNativeAddDeviceSocketToList(env, jni_socket);
     (*env)->DeleteGlobalRef(env, jni_socket);
     (*env)->DeleteLocalRef(env, jni_obj_BTSocket);
-    ca_mutex_unlock(g_mutexObjectList);
+    oc_mutex_unlock(g_mutexObjectList);
 
     // update state
-    ca_mutex_lock(g_mutexStateList);
+    oc_mutex_lock(g_mutexStateList);
     CAEDRUpdateDeviceState(STATE_CONNECTED, address);
-    ca_mutex_unlock(g_mutexStateList);
+    oc_mutex_unlock(g_mutexStateList);
 
     OIC_LOG(DEBUG, TAG, "successfully connected");
 
@@ -1119,9 +1098,9 @@ void CAEDRNativeSocketClose(JNIEnv *env, const char *address)
     CAEDRNativeRemoveDeviceSocket(env, jni_obj_socket);
 
     // update state
-    ca_mutex_lock(g_mutexStateList);
+    oc_mutex_lock(g_mutexStateList);
     CAEDRUpdateDeviceState(STATE_DISCONNECTED, address);
-    ca_mutex_unlock(g_mutexStateList);
+    oc_mutex_unlock(g_mutexStateList);
 
     OIC_LOG_V(DEBUG, TAG, "disconnected with [%s]", address);
 }
index 425469e..c2e17e9 100644 (file)
@@ -27,7 +27,7 @@
 #include "logger.h"
 #include "oic_malloc.h"
 #include "cathreadpool.h" /* for thread pool */
-#include "camutex.h"
+#include "octhread.h"
 #include "uarraylist.h"
 #include "caadapterutils.h"
 #include "caedrserver.h"
index b1cf8a0..ff7c8e4 100644 (file)
@@ -28,7 +28,7 @@
 #include "logger.h"
 #include "oic_malloc.h"
 #include "cathreadpool.h" /* for thread pool */
-#include "camutex.h"
+#include "octhread.h"
 #include "uarraylist.h"
 #include "caadapterutils.h"
 #include "org_iotivity_ca_CaEdrInterface.h"
@@ -54,7 +54,7 @@ static JavaVM *g_jvm;
 /**
  * Mutex to synchronize receive server.
  */
-static ca_mutex g_mutexReceiveServer = NULL;
+static oc_mutex g_mutexReceiveServer = NULL;
 
 /**
  * Flag to control the Receive Unicast Data Thread.
@@ -64,7 +64,7 @@ static bool g_stopUnicast = false;
 /**
  * Mutex to synchronize accept server.
  */
-static ca_mutex g_mutexAcceptServer = NULL;
+static oc_mutex g_mutexAcceptServer = NULL;
 
 /**
  * Flag to control the Accept Thread.
@@ -74,7 +74,7 @@ static bool g_stopAccept = false;
 /**
  * Mutex to synchronize server socket.
  */
-static ca_mutex g_mutexServerSocket = NULL;
+static oc_mutex g_mutexServerSocket = NULL;
 
 /**
  * Flag to control the server socket.
@@ -84,12 +84,12 @@ static jobject g_serverSocket = NULL;
 /**
  * Mutex to synchronize device state list.
  */
-static ca_mutex g_mutexStateList = NULL;
+static oc_mutex g_mutexStateList = NULL;
 
 /**
  * Mutex to synchronize device object list.
  */
-static ca_mutex g_mutexObjectList = NULL;
+static oc_mutex g_mutexObjectList = NULL;
 
 /**
  * Thread context information for unicast, multicast and secured unicast server.
@@ -200,16 +200,16 @@ static void CAAcceptHandler(void *data)
         return;
     }
 
-    ca_mutex_lock(g_mutexServerSocket);
+    oc_mutex_lock(g_mutexServerSocket);
     g_serverSocket = (*env)->NewGlobalRef(env, jni_obj_BTServerSocket);
-    ca_mutex_unlock(g_mutexServerSocket);
+    oc_mutex_unlock(g_mutexServerSocket);
 
     CAAdapterAcceptThreadContext_t *ctx = (CAAdapterAcceptThreadContext_t *) data;
 
     // it should be initialized for restart accept thread
-    ca_mutex_lock(g_mutexAcceptServer);
+    oc_mutex_lock(g_mutexAcceptServer);
     g_stopAccept = false;
-    ca_mutex_unlock(g_mutexAcceptServer);
+    oc_mutex_unlock(g_mutexAcceptServer);
 
     while (true != *(ctx->stopFlag))
     {
@@ -217,12 +217,12 @@ static void CAAcceptHandler(void *data)
         if (!CAEDRNativeIsEnableBTAdapter(env))
         {
             OIC_LOG(INFO, TAG, "BT adapter is not enabled");
-            ca_mutex_lock(g_mutexAcceptServer);
+            oc_mutex_lock(g_mutexAcceptServer);
             g_stopAccept = true;
-            ca_mutex_unlock(g_mutexAcceptServer);
-            ca_mutex_lock(g_mutexServerSocket);
+            oc_mutex_unlock(g_mutexAcceptServer);
+            oc_mutex_lock(g_mutexServerSocket);
             g_serverSocket = NULL;
-            ca_mutex_unlock(g_mutexServerSocket);
+            oc_mutex_unlock(g_mutexServerSocket);
         }
         else
         {
@@ -271,9 +271,9 @@ CAResult_t CAEDRServerStop()
 {
     CAEDRStopReceiveThread();
 
-    ca_mutex_lock(g_mutexAcceptServer);
+    oc_mutex_lock(g_mutexAcceptServer);
     g_stopAccept = true;
-    ca_mutex_unlock(g_mutexAcceptServer);
+    oc_mutex_unlock(g_mutexAcceptServer);
 
     if (!g_jvm)
     {
@@ -316,45 +316,45 @@ static void CAEDRServerDestroyMutex()
 {
     if (g_mutexReceiveServer)
     {
-        ca_mutex_free(g_mutexReceiveServer);
+        oc_mutex_free(g_mutexReceiveServer);
         g_mutexReceiveServer = NULL;
     }
 
     if (g_mutexAcceptServer)
     {
-        ca_mutex_free(g_mutexAcceptServer);
+        oc_mutex_free(g_mutexAcceptServer);
         g_mutexAcceptServer = NULL;
     }
 
     if (g_mutexServerSocket)
     {
-        ca_mutex_free(g_mutexServerSocket);
+        oc_mutex_free(g_mutexServerSocket);
         g_mutexServerSocket = NULL;
     }
 
     if (g_mutexStateList)
     {
-        ca_mutex_free(g_mutexStateList);
+        oc_mutex_free(g_mutexStateList);
         g_mutexStateList = NULL;
     }
 
     if (g_mutexObjectList)
     {
-        ca_mutex_free(g_mutexObjectList);
+        oc_mutex_free(g_mutexObjectList);
         g_mutexObjectList = NULL;
     }
 }
 
 static CAResult_t CAEDRServerCreateMutex()
 {
-    g_mutexReceiveServer = ca_mutex_new();
+    g_mutexReceiveServer = oc_mutex_new();
     if (!g_mutexReceiveServer)
     {
         OIC_LOG(ERROR, TAG, "Failed to created mutex!");
         return CA_STATUS_FAILED;
     }
 
-    g_mutexAcceptServer = ca_mutex_new();
+    g_mutexAcceptServer = oc_mutex_new();
     if (!g_mutexAcceptServer)
     {
         OIC_LOG(ERROR, TAG, "Failed to created mutex!");
@@ -363,7 +363,7 @@ static CAResult_t CAEDRServerCreateMutex()
         return CA_STATUS_FAILED;
     }
 
-    g_mutexServerSocket = ca_mutex_new();
+    g_mutexServerSocket = oc_mutex_new();
     if (!g_mutexServerSocket)
     {
         OIC_LOG(ERROR, TAG, "Failed to created mutex!");
@@ -372,7 +372,7 @@ static CAResult_t CAEDRServerCreateMutex()
         return CA_STATUS_FAILED;
     }
 
-    g_mutexStateList = ca_mutex_new();
+    g_mutexStateList = oc_mutex_new();
     if (!g_mutexStateList)
     {
         OIC_LOG(ERROR, TAG, "Failed to created mutex!");
@@ -381,7 +381,7 @@ static CAResult_t CAEDRServerCreateMutex()
         return CA_STATUS_FAILED;
     }
 
-    g_mutexObjectList = ca_mutex_new();
+    g_mutexObjectList = oc_mutex_new();
     if (!g_mutexObjectList)
     {
         OIC_LOG(ERROR, TAG, "Failed to created mutex!");
@@ -436,13 +436,13 @@ CAResult_t CAEDRServerStartAcceptThread()
         (*env)->ReleaseStringUTFChars(env, jni_address, localAddress);
     }
 
-    ca_mutex_lock(g_mutexStateList);
+    oc_mutex_lock(g_mutexStateList);
     CAEDRNativeCreateDeviceStateList();
-    ca_mutex_unlock(g_mutexStateList);
+    oc_mutex_unlock(g_mutexStateList);
 
-    ca_mutex_lock(g_mutexObjectList);
+    oc_mutex_lock(g_mutexObjectList);
     CAEDRNativeCreateDeviceSocketList();
-    ca_mutex_unlock(g_mutexObjectList);
+    oc_mutex_unlock(g_mutexObjectList);
 
     if (isAttached)
     {
@@ -510,7 +510,7 @@ CAResult_t CAEDRStartReceiveThread(bool isSecured)
 {
     OIC_LOG(DEBUG, TAG, "CAEDRStartReceiveThread");
 
-    ca_mutex_lock(g_mutexReceiveServer);
+    oc_mutex_lock(g_mutexReceiveServer);
 
     /**
      * The task to listen for data from unicast is added to the thread pool.
@@ -524,7 +524,7 @@ CAResult_t CAEDRStartReceiveThread(bool isSecured)
     if (!ctx)
     {
         OIC_LOG(ERROR, TAG, "Out of memory!");
-        ca_mutex_unlock(g_mutexReceiveServer);
+        oc_mutex_unlock(g_mutexReceiveServer);
         return CA_MEMORY_ALLOC_FAILED;
     }
 
@@ -534,11 +534,11 @@ CAResult_t CAEDRStartReceiveThread(bool isSecured)
     if (CA_STATUS_OK != ca_thread_pool_add_task(g_threadPoolHandle, CAReceiveHandler, (void *) ctx))
     {
         OIC_LOG(ERROR, TAG, "Failed to create read thread!");
-        ca_mutex_unlock(g_mutexReceiveServer);
+        oc_mutex_unlock(g_mutexReceiveServer);
         OICFree((void *) ctx);
         return CA_STATUS_FAILED;
     }
-    ca_mutex_unlock(g_mutexReceiveServer);
+    oc_mutex_unlock(g_mutexReceiveServer);
 
     OIC_LOG(DEBUG, TAG, "OUT");
     return CA_STATUS_OK;
@@ -548,9 +548,9 @@ CAResult_t CAEDRStopReceiveThread()
 {
     OIC_LOG(DEBUG, TAG, "CAEDRStopReceiveThread");
 
-    ca_mutex_lock(g_mutexReceiveServer);
+    oc_mutex_lock(g_mutexReceiveServer);
     g_stopUnicast = true;
-    ca_mutex_unlock(g_mutexReceiveServer);
+    oc_mutex_unlock(g_mutexReceiveServer);
 
     return CA_STATUS_OK;
 }
@@ -687,7 +687,7 @@ CAResult_t CAEDRNativeReadData(JNIEnv *env, uint32_t idx)
 
         if (!deviceInfo->totalDataLen)
         {
-            coap_transport_type transport = coap_get_tcp_header_type_from_initbyte(
+            coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(
                     ((unsigned char *) deviceInfo->recvData)[0] >> 4);
             size_t headerLen = coap_get_tcp_header_length_for_transport(transport);
             if (deviceInfo->recvData && deviceInfo->recvDataLen >= headerLen)
@@ -718,9 +718,9 @@ CAResult_t CAEDRNativeReadData(JNIEnv *env, uint32_t idx)
 
                 // update state to disconnect
                 // the socket will be close next read thread routine
-                ca_mutex_lock(g_mutexStateList);
+                oc_mutex_lock(g_mutexStateList);
                 CAEDRUpdateDeviceState(STATE_DISCONNECTED, address);
-                ca_mutex_unlock(g_mutexStateList);
+                oc_mutex_unlock(g_mutexStateList);
 
                 (*env)->ReleaseStringUTFChars(env, jni_str_address, address);
                 (*env)->DeleteLocalRef(env, jni_str_address);
@@ -759,9 +759,9 @@ void CANativeStartListenTask(JNIEnv *env)
         return;
     }
 
-    ca_mutex_lock(g_mutexServerSocket);
+    oc_mutex_lock(g_mutexServerSocket);
     g_serverSocket = (*env)->NewGlobalRef(env, jni_obj_BTServerSocket);
-    ca_mutex_unlock(g_mutexServerSocket);
+    oc_mutex_unlock(g_mutexServerSocket);
 }
 
 jobject CAEDRNativeListen(JNIEnv *env)
@@ -904,9 +904,9 @@ void CAEDRNativeAccept(JNIEnv *env, jobject serverSocketObject)
         OIC_LOG_V(INFO, TAG, "accept a new connection from [%s]", address);
 
         // update state
-        ca_mutex_lock(g_mutexStateList);
+        oc_mutex_lock(g_mutexStateList);
         CAEDRUpdateDeviceState(STATE_CONNECTED, address);
-        ca_mutex_unlock(g_mutexStateList);
+        oc_mutex_unlock(g_mutexStateList);
 
         (*env)->ReleaseStringUTFChars(env, j_str_address, address);
         (*env)->DeleteLocalRef(env, j_str_address);
@@ -920,9 +920,9 @@ void CAEDRNativeAccept(JNIEnv *env, jobject serverSocketObject)
             return;
         }
 
-        ca_mutex_lock(g_mutexObjectList);
+        oc_mutex_lock(g_mutexObjectList);
         CAEDRNativeAddDeviceSocketToList(env, jni_socket);
-        ca_mutex_unlock(g_mutexObjectList);
+        oc_mutex_unlock(g_mutexObjectList);
 
         (*env)->DeleteGlobalRef(env, jni_socket);
         (*env)->DeleteLocalRef(env, jni_obj_BTSocket);
index c5a86d8..a905e2f 100644 (file)
@@ -32,7 +32,7 @@
 #include "caqueueingthread.h"
 #include "oic_malloc.h"
 #include "caremotehandler.h"
-#include "pdu.h"
+#include <coap/pdu.h>
 
 /**
  * Logging tag for module name.
@@ -352,15 +352,15 @@ CAResult_t CAStopEDR()
     // Stop RFComm server if it is running
     CAEDRServerStop();
 
-    // Stop network monitor
-    CAEDRStopNetworkMonitor();
-
     // Stop the adapter
     CAEDRClientUnsetCallbacks();
 
     // Disconnect all the client connections
     CAEDRClientDisconnectAll();
 
+    // Stop network monitor
+    CAEDRStopNetworkMonitor();
+
     // Stop Send and receive Queue
     CAAdapterStopQueue();
 
index e24e2ae..3e276bf 100644 (file)
@@ -30,7 +30,7 @@
 #include <bluetooth_internal.h>
 
 #include "caedrinterface.h"
-#include "camutex.h"
+#include "octhread.h"
 #include "caedrendpoint.h"
 #include "caadapterutils.h"
 #include "caedrutils.h"
@@ -49,7 +49,7 @@
 /**
  * Mutex to synchronize the access to Bluetooth device information list.
  */
-static ca_mutex g_edrDeviceListMutex = NULL;
+static oc_mutex g_edrDeviceListMutex = NULL;
 
 /**
  * Peer Bluetooth device information list.
@@ -75,7 +75,7 @@ static u_arraylist_t *g_multicastDataList = NULL;
 /**
  * Mutex to synchronize the access to Pending multicast data list.
  */
-static ca_mutex g_multicastDataListMutex = NULL;
+static oc_mutex g_multicastDataListMutex = NULL;
 
 /**
  * To Store Adapter Mode information
@@ -174,7 +174,7 @@ void CAEDRSocketConnectionStateCallback(int result, bt_socket_connection_state_e
     {
         case BT_SOCKET_CONNECTED:
             {
-                ca_mutex_lock(g_edrDeviceListMutex);
+                oc_mutex_lock(g_edrDeviceListMutex);
                 CAResult_t res = CAGetEDRDevice(g_edrDeviceList, connection->remote_address,
                                                    &device);
                 if (CA_STATUS_OK != res)
@@ -185,26 +185,26 @@ void CAEDRSocketConnectionStateCallback(int result, bt_socket_connection_state_e
                     if (CA_STATUS_OK != res)
                     {
                         OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Failed add device to list ret[%d]", res);
-                        ca_mutex_unlock(g_edrDeviceListMutex);
+                        oc_mutex_unlock(g_edrDeviceListMutex);
                         return;
                     }
 
                     if(!device)
                     {
                         OIC_LOG(ERROR, EDR_ADAPTER_TAG, "EDRDevice is null!");
-                        ca_mutex_unlock(g_edrDeviceListMutex);
+                        oc_mutex_unlock(g_edrDeviceListMutex);
                         return;
                     }
 
                     device->socketFD = connection->socket_fd;
-                    ca_mutex_unlock(g_edrDeviceListMutex);
+                    oc_mutex_unlock(g_edrDeviceListMutex);
                     return;
                 }
 
                 if(!device)
                 {
                     OIC_LOG(ERROR, EDR_ADAPTER_TAG, "EDRDevice is null!");
-                    ca_mutex_unlock(g_edrDeviceListMutex);
+                    oc_mutex_unlock(g_edrDeviceListMutex);
                     return;
                 }
                 device->socketFD = connection->socket_fd;
@@ -226,17 +226,20 @@ void CAEDRSocketConnectionStateCallback(int result, bt_socket_connection_state_e
                     // Remove the data which send from pending list
                     CARemoveEDRDataFromList(&device->pendingDataList);
                 }
-                ca_mutex_unlock(g_edrDeviceListMutex);
+                oc_mutex_unlock(g_edrDeviceListMutex);
             }
             break;
 
         case BT_SOCKET_DISCONNECTED:
             {
-                ca_mutex_lock(g_edrDeviceListMutex);
+                oc_mutex_lock(g_edrDeviceListMutex);
                 CARemoveEDRDeviceFromList(&g_edrDeviceList, connection->remote_address);
-                ca_mutex_unlock(g_edrDeviceListMutex);
+                oc_mutex_unlock(g_edrDeviceListMutex);
             }
             break;
+
+        default:
+            OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Unknown Bluetooth Socket connection state");
     }
 
     OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
@@ -268,10 +271,10 @@ void CAEDRDeviceDiscoveryCallback(int result, bt_adapter_device_discovery_state_
         case BT_ADAPTER_DEVICE_DISCOVERY_FINISHED:
             {
                 OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "Discovery finished!");
-                ca_mutex_lock(g_multicastDataListMutex);
+                oc_mutex_lock(g_multicastDataListMutex);
                 u_arraylist_destroy(g_multicastDataList);
                 g_multicastDataList = NULL;
-                ca_mutex_unlock(g_multicastDataListMutex);
+                oc_mutex_unlock(g_multicastDataListMutex);
             }
             break;
 
@@ -284,18 +287,18 @@ void CAEDRDeviceDiscoveryCallback(int result, bt_adapter_device_discovery_state_
                                                         OIC_EDR_SERVICE_ID))
                 {
                     // Check if the deivce is already in the list
-                    ca_mutex_lock(g_edrDeviceListMutex);
+                    oc_mutex_lock(g_edrDeviceListMutex);
                     if (CA_STATUS_OK == CAGetEDRDevice(g_edrDeviceList,
                                                 discoveryInfo->remote_address, &device))
                     {
                         if(!device)
                         {
                             OIC_LOG(ERROR, EDR_ADAPTER_TAG, "EDRDevice is null!");
-                            ca_mutex_unlock(g_edrDeviceListMutex);
+                            oc_mutex_unlock(g_edrDeviceListMutex);
                             return;
                         }
                         device->serviceSearched = true;
-                        ca_mutex_unlock(g_edrDeviceListMutex);
+                        oc_mutex_unlock(g_edrDeviceListMutex);
                         return;
                     }
 
@@ -305,14 +308,14 @@ void CAEDRDeviceDiscoveryCallback(int result, bt_adapter_device_discovery_state_
                     if (CA_STATUS_OK != res)
                     {
                         OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Failed to add device to list!");
-                        ca_mutex_unlock(g_edrDeviceListMutex);
+                        oc_mutex_unlock(g_edrDeviceListMutex);
                         return;
                     }
 
                     if(!device)
                     {
                         OIC_LOG(ERROR, EDR_ADAPTER_TAG, "EDRDevice is null!");
-                        ca_mutex_unlock(g_edrDeviceListMutex);
+                        oc_mutex_unlock(g_edrDeviceListMutex);
                         return;
                     }
 
@@ -349,7 +352,7 @@ void CAEDRDeviceDiscoveryCallback(int result, bt_adapter_device_discovery_state_
                         }
                     }
                     device->serviceSearched = true;
-                    ca_mutex_unlock(g_edrDeviceListMutex);
+                    oc_mutex_unlock(g_edrDeviceListMutex);
                 }
                 else
                 {
@@ -357,6 +360,9 @@ void CAEDRDeviceDiscoveryCallback(int result, bt_adapter_device_discovery_state_
                 }
             }
             break;
+
+        default:
+            OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Unknown Bluetooth Adapter device discovery state");
     }
 
     OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
@@ -373,7 +379,7 @@ void CAEDRServiceSearchedCallback(int32_t result,
         return;
     }
 
-    ca_mutex_lock(g_edrDeviceListMutex);
+    oc_mutex_lock(g_edrDeviceListMutex);
 
     EDRDevice *device = NULL;
     CAResult_t res = CAGetEDRDevice(g_edrDeviceList, sdpInfo->remote_address, &device);
@@ -382,7 +388,7 @@ void CAEDRServiceSearchedCallback(int32_t result,
         if (device->serviceSearched)
         {
             OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "Service is already searched for this device!");
-            ca_mutex_unlock(g_edrDeviceListMutex);
+            oc_mutex_unlock(g_edrDeviceListMutex);
             return;
         }
 
@@ -408,7 +414,7 @@ void CAEDRServiceSearchedCallback(int32_t result,
         }
     }
 
-    ca_mutex_unlock(g_edrDeviceListMutex);
+    oc_mutex_unlock(g_edrDeviceListMutex);
 
     OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
 }
@@ -559,12 +565,12 @@ CAResult_t CAEDRManagerInitializeMutex(void)
 
     if (!g_edrDeviceListMutex)
     {
-        g_edrDeviceListMutex = ca_mutex_new();
+        g_edrDeviceListMutex = oc_mutex_new();
     }
 
     if (!g_multicastDataListMutex)
     {
-        g_multicastDataListMutex = ca_mutex_new();
+        g_multicastDataListMutex = oc_mutex_new();
     }
 
     if (!g_edrDeviceListMutex || !g_multicastDataListMutex)
@@ -583,13 +589,13 @@ void CAEDRManagerTerminateMutex(void)
 
     if (g_edrDeviceListMutex)
     {
-        ca_mutex_free(g_edrDeviceListMutex);
+        oc_mutex_free(g_edrDeviceListMutex);
         g_edrDeviceListMutex = NULL;
     }
 
     if (g_multicastDataListMutex)
     {
-        ca_mutex_free(g_multicastDataListMutex);
+        oc_mutex_free(g_multicastDataListMutex);
         g_multicastDataListMutex = NULL;
     }
 
@@ -611,17 +617,17 @@ void CAEDRClientTerminate()
     // Free EDRDevices list
     if (g_edrDeviceListMutex)
     {
-        ca_mutex_lock(g_edrDeviceListMutex);
+        oc_mutex_lock(g_edrDeviceListMutex);
         CADestroyEDRDeviceList(&g_edrDeviceList);
-        ca_mutex_unlock(g_edrDeviceListMutex);
+        oc_mutex_unlock(g_edrDeviceListMutex);
     }
 
     if (g_multicastDataListMutex)
     {
-        ca_mutex_lock(g_multicastDataListMutex);
+        oc_mutex_lock(g_multicastDataListMutex);
         u_arraylist_destroy(g_multicastDataList);
         g_multicastDataList = NULL;
-        ca_mutex_unlock(g_multicastDataListMutex);
+        oc_mutex_unlock(g_multicastDataListMutex);
     }
 
     // Free the mutex
@@ -633,7 +639,7 @@ void CAEDRClientDisconnectAll(void)
 {
     OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
 
-    ca_mutex_lock(g_edrDeviceListMutex);
+    oc_mutex_lock(g_edrDeviceListMutex);
 
     EDRDeviceList *cur = g_edrDeviceList;
     while (cur != NULL)
@@ -654,7 +660,7 @@ void CAEDRClientDisconnectAll(void)
         }
     }
 
-    ca_mutex_unlock(g_edrDeviceListMutex);
+    oc_mutex_unlock(g_edrDeviceListMutex);
 
     OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
 }
@@ -679,7 +685,7 @@ CAResult_t CAEDRClientSendUnicastData(const char *remoteAddress,
     }
 
     // Check the connection existence with remote device
-    ca_mutex_lock(g_edrDeviceListMutex);
+    oc_mutex_lock(g_edrDeviceListMutex);
     CAResult_t result = CAGetEDRDevice(g_edrDeviceList, remoteAddress, &device);
     if (CA_STATUS_OK != result)
     {
@@ -690,7 +696,7 @@ CAResult_t CAEDRClientSendUnicastData(const char *remoteAddress,
         {
             OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Failed create device and add to list!");
 
-            ca_mutex_unlock(g_edrDeviceListMutex);
+            oc_mutex_unlock(g_edrDeviceListMutex);
             return CA_STATUS_FAILED;
         }
 
@@ -703,7 +709,7 @@ CAResult_t CAEDRClientSendUnicastData(const char *remoteAddress,
             // Remove device from list
             CARemoveEDRDeviceFromList(&g_edrDeviceList, remoteAddress);
 
-            ca_mutex_unlock(g_edrDeviceListMutex);
+            oc_mutex_unlock(g_edrDeviceListMutex);
             return CA_STATUS_FAILED;
         }
     }
@@ -714,11 +720,11 @@ CAResult_t CAEDRClientSendUnicastData(const char *remoteAddress,
         // Remove device from list
         CARemoveEDRDeviceFromList(&g_edrDeviceList, remoteAddress);
 
-        ca_mutex_unlock(g_edrDeviceListMutex);
+        oc_mutex_unlock(g_edrDeviceListMutex);
         return CA_STATUS_FAILED;
     }
 
-    ca_mutex_unlock(g_edrDeviceListMutex);
+    oc_mutex_unlock(g_edrDeviceListMutex);
 
     if (-1 == device->socketFD)
     {
@@ -774,7 +780,7 @@ CAResult_t CAEDRClientSendMulticastData(const uint8_t *data,
     }
 
     // Send the packet to all OIC devices
-    ca_mutex_lock(g_edrDeviceListMutex);
+    oc_mutex_lock(g_edrDeviceListMutex);
 
     EDRDeviceList *curList = g_edrDeviceList;
     CAResult_t result = CA_STATUS_FAILED;
@@ -829,7 +835,7 @@ CAResult_t CAEDRClientSendMulticastData(const uint8_t *data,
         }
     }
 
-    ca_mutex_unlock(g_edrDeviceListMutex);
+    oc_mutex_unlock(g_edrDeviceListMutex);
 
     if(g_isDiscoveryServer)
     {
@@ -855,13 +861,13 @@ CAResult_t CAEDRClientSendMulticastData(const uint8_t *data,
             multicastData->dataLength = dataLength;
 
             // Add the data to pending multicast data list.
-            ca_mutex_lock(g_multicastDataListMutex);
+            oc_mutex_lock(g_multicastDataListMutex);
             if (NULL == g_multicastDataList)
             {
                 g_multicastDataList = u_arraylist_create();
             }
             u_arraylist_add(g_multicastDataList, (void *)multicastData);
-            ca_mutex_unlock(g_multicastDataListMutex);
+            oc_mutex_unlock(g_multicastDataListMutex);
         }
     }
 
@@ -939,16 +945,16 @@ void CAEDRDataRecvCallback(bt_socket_received_data_s *data, void *userData)
     }
 
     // Get EDR device from list
-    ca_mutex_lock(g_edrDeviceListMutex);
+    oc_mutex_lock(g_edrDeviceListMutex);
     CAResult_t result = CAGetEDRDeviceBySocketId(g_edrDeviceList, data->socket_fd, &device);
     if (CA_STATUS_OK != result)
     {
         OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Could not find the device!");
 
-        ca_mutex_unlock(g_edrDeviceListMutex);
+        oc_mutex_unlock(g_edrDeviceListMutex);
         return;
     }
-    ca_mutex_unlock(g_edrDeviceListMutex);
+    oc_mutex_unlock(g_edrDeviceListMutex);
 
     //: TODO Need to check if 'check required for socket still connected or not'
     if (!device)
@@ -1000,7 +1006,7 @@ void CAEDRDataRecvCallback(bt_socket_received_data_s *data, void *userData)
 
     if (!deviceInfo->totalDataLen)
     {
-        coap_transport_type transport = coap_get_tcp_header_type_from_initbyte(
+        coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(
                 ((unsigned char *)deviceInfo->recvData)[0] >> 4);
         size_t headerLen = coap_get_tcp_header_length_for_transport(transport);
 
index 9ef15fa..f527f1d 100644 (file)
@@ -31,7 +31,7 @@
 #include "caadapterutils.h"
 #include "caedrutils.h"
 #include "logger.h"
-#include "camutex.h"
+#include "octhread.h"
 #include "cacommon.h"
 #include "caedrdevicelist.h"
 
@@ -46,6 +46,12 @@ CAResult_t CAEDRServerStart()
 {
     OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
 
+    if(-1 != g_serverFD)
+    {
+        OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "%s Already running", __func__);
+        return CA_STATUS_OK;
+    }
+
     bool isRunning = false;
     bt_error_e err = bt_adapter_is_service_used(OIC_EDR_SERVICE_ID, &isRunning);
     if (BT_ERROR_NONE != err)
index cbd5dbd..3e7fd41 100644 (file)
@@ -33,7 +33,7 @@
 #include "oic_malloc.h"
 #include "oic_string.h"
 #include "cathreadpool.h" /* for thread pool */
-#include "camutex.h"
+#include "octhread.h"
 #include "uarraylist.h"
 #include "org_iotivity_ca_CaLeClientInterface.h"
 
@@ -75,30 +75,30 @@ static jbyteArray g_sendBuffer = NULL;
 static uint32_t g_targetCnt = 0;
 static uint32_t g_currentSentCnt = 0;
 static bool g_isFinishedSendData = false;
-static ca_mutex g_SendFinishMutex = NULL;
-static ca_mutex g_threadMutex = NULL;
-static ca_cond g_threadCond = NULL;
-static ca_cond g_deviceDescCond = NULL;
-
-static ca_mutex g_threadSendMutex = NULL;
-static ca_mutex g_threadWriteCharacteristicMutex = NULL;
-static ca_cond g_threadWriteCharacteristicCond = NULL;
+static oc_mutex g_SendFinishMutex = NULL;
+static oc_mutex g_threadMutex = NULL;
+static oc_cond g_threadCond = NULL;
+static oc_cond g_deviceDescCond = NULL;
+
+static oc_mutex g_threadSendMutex = NULL;
+static oc_mutex g_threadWriteCharacteristicMutex = NULL;
+static oc_cond g_threadWriteCharacteristicCond = NULL;
 static bool g_isSignalSetFlag = false;
 
-static ca_mutex g_bleReqRespClientCbMutex = NULL;
-static ca_mutex g_bleServerBDAddressMutex = NULL;
+static oc_mutex g_bleReqRespClientCbMutex = NULL;
+static oc_mutex g_bleServerBDAddressMutex = NULL;
 
-static ca_mutex g_deviceListMutex = NULL;
-static ca_mutex g_gattObjectMutex = NULL;
-static ca_mutex g_deviceStateListMutex = NULL;
+static oc_mutex g_deviceListMutex = NULL;
+static oc_mutex g_gattObjectMutex = NULL;
+static oc_mutex g_deviceStateListMutex = NULL;
 
-static ca_mutex g_deviceScanRetryDelayMutex = NULL;
-static ca_cond g_deviceScanRetryDelayCond = NULL;
+static oc_mutex g_deviceScanRetryDelayMutex = NULL;
+static oc_cond g_deviceScanRetryDelayCond = NULL;
 
-static ca_mutex g_threadScanIntervalMutex = NULL;
-static ca_cond g_threadScanIntervalCond = NULL;
+static oc_mutex g_threadScanIntervalMutex = NULL;
+static oc_cond g_threadScanIntervalCond = NULL;
 
-static ca_mutex g_threadSendStateMutex = NULL;
+static oc_mutex g_threadSendStateMutex = NULL;
 
 static int32_t g_scanIntervalTime = WAIT_TIME_SCAN_INTERVAL_DEFAULT;
 static int32_t g_scanIntervalTimePrev = WAIT_TIME_SCAN_INTERVAL_DEFAULT;
@@ -130,8 +130,9 @@ static bool CALECheckConnectionStateValue(jint state)
         case GATT_REQUEST_NOT_SUPPORTED:
         case GATT_WRITE_NOT_PERMITTED:
             return true;
+        default:
+            return false;
     }
-    return false;
 }
 
 void CALEClientSetScanInterval(int32_t intervalTime, int32_t workingCount)
@@ -152,7 +153,7 @@ void CALERestartScanWithInterval(int32_t intervalTime, int32_t workingCount)
 {
     // restart scan with interval
     CALEClientSetScanInterval(intervalTime, workingCount);
-    ca_cond_signal(g_threadScanIntervalCond);
+    oc_cond_signal(g_threadScanIntervalCond);
 }
 
 static void CALEScanThread(void* object)
@@ -175,7 +176,7 @@ static void CALEScanThread(void* object)
         isAttached = true;
     }
 
-    ca_mutex_lock(g_threadScanIntervalMutex);
+    oc_mutex_lock(g_threadScanIntervalMutex);
     while(g_isWorkingScanThread)
     {
         OIC_LOG(DEBUG, TAG, "scan waiting time out");
@@ -199,7 +200,7 @@ static void CALEScanThread(void* object)
         }
 
         OIC_LOG_V(DEBUG, TAG, "wait for Scan Interval Time during %d sec", g_scanIntervalTime);
-        if (CA_WAIT_SUCCESS == ca_cond_wait_for(g_threadScanIntervalCond,
+        if (OC_WAIT_SUCCESS == oc_cond_wait_for(g_threadScanIntervalCond,
                                                 g_threadScanIntervalMutex,
                                                 g_scanIntervalTime * MICROSECS_PER_SEC))
         {
@@ -229,7 +230,7 @@ static void CALEScanThread(void* object)
            }
         }
     }
-    ca_mutex_unlock(g_threadScanIntervalMutex);
+    oc_mutex_unlock(g_threadScanIntervalMutex);
 
     if (isAttached)
     {
@@ -268,7 +269,7 @@ CAResult_t CALEClientStartScanWithInterval()
 void CALEClientStopScanWithInterval()
 {
     g_isWorkingScanThread = false;
-    ca_cond_signal(g_threadScanIntervalCond);
+    oc_cond_signal(g_threadScanIntervalCond);
 }
 
 //getting jvm
@@ -424,13 +425,13 @@ CAResult_t CALEClientInitialize()
         return ret;
     }
 
-    g_deviceDescCond = ca_cond_new();
+    g_deviceDescCond = oc_cond_new();
 
     // init mutex for send logic
-    g_threadCond = ca_cond_new();
-    g_threadWriteCharacteristicCond = ca_cond_new();
-    g_deviceScanRetryDelayCond = ca_cond_new();
-    g_threadScanIntervalCond =  ca_cond_new();
+    g_threadCond = oc_cond_new();
+    g_threadWriteCharacteristicCond = oc_cond_new();
+    g_deviceScanRetryDelayCond = oc_cond_new();
+    g_threadScanIntervalCond =  oc_cond_new();
 
     CALEClientCreateDeviceList();
     CALEClientJNISetContext();
@@ -543,11 +544,11 @@ void CALEClientTerminate()
     CALEClientTerminateGattMutexVariables();
     CALEClientDestroyJniInterface();
 
-    ca_cond_free(g_deviceDescCond);
-    ca_cond_free(g_threadCond);
-    ca_cond_free(g_threadWriteCharacteristicCond);
-    ca_cond_free(g_deviceScanRetryDelayCond);
-    ca_cond_free(g_threadScanIntervalCond);
+    oc_cond_free(g_deviceDescCond);
+    oc_cond_free(g_threadCond);
+    oc_cond_free(g_threadWriteCharacteristicCond);
+    oc_cond_free(g_deviceScanRetryDelayCond);
+    oc_cond_free(g_threadScanIntervalCond);
 
     g_deviceDescCond = NULL;
     g_threadCond = NULL;
@@ -770,13 +771,13 @@ CAResult_t CALEClientIsThereScannedDevices(JNIEnv *env, const char* address)
         for (size_t i = 0; i < RETRIES; ++i)
         {
             OIC_LOG(DEBUG, TAG, "waiting for target device");
-            if (ca_cond_wait_for(g_deviceDescCond,
+            if (oc_cond_wait_for(g_deviceDescCond,
                                  g_threadSendMutex,
-                                 TIMEOUT) == CA_WAIT_SUCCESS)
+                                 TIMEOUT) == OC_WAIT_SUCCESS)
             {
-                ca_mutex_lock(g_deviceListMutex);
+                oc_mutex_lock(g_deviceListMutex);
                 size_t scannedDeviceLen = u_arraylist_length(g_deviceList);
-                ca_mutex_unlock(g_deviceListMutex);
+                oc_mutex_unlock(g_deviceListMutex);
 
                 if (0 < scannedDeviceLen)
                 {
@@ -792,16 +793,16 @@ CAResult_t CALEClientIsThereScannedDevices(JNIEnv *env, const char* address)
                         {
                             OIC_LOG(INFO, TAG, "waiting..");
 
-                            ca_mutex_lock(g_deviceScanRetryDelayMutex);
-                            if (ca_cond_wait_for(g_deviceScanRetryDelayCond,
+                            oc_mutex_lock(g_deviceScanRetryDelayMutex);
+                            if (oc_cond_wait_for(g_deviceScanRetryDelayCond,
                                                  g_deviceScanRetryDelayMutex,
-                                                 MICROSECS_PER_SEC) == CA_WAIT_SUCCESS)
+                                                 MICROSECS_PER_SEC) == OC_WAIT_SUCCESS)
                             {
                                 OIC_LOG(INFO, TAG, "finish to waiting for target device");
-                                ca_mutex_unlock(g_deviceScanRetryDelayMutex);
+                                oc_mutex_unlock(g_deviceScanRetryDelayMutex);
                                 break;
                             }
-                            ca_mutex_unlock(g_deviceScanRetryDelayMutex);
+                            oc_mutex_unlock(g_deviceScanRetryDelayMutex);
                             // time out
 
                             // checking whether a target device is found while waiting for time-out.
@@ -859,7 +860,7 @@ CAResult_t CALEClientSendUnicastMessageImpl(const char* address, const uint8_t*
         isAttached = true;
     }
 
-    ca_mutex_lock(g_threadSendMutex);
+    oc_mutex_lock(g_threadSendMutex);
 
     CALEClientSetSendFinishFlag(false);
 
@@ -937,14 +938,14 @@ CAResult_t CALEClientSendUnicastMessageImpl(const char* address, const uint8_t*
 
     // wait for finish to send data through "CALeGattServicesDiscoveredCallback"
     // if there is no connection state.
-    ca_mutex_lock(g_threadMutex);
+    oc_mutex_lock(g_threadMutex);
     if (!g_isFinishedSendData)
     {
         OIC_LOG(DEBUG, TAG, "waiting send finish signal");
-        ca_cond_wait(g_threadCond, g_threadMutex);
+        oc_cond_wait(g_threadCond, g_threadMutex);
         OIC_LOG(DEBUG, TAG, "the data was sent");
     }
-    ca_mutex_unlock(g_threadMutex);
+    oc_mutex_unlock(g_threadMutex);
 
     if (isAttached)
     {
@@ -956,11 +957,11 @@ CAResult_t CALEClientSendUnicastMessageImpl(const char* address, const uint8_t*
     if (CA_STATUS_OK != ret)
     {
         OIC_LOG(ERROR, TAG, "CALEClientStartScanWithInterval has failed");
-        ca_mutex_unlock(g_threadSendMutex);
+        oc_mutex_unlock(g_threadSendMutex);
         return ret;
     }
 
-    ca_mutex_unlock(g_threadSendMutex);
+    oc_mutex_unlock(g_threadSendMutex);
     OIC_LOG(INFO, TAG, "unicast - send logic has finished");
     if (CALEClientIsValidState(address, CA_LE_SEND_STATE,
                                STATE_SEND_SUCCESS))
@@ -991,7 +992,7 @@ error_exit:
     if (CA_STATUS_OK != ret)
     {
         OIC_LOG(ERROR, TAG, "CALEClientStartScanWithInterval has failed");
-        ca_mutex_unlock(g_threadSendMutex);
+        oc_mutex_unlock(g_threadSendMutex);
         if (isAttached)
         {
             (*g_jvm)->DetachCurrentThread(g_jvm);
@@ -1004,7 +1005,7 @@ error_exit:
         (*g_jvm)->DetachCurrentThread(g_jvm);
     }
 
-    ca_mutex_unlock(g_threadSendMutex);
+    oc_mutex_unlock(g_threadSendMutex);
     return CA_SEND_FAILED;
 }
 
@@ -1021,7 +1022,7 @@ CAResult_t CALEClientSendMulticastMessageImpl(JNIEnv *env, const uint8_t* data,
         return CA_STATUS_FAILED;
     }
 
-    ca_mutex_lock(g_threadSendMutex);
+    oc_mutex_lock(g_threadSendMutex);
 
     CALEClientSetSendFinishFlag(false);
 
@@ -1068,25 +1069,25 @@ CAResult_t CALEClientSendMulticastMessageImpl(JNIEnv *env, const uint8_t* data,
     OIC_LOG(DEBUG, TAG, "connection routine is finished for multicast");
 
     // wait for finish to send data through "CALeGattServicesDiscoveredCallback"
-    ca_mutex_lock(g_threadMutex);
+    oc_mutex_lock(g_threadMutex);
     if (!g_isFinishedSendData)
     {
         OIC_LOG(DEBUG, TAG, "waiting send finish signal");
-        ca_cond_wait(g_threadCond, g_threadMutex);
+        oc_cond_wait(g_threadCond, g_threadMutex);
         OIC_LOG(DEBUG, TAG, "the data was sent");
     }
-    ca_mutex_unlock(g_threadMutex);
+    oc_mutex_unlock(g_threadMutex);
 
     // start LE Scan again
     res = CALEClientStartScanWithInterval();
     if (CA_STATUS_OK != res)
     {
         OIC_LOG(ERROR, TAG, "CALEClientStartScanWithInterval has failed");
-        ca_mutex_unlock(g_threadSendMutex);
+        oc_mutex_unlock(g_threadSendMutex);
         return res;
     }
 
-    ca_mutex_unlock(g_threadSendMutex);
+    oc_mutex_unlock(g_threadSendMutex);
     OIC_LOG(DEBUG, TAG, "OUT - CALEClientSendMulticastMessageImpl");
     return CA_STATUS_OK;
 
@@ -1095,11 +1096,11 @@ error_exit:
     if (CA_STATUS_OK != res)
     {
         OIC_LOG(ERROR, TAG, "CALEClientStartScanWithInterval has failed");
-        ca_mutex_unlock(g_threadSendMutex);
+        oc_mutex_unlock(g_threadSendMutex);
         return res;
     }
 
-    ca_mutex_unlock(g_threadSendMutex);
+    oc_mutex_unlock(g_threadSendMutex);
     OIC_LOG(DEBUG, TAG, "OUT - CALEClientSendMulticastMessageImpl");
     return CA_SEND_FAILED;
 }
@@ -1123,9 +1124,9 @@ CAResult_t CALEClientSendData(JNIEnv *env, jobject device)
             OIC_LOG(ERROR, TAG, "address is not available");
             return CA_STATUS_FAILED;
         }
-        ca_mutex_lock(g_deviceStateListMutex);
+        oc_mutex_lock(g_deviceStateListMutex);
         state = CALEClientGetStateInfo(address);
-        ca_mutex_unlock(g_deviceStateListMutex);
+        oc_mutex_unlock(g_deviceStateListMutex);
     }
 
     if (!state)
@@ -1641,7 +1642,7 @@ CAResult_t CALEClientSetFlagToState(JNIEnv *env, jstring jni_address, jint state
     VERIFY_NON_NULL(env, TAG, "env");
     VERIFY_NON_NULL(jni_address, TAG, "jni_address");
 
-    ca_mutex_lock(g_deviceStateListMutex);
+    oc_mutex_lock(g_deviceStateListMutex);
 
     char* address = (char*)(*env)->GetStringUTFChars(env, jni_address, NULL);
     if (!address)
@@ -1657,7 +1658,7 @@ CAResult_t CALEClientSetFlagToState(JNIEnv *env, jstring jni_address, jint state
         {
             OIC_LOG(ERROR, TAG, "curState is null");
             (*env)->ReleaseStringUTFChars(env, jni_address, address);
-            ca_mutex_unlock(g_deviceStateListMutex);
+            oc_mutex_unlock(g_deviceStateListMutex);
             return CA_STATUS_FAILED;
         }
         OIC_LOG_V(INFO, TAG, "%d flag is set : %d", state_idx, flag);
@@ -1676,7 +1677,7 @@ CAResult_t CALEClientSetFlagToState(JNIEnv *env, jstring jni_address, jint state
     }
 
     (*env)->ReleaseStringUTFChars(env, jni_address, address);
-    ca_mutex_unlock(g_deviceStateListMutex);
+    oc_mutex_unlock(g_deviceStateListMutex);
     OIC_LOG(DEBUG, TAG, "OUT - CALEClientSetFlagToState");
     return CA_STATUS_OK;
 }
@@ -1687,13 +1688,13 @@ jboolean CALEClientGetFlagFromState(JNIEnv *env, jstring jni_address, jint state
     VERIFY_NON_NULL_RET(env, TAG, "env", false);
     VERIFY_NON_NULL_RET(jni_address, TAG, "jni_address", false);
 
-    ca_mutex_lock(g_deviceStateListMutex);
+    oc_mutex_lock(g_deviceStateListMutex);
 
     char* address = (char*)(*env)->GetStringUTFChars(env, jni_address, NULL);
     if (!address)
     {
         OIC_LOG(ERROR, TAG, "address is not available");
-        ca_mutex_unlock(g_deviceStateListMutex);
+        oc_mutex_unlock(g_deviceStateListMutex);
         return JNI_FALSE;
     }
 
@@ -1702,7 +1703,7 @@ jboolean CALEClientGetFlagFromState(JNIEnv *env, jstring jni_address, jint state
     if(!curState)
     {
         OIC_LOG(INFO, TAG, "there is no information. auto connect flag is false");
-        ca_mutex_unlock(g_deviceStateListMutex);
+        oc_mutex_unlock(g_deviceStateListMutex);
         return JNI_FALSE;
     }
 
@@ -1718,7 +1719,7 @@ jboolean CALEClientGetFlagFromState(JNIEnv *env, jstring jni_address, jint state
         default:
             break;
     }
-    ca_mutex_unlock(g_deviceStateListMutex);
+    oc_mutex_unlock(g_deviceStateListMutex);
 
     OIC_LOG_V(INFO, TAG, "%d flag is %d", state_idx, ret);
     OIC_LOG(DEBUG, TAG, "OUT - CALEClientGetFlagFromState");
@@ -1731,13 +1732,13 @@ CAResult_t CALEClientDirectConnect(JNIEnv *env, jobject bluetoothDevice, jboolea
     VERIFY_NON_NULL(env, TAG, "env is null");
     VERIFY_NON_NULL(bluetoothDevice, TAG, "bluetoothDevice is null");
 
-    ca_mutex_lock(g_threadSendMutex);
+    oc_mutex_lock(g_threadSendMutex);
 
     jstring jni_address = CALEGetAddressFromBTDevice(env, bluetoothDevice);
     if (!jni_address)
     {
         OIC_LOG(ERROR, TAG, "jni_address is not available");
-        ca_mutex_unlock(g_threadSendMutex);
+        oc_mutex_unlock(g_threadSendMutex);
         return CA_STATUS_FAILED;
     }
 
@@ -1745,7 +1746,7 @@ CAResult_t CALEClientDirectConnect(JNIEnv *env, jobject bluetoothDevice, jboolea
     if (!address)
     {
         OIC_LOG(ERROR, TAG, "address is not available");
-        ca_mutex_unlock(g_threadSendMutex);
+        oc_mutex_unlock(g_threadSendMutex);
         return CA_STATUS_FAILED;
     }
 
@@ -1760,7 +1761,7 @@ CAResult_t CALEClientDirectConnect(JNIEnv *env, jobject bluetoothDevice, jboolea
             res = CA_STATUS_FAILED;
         }
     }
-    ca_mutex_unlock(g_threadSendMutex);
+    oc_mutex_unlock(g_threadSendMutex);
 
     return res;
 }
@@ -2177,13 +2178,13 @@ CAResult_t CALESetValueAndWriteCharacteristic(JNIEnv* env, jobject gatt)
         return CA_STATUS_FAILED;
     }
 
-    ca_mutex_lock(g_threadSendStateMutex);
+    oc_mutex_lock(g_threadSendStateMutex);
 
     if (CALEClientIsValidState(address, CA_LE_SEND_STATE, STATE_SENDING))
     {
         OIC_LOG(INFO, TAG, "current state is SENDING");
         (*env)->ReleaseStringUTFChars(env, jni_address, address);
-        ca_mutex_unlock(g_threadSendStateMutex);
+        oc_mutex_unlock(g_threadSendStateMutex);
         return CA_STATUS_OK;
     }
 
@@ -2193,13 +2194,13 @@ CAResult_t CALESetValueAndWriteCharacteristic(JNIEnv* env, jobject gatt)
         OIC_LOG(ERROR, TAG, "CALEClientUpdateDeviceState has failed");
         (*env)->ReleaseStringUTFChars(env, jni_address, address);
         CALEClientSendFinish(env, gatt);
-        ca_mutex_unlock(g_threadSendStateMutex);
+        oc_mutex_unlock(g_threadSendStateMutex);
         return CA_STATUS_FAILED;
     }
 
     (*env)->ReleaseStringUTFChars(env, jni_address, address);
 
-    ca_mutex_unlock(g_threadSendStateMutex);
+    oc_mutex_unlock(g_threadSendStateMutex);
 
     // send data
     jobject jni_obj_character = CALEClientCreateGattCharacteristic(env, gatt, g_sendBuffer);
@@ -2218,23 +2219,25 @@ CAResult_t CALESetValueAndWriteCharacteristic(JNIEnv* env, jobject gatt)
 
     // wait for callback for write Characteristic with success to sent data
     OIC_LOG_V(DEBUG, TAG, "callback flag is %d", g_isSignalSetFlag);
-    ca_mutex_lock(g_threadWriteCharacteristicMutex);
+    oc_mutex_lock(g_threadWriteCharacteristicMutex);
     if (!g_isSignalSetFlag)
     {
         OIC_LOG(DEBUG, TAG, "wait for callback to notify writeCharacteristic is success");
-        if (CA_WAIT_SUCCESS != ca_cond_wait_for(g_threadWriteCharacteristicCond,
+        if (OC_WAIT_SUCCESS != oc_cond_wait_for(g_threadWriteCharacteristicCond,
                                   g_threadWriteCharacteristicMutex,
                                   WAIT_TIME_WRITE_CHARACTERISTIC))
         {
             OIC_LOG(ERROR, TAG, "there is no response. write has failed");
             g_isSignalSetFlag = false;
-            ca_mutex_unlock(g_threadWriteCharacteristicMutex);
+            oc_mutex_unlock(g_threadWriteCharacteristicMutex);
             return CA_STATUS_FAILED;
         }
     }
     // reset flag set by writeCharacteristic Callback
     g_isSignalSetFlag = false;
-    ca_mutex_unlock(g_threadWriteCharacteristicMutex);
+    oc_mutex_unlock(g_threadWriteCharacteristicMutex);
+
+    CALEClientUpdateSendCnt(env);
 
     OIC_LOG(INFO, TAG, "writeCharacteristic success!!");
     return CA_STATUS_OK;
@@ -2759,7 +2762,7 @@ void CALEClientCreateScanDeviceList(JNIEnv *env)
     OIC_LOG(DEBUG, TAG, "CALEClientCreateScanDeviceList");
     VERIFY_NON_NULL_VOID(env, TAG, "env is null");
 
-    ca_mutex_lock(g_deviceListMutex);
+    oc_mutex_lock(g_deviceListMutex);
     // create new object array
     if (g_deviceList == NULL)
     {
@@ -2767,7 +2770,7 @@ void CALEClientCreateScanDeviceList(JNIEnv *env)
 
         g_deviceList = u_arraylist_create();
     }
-    ca_mutex_unlock(g_deviceListMutex);
+    oc_mutex_unlock(g_deviceListMutex);
 }
 
 CAResult_t CALEClientAddScanDeviceToList(JNIEnv *env, jobject device)
@@ -2775,14 +2778,14 @@ CAResult_t CALEClientAddScanDeviceToList(JNIEnv *env, jobject device)
     VERIFY_NON_NULL(device, TAG, "device is null");
     VERIFY_NON_NULL(env, TAG, "env is null");
 
-    ca_mutex_lock(g_deviceListMutex);
+    oc_mutex_lock(g_deviceListMutex);
 
     if (!g_deviceList)
     {
         OIC_LOG(ERROR, TAG, "gdevice_list is null");
         CALEClientStopScanWithInterval();
 
-        ca_mutex_unlock(g_deviceListMutex);
+        oc_mutex_unlock(g_deviceListMutex);
         return CA_STATUS_FAILED;
     }
 
@@ -2790,7 +2793,7 @@ CAResult_t CALEClientAddScanDeviceToList(JNIEnv *env, jobject device)
     if (!jni_remoteAddress)
     {
         OIC_LOG(ERROR, TAG, "jni_remoteAddress is null");
-        ca_mutex_unlock(g_deviceListMutex);
+        oc_mutex_unlock(g_deviceListMutex);
         return CA_STATUS_FAILED;
     }
 
@@ -2799,7 +2802,7 @@ CAResult_t CALEClientAddScanDeviceToList(JNIEnv *env, jobject device)
     {
         OIC_LOG(ERROR, TAG, "remoteAddress is null");
         (*env)->DeleteLocalRef(env, jni_remoteAddress);
-        ca_mutex_unlock(g_deviceListMutex);
+        oc_mutex_unlock(g_deviceListMutex);
         return CA_STATUS_FAILED;
     }
 
@@ -2807,13 +2810,13 @@ CAResult_t CALEClientAddScanDeviceToList(JNIEnv *env, jobject device)
     {
         jobject gdevice = (*env)->NewGlobalRef(env, device);
         u_arraylist_add(g_deviceList, gdevice);
-        ca_cond_signal(g_deviceDescCond);
+        oc_cond_signal(g_deviceDescCond);
         OIC_LOG_V(DEBUG, TAG, "Added a new BT Device in deviceList [%s]", remoteAddress);
     }
     (*env)->ReleaseStringUTFChars(env, jni_remoteAddress, remoteAddress);
     (*env)->DeleteLocalRef(env, jni_remoteAddress);
 
-    ca_mutex_unlock(g_deviceListMutex);
+    oc_mutex_unlock(g_deviceListMutex);
 
     return CA_STATUS_OK;
 }
@@ -2875,12 +2878,12 @@ CAResult_t CALEClientRemoveAllScanDevices(JNIEnv *env)
     OIC_LOG(DEBUG, TAG, "CALEClientRemoveAllScanDevices");
     VERIFY_NON_NULL(env, TAG, "env is null");
 
-    ca_mutex_lock(g_deviceListMutex);
+    oc_mutex_lock(g_deviceListMutex);
 
     if (!g_deviceList)
     {
         OIC_LOG(ERROR, TAG, "g_deviceList is null");
-        ca_mutex_unlock(g_deviceListMutex);
+        oc_mutex_unlock(g_deviceListMutex);
         return CA_STATUS_FAILED;
     }
 
@@ -2900,7 +2903,7 @@ CAResult_t CALEClientRemoveAllScanDevices(JNIEnv *env)
     OICFree(g_deviceList);
     g_deviceList = NULL;
 
-    ca_mutex_unlock(g_deviceListMutex);
+    oc_mutex_unlock(g_deviceListMutex);
     return CA_STATUS_OK;
 }
 
@@ -2910,12 +2913,12 @@ CAResult_t CALEClientRemoveDeviceInScanDeviceList(JNIEnv *env, jstring address)
     VERIFY_NON_NULL(address, TAG, "address is null");
     VERIFY_NON_NULL(env, TAG, "env is null");
 
-    ca_mutex_lock(g_deviceListMutex);
+    oc_mutex_lock(g_deviceListMutex);
 
     if (!g_deviceList)
     {
         OIC_LOG(ERROR, TAG, "g_deviceList is null");
-        ca_mutex_unlock(g_deviceListMutex);
+        oc_mutex_unlock(g_deviceListMutex);
         return CA_STATUS_FAILED;
     }
 
@@ -2926,7 +2929,7 @@ CAResult_t CALEClientRemoveDeviceInScanDeviceList(JNIEnv *env, jstring address)
         if (!jarrayObj)
         {
             OIC_LOG(ERROR, TAG, "jarrayObj is null");
-            ca_mutex_unlock(g_deviceListMutex);
+            oc_mutex_unlock(g_deviceListMutex);
             return CA_STATUS_FAILED;
         }
 
@@ -2934,7 +2937,7 @@ CAResult_t CALEClientRemoveDeviceInScanDeviceList(JNIEnv *env, jstring address)
         if (!jni_setAddress)
         {
             OIC_LOG(ERROR, TAG, "jni_setAddress is null");
-            ca_mutex_unlock(g_deviceListMutex);
+            oc_mutex_unlock(g_deviceListMutex);
             return CA_STATUS_FAILED;
         }
 
@@ -2942,7 +2945,7 @@ CAResult_t CALEClientRemoveDeviceInScanDeviceList(JNIEnv *env, jstring address)
         if (!setAddress)
         {
             OIC_LOG(ERROR, TAG, "setAddress is null");
-            ca_mutex_unlock(g_deviceListMutex);
+            oc_mutex_unlock(g_deviceListMutex);
             return CA_STATUS_FAILED;
         }
 
@@ -2951,7 +2954,7 @@ CAResult_t CALEClientRemoveDeviceInScanDeviceList(JNIEnv *env, jstring address)
         {
             OIC_LOG(ERROR, TAG, "remoteAddress is null");
             (*env)->ReleaseStringUTFChars(env, jni_setAddress, setAddress);
-            ca_mutex_unlock(g_deviceListMutex);
+            oc_mutex_unlock(g_deviceListMutex);
             return CA_STATUS_FAILED;
         }
 
@@ -2966,17 +2969,17 @@ CAResult_t CALEClientRemoveDeviceInScanDeviceList(JNIEnv *env, jstring address)
             if (NULL == u_arraylist_remove(g_deviceList, index))
             {
                 OIC_LOG(ERROR, TAG, "List removal failed.");
-                ca_mutex_unlock(g_deviceListMutex);
+                oc_mutex_unlock(g_deviceListMutex);
                 return CA_STATUS_FAILED;
             }
-            ca_mutex_unlock(g_deviceListMutex);
+            oc_mutex_unlock(g_deviceListMutex);
             return CA_STATUS_OK;
         }
         (*env)->ReleaseStringUTFChars(env, jni_setAddress, setAddress);
         (*env)->ReleaseStringUTFChars(env, address, remoteAddress);
     }
 
-    ca_mutex_unlock(g_deviceListMutex);
+    oc_mutex_unlock(g_deviceListMutex);
     OIC_LOG(DEBUG, TAG, "There are no object in the device list");
 
     return CA_STATUS_OK;
@@ -2992,12 +2995,12 @@ CAResult_t CALEClientAddGattobjToList(JNIEnv *env, jobject gatt)
     VERIFY_NON_NULL(env, TAG, "env is null");
     VERIFY_NON_NULL(gatt, TAG, "gatt is null");
 
-    ca_mutex_lock(g_gattObjectMutex);
+    oc_mutex_lock(g_gattObjectMutex);
 
     if (!g_gattObjectList)
     {
         OIC_LOG(ERROR, TAG, "g_gattObjectList is not available");
-        ca_mutex_unlock(g_gattObjectMutex);
+        oc_mutex_unlock(g_gattObjectMutex);
         return CA_STATUS_FAILED;
     }
 
@@ -3005,7 +3008,7 @@ CAResult_t CALEClientAddGattobjToList(JNIEnv *env, jobject gatt)
     if (!jni_remoteAddress)
     {
         OIC_LOG(ERROR, TAG, "jni_remoteAddress is null");
-        ca_mutex_unlock(g_gattObjectMutex);
+        oc_mutex_unlock(g_gattObjectMutex);
         return CA_STATUS_FAILED;
     }
 
@@ -3013,7 +3016,7 @@ CAResult_t CALEClientAddGattobjToList(JNIEnv *env, jobject gatt)
     if (!remoteAddress)
     {
         OIC_LOG(ERROR, TAG, "remoteAddress is null");
-        ca_mutex_unlock(g_gattObjectMutex);
+        oc_mutex_unlock(g_gattObjectMutex);
         return CA_STATUS_FAILED;
     }
 
@@ -3026,7 +3029,7 @@ CAResult_t CALEClientAddGattobjToList(JNIEnv *env, jobject gatt)
     }
 
     (*env)->ReleaseStringUTFChars(env, jni_remoteAddress, remoteAddress);
-    ca_mutex_unlock(g_gattObjectMutex);
+    oc_mutex_unlock(g_gattObjectMutex);
     return CA_STATUS_OK;
 }
 
@@ -3084,7 +3087,7 @@ jobject CALEClientGetGattObjInList(JNIEnv *env, const char* remoteAddress)
     VERIFY_NON_NULL_RET(env, TAG, "env is null", NULL);
     VERIFY_NON_NULL_RET(remoteAddress, TAG, "remoteAddress is null", NULL);
 
-    ca_mutex_lock(g_gattObjectMutex);
+    oc_mutex_lock(g_gattObjectMutex);
     uint32_t length = u_arraylist_length(g_gattObjectList);
     for (uint32_t index = 0; index < length; index++)
     {
@@ -3092,7 +3095,7 @@ jobject CALEClientGetGattObjInList(JNIEnv *env, const char* remoteAddress)
         if (!jarrayObj)
         {
             OIC_LOG(ERROR, TAG, "jarrayObj is null");
-            ca_mutex_unlock(g_gattObjectMutex);
+            oc_mutex_unlock(g_gattObjectMutex);
             return NULL;
         }
 
@@ -3100,7 +3103,7 @@ jobject CALEClientGetGattObjInList(JNIEnv *env, const char* remoteAddress)
         if (!jni_setAddress)
         {
             OIC_LOG(ERROR, TAG, "jni_setAddress is null");
-            ca_mutex_unlock(g_gattObjectMutex);
+            oc_mutex_unlock(g_gattObjectMutex);
             return NULL;
         }
 
@@ -3108,7 +3111,7 @@ jobject CALEClientGetGattObjInList(JNIEnv *env, const char* remoteAddress)
         if (!setAddress)
         {
             OIC_LOG(ERROR, TAG, "setAddress is null");
-            ca_mutex_unlock(g_gattObjectMutex);
+            oc_mutex_unlock(g_gattObjectMutex);
             return NULL;
         }
 
@@ -3116,13 +3119,13 @@ jobject CALEClientGetGattObjInList(JNIEnv *env, const char* remoteAddress)
         {
             OIC_LOG(DEBUG, TAG, "the device is already set");
             (*env)->ReleaseStringUTFChars(env, jni_setAddress, setAddress);
-            ca_mutex_unlock(g_gattObjectMutex);
+            oc_mutex_unlock(g_gattObjectMutex);
             return jarrayObj;
         }
         (*env)->ReleaseStringUTFChars(env, jni_setAddress, setAddress);
     }
 
-    ca_mutex_unlock(g_gattObjectMutex);
+    oc_mutex_unlock(g_gattObjectMutex);
     OIC_LOG(DEBUG, TAG, "There are no the gatt object in list");
     return NULL;
 }
@@ -3132,11 +3135,11 @@ CAResult_t CALEClientRemoveAllGattObjs(JNIEnv *env)
     OIC_LOG(DEBUG, TAG, "CALEClientRemoveAllGattObjs");
     VERIFY_NON_NULL(env, TAG, "env is null");
 
-    ca_mutex_lock(g_gattObjectMutex);
+    oc_mutex_lock(g_gattObjectMutex);
     if (!g_gattObjectList)
     {
         OIC_LOG(DEBUG, TAG, "already removed for g_gattObjectList");
-        ca_mutex_unlock(g_gattObjectMutex);
+        oc_mutex_unlock(g_gattObjectMutex);
         return CA_STATUS_OK;
     }
 
@@ -3156,7 +3159,7 @@ CAResult_t CALEClientRemoveAllGattObjs(JNIEnv *env)
     OICFree(g_gattObjectList);
     g_gattObjectList = NULL;
     OIC_LOG(INFO, TAG, "g_gattObjectList is removed");
-    ca_mutex_unlock(g_gattObjectMutex);
+    oc_mutex_unlock(g_gattObjectMutex);
     return CA_STATUS_OK;
 }
 
@@ -3166,11 +3169,11 @@ CAResult_t CALEClientRemoveGattObj(JNIEnv *env, jobject gatt)
     VERIFY_NON_NULL(gatt, TAG, "gatt is null");
     VERIFY_NON_NULL(env, TAG, "env is null");
 
-    ca_mutex_lock(g_gattObjectMutex);
+    oc_mutex_lock(g_gattObjectMutex);
     if (!g_gattObjectList)
     {
         OIC_LOG(DEBUG, TAG, "already removed for g_gattObjectList");
-        ca_mutex_unlock(g_gattObjectMutex);
+        oc_mutex_unlock(g_gattObjectMutex);
         return CA_STATUS_OK;
     }
 
@@ -3181,7 +3184,7 @@ CAResult_t CALEClientRemoveGattObj(JNIEnv *env, jobject gatt)
         if (!jarrayObj)
         {
             OIC_LOG(ERROR, TAG, "jarrayObj is null");
-            ca_mutex_unlock(g_gattObjectMutex);
+            oc_mutex_unlock(g_gattObjectMutex);
             return CA_STATUS_FAILED;
         }
 
@@ -3189,7 +3192,7 @@ CAResult_t CALEClientRemoveGattObj(JNIEnv *env, jobject gatt)
         if (!jni_setAddress)
         {
             OIC_LOG(ERROR, TAG, "jni_setAddress is null");
-            ca_mutex_unlock(g_gattObjectMutex);
+            oc_mutex_unlock(g_gattObjectMutex);
             return CA_STATUS_FAILED;
         }
 
@@ -3197,7 +3200,7 @@ CAResult_t CALEClientRemoveGattObj(JNIEnv *env, jobject gatt)
         if (!setAddress)
         {
             OIC_LOG(ERROR, TAG, "setAddress is null");
-            ca_mutex_unlock(g_gattObjectMutex);
+            oc_mutex_unlock(g_gattObjectMutex);
             return CA_STATUS_FAILED;
         }
 
@@ -3206,7 +3209,7 @@ CAResult_t CALEClientRemoveGattObj(JNIEnv *env, jobject gatt)
         {
             OIC_LOG(ERROR, TAG, "jni_remoteAddress is null");
             (*env)->ReleaseStringUTFChars(env, jni_setAddress, setAddress);
-            ca_mutex_unlock(g_gattObjectMutex);
+            oc_mutex_unlock(g_gattObjectMutex);
             return CA_STATUS_FAILED;
         }
 
@@ -3215,7 +3218,7 @@ CAResult_t CALEClientRemoveGattObj(JNIEnv *env, jobject gatt)
         {
             OIC_LOG(ERROR, TAG, "remoteAddress is null");
             (*env)->ReleaseStringUTFChars(env, jni_setAddress, setAddress);
-            ca_mutex_unlock(g_gattObjectMutex);
+            oc_mutex_unlock(g_gattObjectMutex);
             return CA_STATUS_FAILED;
         }
 
@@ -3230,17 +3233,17 @@ CAResult_t CALEClientRemoveGattObj(JNIEnv *env, jobject gatt)
             if (NULL == u_arraylist_remove(g_gattObjectList, index))
             {
                 OIC_LOG(ERROR, TAG, "List removal failed.");
-                ca_mutex_unlock(g_gattObjectMutex);
+                oc_mutex_unlock(g_gattObjectMutex);
                 return CA_STATUS_FAILED;
             }
-            ca_mutex_unlock(g_gattObjectMutex);
+            oc_mutex_unlock(g_gattObjectMutex);
             return CA_STATUS_OK;
         }
         (*env)->ReleaseStringUTFChars(env, jni_setAddress, setAddress);
         (*env)->ReleaseStringUTFChars(env, jni_remoteAddress, remoteAddress);
     }
 
-    ca_mutex_unlock(g_gattObjectMutex);
+    oc_mutex_unlock(g_gattObjectMutex);
     OIC_LOG(DEBUG, TAG, "there are no target object");
     return CA_STATUS_OK;
 }
@@ -3251,11 +3254,11 @@ CAResult_t CALEClientRemoveGattObjForAddr(JNIEnv *env, jstring addr)
     VERIFY_NON_NULL(addr, TAG, "addr is null");
     VERIFY_NON_NULL(env, TAG, "env is null");
 
-    ca_mutex_lock(g_gattObjectMutex);
+    oc_mutex_lock(g_gattObjectMutex);
     if (!g_gattObjectList)
     {
         OIC_LOG(DEBUG, TAG, "already removed for g_gattObjectList");
-        ca_mutex_unlock(g_gattObjectMutex);
+        oc_mutex_unlock(g_gattObjectMutex);
         return CA_STATUS_OK;
     }
 
@@ -3266,7 +3269,7 @@ CAResult_t CALEClientRemoveGattObjForAddr(JNIEnv *env, jstring addr)
         if (!jarrayObj)
         {
             OIC_LOG(ERROR, TAG, "jarrayObj is null");
-            ca_mutex_unlock(g_gattObjectMutex);
+            oc_mutex_unlock(g_gattObjectMutex);
             return CA_STATUS_FAILED;
         }
 
@@ -3274,7 +3277,7 @@ CAResult_t CALEClientRemoveGattObjForAddr(JNIEnv *env, jstring addr)
         if (!jni_setAddress)
         {
             OIC_LOG(ERROR, TAG, "jni_setAddress is null");
-            ca_mutex_unlock(g_gattObjectMutex);
+            oc_mutex_unlock(g_gattObjectMutex);
             return CA_STATUS_FAILED;
         }
 
@@ -3282,7 +3285,7 @@ CAResult_t CALEClientRemoveGattObjForAddr(JNIEnv *env, jstring addr)
         if (!setAddress)
         {
             OIC_LOG(ERROR, TAG, "setAddress is null");
-            ca_mutex_unlock(g_gattObjectMutex);
+            oc_mutex_unlock(g_gattObjectMutex);
             return CA_STATUS_FAILED;
         }
 
@@ -3291,7 +3294,7 @@ CAResult_t CALEClientRemoveGattObjForAddr(JNIEnv *env, jstring addr)
         {
             OIC_LOG(ERROR, TAG, "remoteAddress is null");
             (*env)->ReleaseStringUTFChars(env, jni_setAddress, setAddress);
-            ca_mutex_unlock(g_gattObjectMutex);
+            oc_mutex_unlock(g_gattObjectMutex);
             return CA_STATUS_FAILED;
         }
 
@@ -3305,17 +3308,17 @@ CAResult_t CALEClientRemoveGattObjForAddr(JNIEnv *env, jstring addr)
             if (NULL == u_arraylist_remove(g_gattObjectList, index))
             {
                 OIC_LOG(ERROR, TAG, "List removal failed.");
-                ca_mutex_unlock(g_gattObjectMutex);
+                oc_mutex_unlock(g_gattObjectMutex);
                 return CA_STATUS_FAILED;
             }
-            ca_mutex_unlock(g_gattObjectMutex);
+            oc_mutex_unlock(g_gattObjectMutex);
             return CA_STATUS_OK;
         }
         (*env)->ReleaseStringUTFChars(env, jni_setAddress, setAddress);
         (*env)->ReleaseStringUTFChars(env, addr, remoteAddress);
     }
 
-    ca_mutex_unlock(g_gattObjectMutex);
+    oc_mutex_unlock(g_gattObjectMutex);
     OIC_LOG(DEBUG, TAG, "there are no target object");
     return CA_STATUS_FAILED;
 }
@@ -3352,7 +3355,7 @@ jstring CALEClientGetLEAddressFromBTDevice(JNIEnv *env, jobject bluetoothDevice)
         return NULL;
     }
 
-    ca_mutex_lock(g_gattObjectMutex);
+    oc_mutex_lock(g_gattObjectMutex);
 
     size_t length = u_arraylist_length(g_gattObjectList);
     OIC_LOG_V(DEBUG, TAG, "length of gattObjectList : %d", length);
@@ -3363,7 +3366,7 @@ jstring CALEClientGetLEAddressFromBTDevice(JNIEnv *env, jobject bluetoothDevice)
         jobject jarrayObj = (jobject) u_arraylist_get(g_gattObjectList, index);
         if (!jarrayObj)
         {
-            ca_mutex_unlock(g_gattObjectMutex);
+            oc_mutex_unlock(g_gattObjectMutex);
             OIC_LOG(ERROR, TAG, "jarrayObj is null");
             (*env)->ReleaseStringUTFChars(env, jni_btTargetAddress, targetAddress);
             return NULL;
@@ -3372,7 +3375,7 @@ jstring CALEClientGetLEAddressFromBTDevice(JNIEnv *env, jobject bluetoothDevice)
         jobject jni_obj_device = (*env)->CallObjectMethod(env, jarrayObj, jni_mid_getDevice);
         if (!jni_obj_device)
         {
-            ca_mutex_unlock(g_gattObjectMutex);
+            oc_mutex_unlock(g_gattObjectMutex);
             OIC_LOG(ERROR, TAG, "jni_obj_device is null");
             (*env)->ReleaseStringUTFChars(env, jni_btTargetAddress, targetAddress);
             return NULL;
@@ -3381,7 +3384,7 @@ jstring CALEClientGetLEAddressFromBTDevice(JNIEnv *env, jobject bluetoothDevice)
         jstring jni_btAddress = CALEGetAddressFromBTDevice(env, jni_obj_device);
         if (!jni_btAddress)
         {
-            ca_mutex_unlock(g_gattObjectMutex);
+            oc_mutex_unlock(g_gattObjectMutex);
             OIC_LOG(ERROR, TAG, "CALEGetAddressFromBTDevice has failed");
             (*env)->ReleaseStringUTFChars(env, jni_btTargetAddress, targetAddress);
             return NULL;
@@ -3390,7 +3393,7 @@ jstring CALEClientGetLEAddressFromBTDevice(JNIEnv *env, jobject bluetoothDevice)
         const char* btAddress = (*env)->GetStringUTFChars(env, jni_btAddress, NULL);
         if (!btAddress)
         {
-            ca_mutex_unlock(g_gattObjectMutex);
+            oc_mutex_unlock(g_gattObjectMutex);
             OIC_LOG(ERROR, TAG, "btAddress is not available");
             (*env)->ReleaseStringUTFChars(env, jni_btTargetAddress, targetAddress);
             return NULL;
@@ -3407,7 +3410,7 @@ jstring CALEClientGetLEAddressFromBTDevice(JNIEnv *env, jobject bluetoothDevice)
             {
                 OIC_LOG(ERROR, TAG, "jni_LEAddress is null");
             }
-            ca_mutex_unlock(g_gattObjectMutex);
+            oc_mutex_unlock(g_gattObjectMutex);
             (*env)->ReleaseStringUTFChars(env, jni_btTargetAddress, targetAddress);
             (*env)->ReleaseStringUTFChars(env, jni_btAddress, btAddress);
             (*env)->DeleteLocalRef(env, jni_btAddress);
@@ -3418,7 +3421,7 @@ jstring CALEClientGetLEAddressFromBTDevice(JNIEnv *env, jobject bluetoothDevice)
         (*env)->DeleteLocalRef(env, jni_btAddress);
         (*env)->DeleteLocalRef(env, jni_obj_device);
     }
-    ca_mutex_unlock(g_gattObjectMutex);
+    oc_mutex_unlock(g_gattObjectMutex);
 
     (*env)->ReleaseStringUTFChars(env, jni_btTargetAddress, targetAddress);
     OIC_LOG_V(DEBUG, TAG, "[%s] doesn't exist in gattObjectList", targetAddress);
@@ -3442,7 +3445,7 @@ CAResult_t CALEClientUpdateDeviceState(const char* address, uint16_t state_type,
         return CA_STATUS_FAILED;
     }
 
-    ca_mutex_lock(g_deviceStateListMutex);
+    oc_mutex_lock(g_deviceStateListMutex);
 
     if (CALEClientIsDeviceInList(address))
     {
@@ -3450,7 +3453,7 @@ CAResult_t CALEClientUpdateDeviceState(const char* address, uint16_t state_type,
         if(!curState)
         {
             OIC_LOG(ERROR, TAG, "curState is null");
-            ca_mutex_unlock(g_deviceStateListMutex);
+            oc_mutex_unlock(g_deviceStateListMutex);
             return CA_STATUS_FAILED;
         }
 
@@ -3474,7 +3477,7 @@ CAResult_t CALEClientUpdateDeviceState(const char* address, uint16_t state_type,
         if (strlen(address) > CA_MACADDR_SIZE)
         {
             OIC_LOG(ERROR, TAG, "address is not proper");
-            ca_mutex_unlock(g_deviceStateListMutex);
+            oc_mutex_unlock(g_deviceStateListMutex);
             return CA_STATUS_INVALID_PARAM;
         }
 
@@ -3482,7 +3485,7 @@ CAResult_t CALEClientUpdateDeviceState(const char* address, uint16_t state_type,
         if (!newstate)
         {
             OIC_LOG(ERROR, TAG, "out of memory");
-            ca_mutex_unlock(g_deviceStateListMutex);
+            oc_mutex_unlock(g_deviceStateListMutex);
             return CA_MEMORY_ALLOC_FAILED;
         }
 
@@ -3507,7 +3510,7 @@ CAResult_t CALEClientUpdateDeviceState(const char* address, uint16_t state_type,
                   newstate->autoConnectFlag);
         u_arraylist_add(g_deviceStateList, newstate); // update new state
     }
-    ca_mutex_unlock(g_deviceStateListMutex);
+    oc_mutex_unlock(g_deviceStateListMutex);
 
     return CA_STATUS_OK;
 }
@@ -3551,11 +3554,11 @@ CAResult_t CALEClientRemoveAllDeviceState()
 {
     OIC_LOG(DEBUG, TAG, "CALEClientRemoveAllDeviceState");
 
-    ca_mutex_lock(g_deviceStateListMutex);
+    oc_mutex_lock(g_deviceStateListMutex);
     if (!g_deviceStateList)
     {
         OIC_LOG(ERROR, TAG, "g_deviceStateList is null");
-        ca_mutex_unlock(g_deviceStateListMutex);
+        oc_mutex_unlock(g_deviceStateListMutex);
         return CA_STATUS_FAILED;
     }
 
@@ -3573,7 +3576,7 @@ CAResult_t CALEClientRemoveAllDeviceState()
 
     OICFree(g_deviceStateList);
     g_deviceStateList = NULL;
-    ca_mutex_unlock(g_deviceStateListMutex);
+    oc_mutex_unlock(g_deviceStateListMutex);
 
     return CA_STATUS_OK;
 }
@@ -3582,11 +3585,11 @@ CAResult_t CALEClientResetDeviceStateForAll()
 {
     OIC_LOG(DEBUG, TAG, "CALEClientResetDeviceStateForAll");
 
-    ca_mutex_lock(g_deviceStateListMutex);
+    oc_mutex_lock(g_deviceStateListMutex);
     if (!g_deviceStateList)
     {
         OIC_LOG(ERROR, TAG, "g_deviceStateList is null");
-        ca_mutex_unlock(g_deviceStateListMutex);
+        oc_mutex_unlock(g_deviceStateListMutex);
         return CA_STATUS_FAILED;
     }
 
@@ -3605,7 +3608,7 @@ CAResult_t CALEClientResetDeviceStateForAll()
         state->connectedState = STATE_DISCONNECTED;
         state->sendState = STATE_SEND_NONE;
     }
-    ca_mutex_unlock(g_deviceStateListMutex);
+    oc_mutex_unlock(g_deviceStateListMutex);
 
     return CA_STATUS_OK;
 }
@@ -3694,11 +3697,11 @@ bool CALEClientIsValidState(const char* remoteAddress, uint16_t state_type,
               state_type, target_state);
     VERIFY_NON_NULL_RET(remoteAddress, TAG, "remoteAddress is null", false);
 
-    ca_mutex_lock(g_deviceStateListMutex);
+    oc_mutex_lock(g_deviceStateListMutex);
     if (!g_deviceStateList)
     {
         OIC_LOG(ERROR, TAG, "g_deviceStateList is null");
-        ca_mutex_unlock(g_deviceStateListMutex);
+        oc_mutex_unlock(g_deviceStateListMutex);
         return false;
     }
 
@@ -3706,7 +3709,7 @@ bool CALEClientIsValidState(const char* remoteAddress, uint16_t state_type,
     if (NULL == state)
     {
         OIC_LOG(ERROR, TAG, "state is null");
-        ca_mutex_unlock(g_deviceStateListMutex);
+        oc_mutex_unlock(g_deviceStateListMutex);
         return false;
     }
 
@@ -3725,16 +3728,16 @@ bool CALEClientIsValidState(const char* remoteAddress, uint16_t state_type,
 
     if (target_state == curValue)
     {
-        ca_mutex_unlock(g_deviceStateListMutex);
+        oc_mutex_unlock(g_deviceStateListMutex);
         return true;
     }
     else
     {
-        ca_mutex_unlock(g_deviceStateListMutex);
+        oc_mutex_unlock(g_deviceStateListMutex);
         return false;
     }
 
-    ca_mutex_unlock(g_deviceStateListMutex);
+    oc_mutex_unlock(g_deviceStateListMutex);
     return false;
 }
 
@@ -3774,7 +3777,7 @@ void CALEClientUpdateSendCnt(JNIEnv *env)
 
     VERIFY_NON_NULL_VOID(env, TAG, "env is null");
     // mutex lock
-    ca_mutex_lock(g_threadMutex);
+    oc_mutex_lock(g_threadMutex);
 
     g_currentSentCnt++;
 
@@ -3789,133 +3792,133 @@ void CALEClientUpdateSendCnt(JNIEnv *env)
             g_sendBuffer = NULL;
         }
         // notity the thread
-        ca_cond_signal(g_threadCond);
+        oc_cond_signal(g_threadCond);
 
         CALEClientSetSendFinishFlag(true);
         OIC_LOG(DEBUG, TAG, "set signal for send data");
     }
     // mutex unlock
-    ca_mutex_unlock(g_threadMutex);
+    oc_mutex_unlock(g_threadMutex);
 }
 
 CAResult_t CALEClientInitGattMutexVaraibles()
 {
     if (NULL == g_bleReqRespClientCbMutex)
     {
-        g_bleReqRespClientCbMutex = ca_mutex_new();
+        g_bleReqRespClientCbMutex = oc_mutex_new();
         if (NULL == g_bleReqRespClientCbMutex)
         {
-            OIC_LOG(ERROR, TAG, "ca_mutex_new has failed");
+            OIC_LOG(ERROR, TAG, "oc_mutex_new has failed");
             return CA_STATUS_FAILED;
         }
     }
 
     if (NULL == g_bleServerBDAddressMutex)
     {
-        g_bleServerBDAddressMutex = ca_mutex_new();
+        g_bleServerBDAddressMutex = oc_mutex_new();
         if (NULL == g_bleServerBDAddressMutex)
         {
-            OIC_LOG(ERROR, TAG, "ca_mutex_new has failed");
+            OIC_LOG(ERROR, TAG, "oc_mutex_new has failed");
             return CA_STATUS_FAILED;
         }
     }
 
     if (NULL == g_threadMutex)
     {
-        g_threadMutex = ca_mutex_new();
+        g_threadMutex = oc_mutex_new();
         if (NULL == g_threadMutex)
         {
-            OIC_LOG(ERROR, TAG, "ca_mutex_new has failed");
+            OIC_LOG(ERROR, TAG, "oc_mutex_new has failed");
             return CA_STATUS_FAILED;
         }
     }
 
     if (NULL == g_threadSendMutex)
     {
-        g_threadSendMutex = ca_mutex_new();
+        g_threadSendMutex = oc_mutex_new();
         if (NULL == g_threadSendMutex)
         {
-            OIC_LOG(ERROR, TAG, "ca_mutex_new has failed");
+            OIC_LOG(ERROR, TAG, "oc_mutex_new has failed");
             return CA_STATUS_FAILED;
         }
     }
 
     if (NULL == g_deviceListMutex)
     {
-        g_deviceListMutex = ca_mutex_new();
+        g_deviceListMutex = oc_mutex_new();
         if (NULL == g_deviceListMutex)
         {
-            OIC_LOG(ERROR, TAG, "ca_mutex_new has failed");
+            OIC_LOG(ERROR, TAG, "oc_mutex_new has failed");
             return CA_STATUS_FAILED;
         }
     }
 
     if (NULL == g_gattObjectMutex)
     {
-        g_gattObjectMutex = ca_mutex_new();
+        g_gattObjectMutex = oc_mutex_new();
         if (NULL == g_gattObjectMutex)
         {
-            OIC_LOG(ERROR, TAG, "ca_mutex_new has failed");
+            OIC_LOG(ERROR, TAG, "oc_mutex_new has failed");
             return CA_STATUS_FAILED;
         }
     }
 
     if (NULL == g_deviceStateListMutex)
     {
-        g_deviceStateListMutex = ca_mutex_new();
+        g_deviceStateListMutex = oc_mutex_new();
         if (NULL == g_deviceStateListMutex)
         {
-            OIC_LOG(ERROR, TAG, "ca_mutex_new has failed");
+            OIC_LOG(ERROR, TAG, "oc_mutex_new has failed");
             return CA_STATUS_FAILED;
         }
     }
 
     if (NULL == g_SendFinishMutex)
     {
-        g_SendFinishMutex = ca_mutex_new();
+        g_SendFinishMutex = oc_mutex_new();
         if (NULL == g_SendFinishMutex)
         {
-            OIC_LOG(ERROR, TAG, "ca_mutex_new has failed");
+            OIC_LOG(ERROR, TAG, "oc_mutex_new has failed");
             return CA_STATUS_FAILED;
         }
     }
 
     if (NULL == g_threadWriteCharacteristicMutex)
     {
-        g_threadWriteCharacteristicMutex = ca_mutex_new();
+        g_threadWriteCharacteristicMutex = oc_mutex_new();
         if (NULL == g_threadWriteCharacteristicMutex)
         {
-            OIC_LOG(ERROR, TAG, "ca_mutex_new has failed");
+            OIC_LOG(ERROR, TAG, "oc_mutex_new has failed");
             return CA_STATUS_FAILED;
         }
     }
 
     if (NULL == g_deviceScanRetryDelayMutex)
     {
-        g_deviceScanRetryDelayMutex = ca_mutex_new();
+        g_deviceScanRetryDelayMutex = oc_mutex_new();
         if (NULL == g_deviceScanRetryDelayMutex)
         {
-            OIC_LOG(ERROR, TAG, "ca_mutex_new has failed");
+            OIC_LOG(ERROR, TAG, "oc_mutex_new has failed");
             return CA_STATUS_FAILED;
         }
     }
 
     if (NULL == g_threadSendStateMutex)
     {
-        g_threadSendStateMutex = ca_mutex_new();
+        g_threadSendStateMutex = oc_mutex_new();
         if (NULL == g_threadSendStateMutex)
         {
-            OIC_LOG(ERROR, TAG, "ca_mutex_new has failed");
+            OIC_LOG(ERROR, TAG, "oc_mutex_new has failed");
             return CA_STATUS_FAILED;
         }
     }
 
     if (NULL == g_threadScanIntervalMutex)
     {
-        g_threadScanIntervalMutex = ca_mutex_new();
+        g_threadScanIntervalMutex = oc_mutex_new();
         if (NULL == g_threadScanIntervalMutex)
         {
-            OIC_LOG(ERROR, TAG, "ca_mutex_new has failed");
+            OIC_LOG(ERROR, TAG, "oc_mutex_new has failed");
             return CA_STATUS_FAILED;
         }
     }
@@ -3925,34 +3928,34 @@ CAResult_t CALEClientInitGattMutexVaraibles()
 
 void CALEClientTerminateGattMutexVariables()
 {
-    ca_mutex_free(g_bleReqRespClientCbMutex);
+    oc_mutex_free(g_bleReqRespClientCbMutex);
     g_bleReqRespClientCbMutex = NULL;
 
-    ca_mutex_free(g_bleServerBDAddressMutex);
+    oc_mutex_free(g_bleServerBDAddressMutex);
     g_bleServerBDAddressMutex = NULL;
 
-    ca_mutex_free(g_threadMutex);
+    oc_mutex_free(g_threadMutex);
     g_threadMutex = NULL;
 
-    ca_mutex_free(g_threadSendMutex);
+    oc_mutex_free(g_threadSendMutex);
     g_threadSendMutex = NULL;
 
-    ca_mutex_free(g_deviceListMutex);
+    oc_mutex_free(g_deviceListMutex);
     g_deviceListMutex = NULL;
 
-    ca_mutex_free(g_SendFinishMutex);
+    oc_mutex_free(g_SendFinishMutex);
     g_SendFinishMutex = NULL;
 
-    ca_mutex_free(g_threadWriteCharacteristicMutex);
+    oc_mutex_free(g_threadWriteCharacteristicMutex);
     g_threadWriteCharacteristicMutex = NULL;
 
-    ca_mutex_free(g_deviceScanRetryDelayMutex);
+    oc_mutex_free(g_deviceScanRetryDelayMutex);
     g_deviceScanRetryDelayMutex = NULL;
 
-    ca_mutex_free(g_threadSendStateMutex);
+    oc_mutex_free(g_threadSendStateMutex);
     g_threadSendStateMutex = NULL;
 
-    ca_mutex_free(g_threadScanIntervalMutex);
+    oc_mutex_free(g_threadScanIntervalMutex);
     g_threadScanIntervalMutex = NULL;
 }
 
@@ -3960,9 +3963,9 @@ void CALEClientSetSendFinishFlag(bool flag)
 {
     OIC_LOG_V(DEBUG, TAG, "g_isFinishedSendData is %d", flag);
 
-    ca_mutex_lock(g_SendFinishMutex);
+    oc_mutex_lock(g_SendFinishMutex);
     g_isFinishedSendData = flag;
-    ca_mutex_unlock(g_SendFinishMutex);
+    oc_mutex_unlock(g_SendFinishMutex);
 }
 
 /**
@@ -3974,22 +3977,22 @@ CAResult_t CAStartLEGattClient()
     // init mutex for send logic
     if (!g_deviceDescCond)
     {
-        g_deviceDescCond = ca_cond_new();
+        g_deviceDescCond = oc_cond_new();
     }
 
     if (!g_threadCond)
     {
-        g_threadCond = ca_cond_new();
+        g_threadCond = oc_cond_new();
     }
 
     if (!g_threadWriteCharacteristicCond)
     {
-        g_threadWriteCharacteristicCond = ca_cond_new();
+        g_threadWriteCharacteristicCond = oc_cond_new();
     }
 
     if (!g_threadScanIntervalCond)
     {
-        g_threadScanIntervalCond = ca_cond_new();
+        g_threadScanIntervalCond = oc_cond_new();
     }
 
     CAResult_t ret = CALEClientStartScanWithInterval();
@@ -4037,32 +4040,32 @@ void CAStopLEGattClient()
 
     CALEClientStopScanWithInterval();
 
-    ca_mutex_lock(g_threadMutex);
+    oc_mutex_lock(g_threadMutex);
     OIC_LOG(DEBUG, TAG, "signal - connection cond");
-    ca_cond_signal(g_threadCond);
+    oc_cond_signal(g_threadCond);
     CALEClientSetSendFinishFlag(true);
-    ca_mutex_unlock(g_threadMutex);
+    oc_mutex_unlock(g_threadMutex);
 
-    ca_mutex_lock(g_threadWriteCharacteristicMutex);
+    oc_mutex_lock(g_threadWriteCharacteristicMutex);
     OIC_LOG(DEBUG, TAG, "signal - WriteCharacteristic cond");
-    ca_cond_signal(g_threadWriteCharacteristicCond);
-    ca_mutex_unlock(g_threadWriteCharacteristicMutex);
+    oc_cond_signal(g_threadWriteCharacteristicCond);
+    oc_mutex_unlock(g_threadWriteCharacteristicMutex);
 
-    ca_mutex_lock(g_deviceScanRetryDelayMutex);
+    oc_mutex_lock(g_deviceScanRetryDelayMutex);
     OIC_LOG(DEBUG, TAG, "signal - delay cond");
-    ca_cond_signal(g_deviceScanRetryDelayCond);
-    ca_mutex_unlock(g_deviceScanRetryDelayMutex);
+    oc_cond_signal(g_deviceScanRetryDelayCond);
+    oc_mutex_unlock(g_deviceScanRetryDelayMutex);
 
-    ca_mutex_lock(g_threadScanIntervalMutex);
+    oc_mutex_lock(g_threadScanIntervalMutex);
     OIC_LOG(DEBUG, TAG, "signal - delay cond");
-    ca_cond_signal(g_threadScanIntervalCond);
-    ca_mutex_unlock(g_threadScanIntervalMutex);
+    oc_cond_signal(g_threadScanIntervalCond);
+    oc_mutex_unlock(g_threadScanIntervalMutex);
 
-    ca_cond_free(g_deviceDescCond);
-    ca_cond_free(g_threadCond);
-    ca_cond_free(g_threadWriteCharacteristicCond);
-    ca_cond_free(g_deviceScanRetryDelayCond);
-    ca_cond_free(g_threadScanIntervalCond);
+    oc_cond_free(g_deviceDescCond);
+    oc_cond_free(g_threadCond);
+    oc_cond_free(g_threadWriteCharacteristicCond);
+    oc_cond_free(g_deviceScanRetryDelayCond);
+    oc_cond_free(g_threadScanIntervalCond);
 
     g_deviceDescCond = NULL;
     g_threadCond = NULL;
@@ -4118,9 +4121,9 @@ CAResult_t CAUpdateCharacteristicsToAllGattServers(const uint8_t *data, uint32_t
 
 void CASetLEReqRespClientCallback(CABLEDataReceivedCallback callback)
 {
-    ca_mutex_lock(g_bleReqRespClientCbMutex);
+    oc_mutex_lock(g_bleReqRespClientCbMutex);
     g_CABLEClientDataReceivedCallback = callback;
-    ca_mutex_unlock(g_bleReqRespClientCbMutex);
+    oc_mutex_unlock(g_bleReqRespClientCbMutex);
 }
 
 void CASetLEClientThreadPoolHandle(ca_thread_pool_t handle)
@@ -4440,10 +4443,10 @@ Java_org_iotivity_ca_CaLeClientInterface_caLeGattCharacteristicWriteCallback(
         if (CA_STATUS_OK != res)
         {
             OIC_LOG(ERROR, TAG, "WriteCharacteristic has failed");
-            ca_mutex_lock(g_threadWriteCharacteristicMutex);
+            oc_mutex_lock(g_threadWriteCharacteristicMutex);
             g_isSignalSetFlag = true;
-            ca_cond_signal(g_threadWriteCharacteristicCond);
-            ca_mutex_unlock(g_threadWriteCharacteristicMutex);
+            oc_cond_signal(g_threadWriteCharacteristicCond);
+            oc_mutex_unlock(g_threadWriteCharacteristicMutex);
 
             CAResult_t res = CALEClientUpdateDeviceState(address, CA_LE_SEND_STATE,
                                                          STATE_SEND_FAIL);
@@ -4472,13 +4475,11 @@ Java_org_iotivity_ca_CaLeClientInterface_caLeGattCharacteristicWriteCallback(
             OIC_LOG(ERROR, TAG, "CALEClientUpdateDeviceState has failed");
         }
 
-        ca_mutex_lock(g_threadWriteCharacteristicMutex);
+        oc_mutex_lock(g_threadWriteCharacteristicMutex);
         OIC_LOG(DEBUG, TAG, "g_isSignalSetFlag is set true and signal");
         g_isSignalSetFlag = true;
-        ca_cond_signal(g_threadWriteCharacteristicCond);
-        ca_mutex_unlock(g_threadWriteCharacteristicMutex);
-
-        CALEClientUpdateSendCnt(env);
+        oc_cond_signal(g_threadWriteCharacteristicCond);
+        oc_mutex_unlock(g_threadWriteCharacteristicMutex);
     }
 
     (*env)->ReleaseStringUTFChars(env, jni_address, address);
@@ -4545,9 +4546,9 @@ Java_org_iotivity_ca_CaLeClientInterface_caLeGattCharacteristicChangedCallback(
               receivedData, length);
 
     uint32_t sentLength = 0;
-    ca_mutex_lock(g_bleServerBDAddressMutex);
+    oc_mutex_lock(g_bleServerBDAddressMutex);
     g_CABLEClientDataReceivedCallback(address, receivedData, length, &sentLength);
-    ca_mutex_unlock(g_bleServerBDAddressMutex);
+    oc_mutex_unlock(g_bleServerBDAddressMutex);
 
     (*env)->ReleaseStringUTFChars(env, jni_address, address);
 }
index 4a65ed2..694e651 100644 (file)
@@ -29,7 +29,7 @@
 #include "caleinterface.h"
 #include "caadapterutils.h"
 
-#include "camutex.h"
+#include "octhread.h"
 
 #include "org_iotivity_ca_CaLeClientInterface.h"
 #include "org_iotivity_ca_CaLeServerInterface.h"
@@ -57,14 +57,14 @@ static CALEConnectionStateChangedCallback g_bleConnectionStateChangedCallback =
  * @brief Mutex to synchronize access to the deviceStateChanged Callback when the state
  *           of the LE adapter gets change.
  */
-static ca_mutex g_bleDeviceStateChangedCbMutex = NULL;
+static oc_mutex g_bleDeviceStateChangedCbMutex = NULL;
 
 /**
  * @var g_bleConnectionStateChangedCbMutex
  * @brief Mutex to synchronize access to the LE ConnectionStateChanged Callback when the state
  *           of the LE adapter gets change.
  */
-static ca_mutex g_bleConnectionStateChangedCbMutex = NULL;
+static oc_mutex g_bleConnectionStateChangedCbMutex = NULL;
 
 //getting context
 void CALENetworkMonitorJNISetContext()
@@ -111,21 +111,21 @@ CAResult_t CAInitLENwkMonitorMutexVaraibles()
     OIC_LOG(DEBUG, TAG, "IN");
     if (NULL == g_bleDeviceStateChangedCbMutex)
     {
-        g_bleDeviceStateChangedCbMutex = ca_mutex_new();
+        g_bleDeviceStateChangedCbMutex = oc_mutex_new();
         if (NULL == g_bleDeviceStateChangedCbMutex)
         {
-            OIC_LOG(ERROR, TAG, "ca_mutex_new has failed");
+            OIC_LOG(ERROR, TAG, "oc_mutex_new has failed");
             return CA_STATUS_FAILED;
         }
     }
 
     if (NULL == g_bleConnectionStateChangedCbMutex)
     {
-       g_bleConnectionStateChangedCbMutex = ca_mutex_new();
+       g_bleConnectionStateChangedCbMutex = oc_mutex_new();
         if (NULL == g_bleConnectionStateChangedCbMutex)
         {
-            OIC_LOG(ERROR, TAG, "ca_mutex_new has failed");
-            ca_mutex_free(g_bleDeviceStateChangedCbMutex);
+            OIC_LOG(ERROR, TAG, "oc_mutex_new has failed");
+            oc_mutex_free(g_bleDeviceStateChangedCbMutex);
             return CA_STATUS_FAILED;
         }
     }
@@ -138,10 +138,10 @@ void CATerminateLENwkMonitorMutexVaraibles()
 {
     OIC_LOG(DEBUG, TAG, "IN");
 
-    ca_mutex_free(g_bleDeviceStateChangedCbMutex);
+    oc_mutex_free(g_bleDeviceStateChangedCbMutex);
     g_bleDeviceStateChangedCbMutex = NULL;
 
-    ca_mutex_free(g_bleConnectionStateChangedCbMutex);
+    oc_mutex_free(g_bleConnectionStateChangedCbMutex);
     g_bleConnectionStateChangedCbMutex = NULL;
 
     OIC_LOG(DEBUG, TAG, "OUT");
@@ -227,9 +227,9 @@ CAResult_t CASetLEAdapterStateChangedCb(CALEDeviceStateChangedCallback callback)
 
     OIC_LOG(DEBUG, TAG, "Setting CALEDeviceStateChangedCallback");
 
-    ca_mutex_lock(g_bleDeviceStateChangedCbMutex);
+    oc_mutex_lock(g_bleDeviceStateChangedCbMutex);
     CALESetAdapterStateCallback(callback);
-    ca_mutex_unlock(g_bleDeviceStateChangedCbMutex);
+    oc_mutex_unlock(g_bleDeviceStateChangedCbMutex);
 
     OIC_LOG(DEBUG, TAG, "OUT");
     return CA_STATUS_OK;
@@ -244,9 +244,9 @@ CAResult_t CAUnSetLEAdapterStateChangedCb()
 CAResult_t CASetLENWConnectionStateChangedCb(CALEConnectionStateChangedCallback callback)
 {
     OIC_LOG(DEBUG, TAG, "IN");
-    ca_mutex_lock(g_bleConnectionStateChangedCbMutex);
+    oc_mutex_lock(g_bleConnectionStateChangedCbMutex);
     g_bleConnectionStateChangedCallback = callback;
-    ca_mutex_unlock(g_bleConnectionStateChangedCbMutex);
+    oc_mutex_unlock(g_bleConnectionStateChangedCbMutex);
     OIC_LOG(DEBUG, TAG, "OUT");
     return CA_STATUS_OK;
 }
@@ -254,9 +254,9 @@ CAResult_t CASetLENWConnectionStateChangedCb(CALEConnectionStateChangedCallback
 CAResult_t CAUnsetLENWConnectionStateChangedCb()
 {
     OIC_LOG(DEBUG, TAG, "IN");
-    ca_mutex_lock(g_bleConnectionStateChangedCbMutex);
+    oc_mutex_lock(g_bleConnectionStateChangedCbMutex);
     g_bleConnectionStateChangedCallback = NULL;
-    ca_mutex_unlock(g_bleConnectionStateChangedCbMutex);
+    oc_mutex_unlock(g_bleConnectionStateChangedCbMutex);
     OIC_LOG(DEBUG, TAG, "OUT");
     return CA_STATUS_OK;
 }
index b722c01..4f0cafc 100644 (file)
@@ -31,7 +31,7 @@
 #include "logger.h"
 #include "oic_malloc.h"
 #include "cathreadpool.h"
-#include "camutex.h"
+#include "octhread.h"
 #include "uarraylist.h"
 #include "org_iotivity_ca_CaLeServerInterface.h"
 
@@ -59,13 +59,13 @@ static jbyteArray g_sendBuffer = NULL;
 static jobject g_obj_bluetoothDevice = NULL;
 
 static CABLEDataReceivedCallback g_CABLEServerDataReceivedCallback = NULL;
-static ca_mutex g_bleReqRespCbMutex = NULL;
-static ca_mutex g_bleClientBDAddressMutex = NULL;
-static ca_mutex g_connectedDeviceListMutex = NULL;
+static oc_mutex g_bleReqRespCbMutex = NULL;
+static oc_mutex g_bleClientBDAddressMutex = NULL;
+static oc_mutex g_connectedDeviceListMutex = NULL;
 
-static ca_mutex g_threadSendMutex = NULL;
-static ca_mutex g_threadSendNotifyMutex = NULL;
-static ca_cond g_threadSendNotifyCond = NULL;
+static oc_mutex g_threadSendMutex = NULL;
+static oc_mutex g_threadSendNotifyMutex = NULL;
+static oc_cond g_threadSendNotifyCond = NULL;
 static bool g_isSignalSetFlag = false;
 
 static jint g_state_connected = INVALID_STATE;
@@ -333,21 +333,21 @@ CAResult_t CALEServerSendResponseData(JNIEnv *env, jobject device, jobject respo
     }
 
     OIC_LOG_V(DEBUG, TAG, "callback flag is %d", g_isSignalSetFlag);
-    ca_mutex_lock(g_threadSendNotifyMutex);
+    oc_mutex_lock(g_threadSendNotifyMutex);
     if (!g_isSignalSetFlag)
     {
         OIC_LOG(DEBUG, TAG, "wait for callback to notify notifyCharacteristic is success");
-        if (0 != ca_cond_wait_for(g_threadSendNotifyCond, g_threadSendNotifyMutex,
+        if (0 != oc_cond_wait_for(g_threadSendNotifyCond, g_threadSendNotifyMutex,
                                   WAIT_TIME_WRITE_CHARACTERISTIC))
         {
             OIC_LOG(ERROR, TAG, "there is no response. notifyCharacteristic has failed");
-            ca_mutex_unlock(g_threadSendNotifyMutex);
+            oc_mutex_unlock(g_threadSendNotifyMutex);
             return CA_STATUS_FAILED;
         }
     }
     // reset flag set by writeCharacteristic Callback
     g_isSignalSetFlag = false;
-    ca_mutex_unlock(g_threadSendNotifyMutex);
+    oc_mutex_unlock(g_threadSendNotifyMutex);
     OIC_LOG(INFO, TAG, "notifyCharacteristic success");
     return CA_STATUS_OK;
 }
@@ -1309,11 +1309,11 @@ CAResult_t CALEServerDisconnectAllDevices(JNIEnv *env)
     OIC_LOG(DEBUG, TAG, "IN - CALEServerDisconnectAllDevices");
     VERIFY_NON_NULL(env, TAG, "env is null");
 
-    ca_mutex_lock(g_connectedDeviceListMutex);
+    oc_mutex_lock(g_connectedDeviceListMutex);
     if (!g_connectedDeviceList)
     {
         OIC_LOG(ERROR, TAG, "g_connectedDeviceList is null");
-        ca_mutex_unlock(g_connectedDeviceListMutex);
+        oc_mutex_unlock(g_connectedDeviceListMutex);
         return CA_STATUS_FAILED;
     }
 
@@ -1336,7 +1336,7 @@ CAResult_t CALEServerDisconnectAllDevices(JNIEnv *env)
         }
     }
 
-    ca_mutex_unlock(g_connectedDeviceListMutex);
+    oc_mutex_unlock(g_connectedDeviceListMutex);
     OIC_LOG(DEBUG, TAG, "OUT - CALEServerDisconnectAllDevices");
     return CA_STATUS_OK;
 }
@@ -1480,7 +1480,7 @@ CAResult_t CALEServerInitialize()
         return ret;
     }
 
-    g_threadSendNotifyCond = ca_cond_new();
+    g_threadSendNotifyCond = oc_cond_new();
 
     ret = CALEServerInitMutexVaraibles();
     if (CA_STATUS_OK != ret)
@@ -1557,7 +1557,7 @@ void CALEServerTerminate()
         g_bluetoothManager = NULL;
     }
 
-    ca_cond_free(g_threadSendNotifyCond);
+    oc_cond_free(g_threadSendNotifyCond);
     g_threadSendNotifyCond = NULL;
 
     CALEServerTerminateMutexVaraibles();
@@ -1794,7 +1794,7 @@ CAResult_t CALEServerSendUnicastMessageImpl(JNIEnv *env, const char* address, co
         return CA_STATUS_FAILED;
     }
 
-    ca_mutex_lock(g_threadSendMutex);
+    oc_mutex_lock(g_threadSendMutex);
 
     uint32_t length = u_arraylist_length(g_connectedDeviceList);
     for (uint32_t index = 0; index < length; index++)
@@ -1868,7 +1868,7 @@ CAResult_t CALEServerSendUnicastMessageImpl(JNIEnv *env, const char* address, co
         g_sendBuffer = NULL;
     }
 
-    ca_mutex_unlock(g_threadSendMutex);
+    oc_mutex_unlock(g_threadSendMutex);
     OIC_LOG(INFO, TAG, "unicast - send request is successful");
     return CA_STATUS_OK;
 
@@ -1885,7 +1885,7 @@ error_exit:
         g_obj_bluetoothDevice = NULL;
     }
 
-    ca_mutex_unlock(g_threadSendMutex);
+    oc_mutex_unlock(g_threadSendMutex);
     return CA_SEND_FAILED;
 }
 
@@ -1901,7 +1901,7 @@ CAResult_t CALEServerSendMulticastMessageImpl(JNIEnv *env, const uint8_t *data,
         return CA_STATUS_FAILED;
     }
 
-    ca_mutex_lock(g_threadSendMutex);
+    oc_mutex_lock(g_threadSendMutex);
 
     OIC_LOG(DEBUG, TAG, "set data into g_sendBuffer for notify");
     if (g_sendBuffer)
@@ -1975,20 +1975,20 @@ CAResult_t CALEServerSendMulticastMessageImpl(JNIEnv *env, const uint8_t *data,
         g_sendBuffer = NULL;
     }
 
-    ca_mutex_unlock(g_threadSendMutex);
+    oc_mutex_unlock(g_threadSendMutex);
     return CA_STATUS_OK;
 }
 
 void CALEServerCreateCachedDeviceList()
 {
-    ca_mutex_lock(g_connectedDeviceListMutex);
+    oc_mutex_lock(g_connectedDeviceListMutex);
     // create new object array
     if (!g_connectedDeviceList)
     {
         OIC_LOG(DEBUG, TAG, "Create device list");
         g_connectedDeviceList = u_arraylist_create();
     }
-    ca_mutex_unlock(g_connectedDeviceListMutex);
+    oc_mutex_unlock(g_connectedDeviceListMutex);
 }
 
 bool CALEServerIsDeviceInList(JNIEnv *env, const char* remoteAddress)
@@ -2050,12 +2050,12 @@ CAResult_t CALEServerAddDeviceToList(JNIEnv *env, jobject device)
     VERIFY_NON_NULL(device, TAG, "device is null");
     VERIFY_NON_NULL(env, TAG, "env is null");
 
-    ca_mutex_lock(g_connectedDeviceListMutex);
+    oc_mutex_lock(g_connectedDeviceListMutex);
 
     if (!g_connectedDeviceList)
     {
         OIC_LOG(ERROR, TAG, "list is null");
-        ca_mutex_unlock(g_connectedDeviceListMutex);
+        oc_mutex_unlock(g_connectedDeviceListMutex);
         return CA_STATUS_FAILED;
     }
 
@@ -2063,7 +2063,7 @@ CAResult_t CALEServerAddDeviceToList(JNIEnv *env, jobject device)
     if (!jni_remoteAddress)
     {
         OIC_LOG(ERROR, TAG, "jni_remoteAddress is null");
-        ca_mutex_unlock(g_connectedDeviceListMutex);
+        oc_mutex_unlock(g_connectedDeviceListMutex);
         return CA_STATUS_FAILED;
     }
 
@@ -2071,7 +2071,7 @@ CAResult_t CALEServerAddDeviceToList(JNIEnv *env, jobject device)
     if (!remoteAddress)
     {
         OIC_LOG(ERROR, TAG, "remoteAddress is null");
-        ca_mutex_unlock(g_connectedDeviceListMutex);
+        oc_mutex_unlock(g_connectedDeviceListMutex);
         return CA_STATUS_FAILED;
     }
 
@@ -2083,7 +2083,7 @@ CAResult_t CALEServerAddDeviceToList(JNIEnv *env, jobject device)
     }
 
     (*env)->ReleaseStringUTFChars(env, jni_remoteAddress, remoteAddress);
-    ca_mutex_unlock(g_connectedDeviceListMutex);
+    oc_mutex_unlock(g_connectedDeviceListMutex);
     OIC_LOG(DEBUG, TAG, "OUT - CALEServerAddDeviceToList");
     return CA_STATUS_OK;
 }
@@ -2093,11 +2093,11 @@ CAResult_t CALEServerRemoveAllDevices(JNIEnv *env)
     OIC_LOG(DEBUG, TAG, "IN - CALEServerRemoveAllDevices");
     VERIFY_NON_NULL(env, TAG, "env is null");
 
-    ca_mutex_lock(g_connectedDeviceListMutex);
+    oc_mutex_lock(g_connectedDeviceListMutex);
     if (!g_connectedDeviceList)
     {
         OIC_LOG(ERROR, TAG, "g_connectedDeviceList is null");
-        ca_mutex_unlock(g_connectedDeviceListMutex);
+        oc_mutex_unlock(g_connectedDeviceListMutex);
         return CA_STATUS_FAILED;
     }
 
@@ -2113,7 +2113,7 @@ CAResult_t CALEServerRemoveAllDevices(JNIEnv *env)
 
     OICFree(g_connectedDeviceList);
     g_connectedDeviceList = NULL;
-    ca_mutex_unlock(g_connectedDeviceListMutex);
+    oc_mutex_unlock(g_connectedDeviceListMutex);
 
     OIC_LOG(DEBUG, TAG, "OUT - CALEServerRemoveAllDevices");
     return CA_STATUS_OK;
@@ -2125,11 +2125,11 @@ CAResult_t CALEServerRemoveDevice(JNIEnv *env, jstring address)
     VERIFY_NON_NULL(env, TAG, "env is null");
     VERIFY_NON_NULL(address, TAG, "address is null");
 
-    ca_mutex_lock(g_connectedDeviceListMutex);
+    oc_mutex_lock(g_connectedDeviceListMutex);
     if (!g_connectedDeviceList)
     {
         OIC_LOG(ERROR, TAG, "no deviceList");
-        ca_mutex_unlock(g_connectedDeviceListMutex);
+        oc_mutex_unlock(g_connectedDeviceListMutex);
         return CA_STATUS_FAILED;
     }
 
@@ -2173,10 +2173,10 @@ CAResult_t CALEServerRemoveDevice(JNIEnv *env, jstring address)
                 if (NULL == u_arraylist_remove(g_connectedDeviceList, index))
                 {
                     OIC_LOG(ERROR, TAG, "List removal failed.");
-                    ca_mutex_unlock(g_connectedDeviceListMutex);
+                    oc_mutex_unlock(g_connectedDeviceListMutex);
                     return CA_STATUS_FAILED;
                 }
-                ca_mutex_unlock(g_connectedDeviceListMutex);
+                oc_mutex_unlock(g_connectedDeviceListMutex);
                 return CA_STATUS_OK;
             }
             (*env)->ReleaseStringUTFChars(env, jni_setAddress, setAddress);
@@ -2184,7 +2184,7 @@ CAResult_t CALEServerRemoveDevice(JNIEnv *env, jstring address)
         }
     }
 
-    ca_mutex_unlock(g_connectedDeviceListMutex);
+    oc_mutex_unlock(g_connectedDeviceListMutex);
 
     OIC_LOG(DEBUG, TAG, "there are no device in the device list");
 
@@ -2353,11 +2353,11 @@ Java_org_iotivity_ca_CaLeServerInterface_caLeGattServerCharacteristicWriteReques
 
     OIC_LOG_V(DEBUG, TAG, "remote device address : %s, %p, %d", address, requestData, length);
 
-    ca_mutex_lock(g_bleClientBDAddressMutex);
+    oc_mutex_lock(g_bleClientBDAddressMutex);
     uint32_t sentLength = 0;
     g_CABLEServerDataReceivedCallback(address, requestData, length,
                                       &sentLength);
-    ca_mutex_unlock(g_bleClientBDAddressMutex);
+    oc_mutex_unlock(g_bleClientBDAddressMutex);
 
     (*env)->ReleaseStringUTFChars(env, jni_address, address);
 }
@@ -2391,10 +2391,10 @@ Java_org_iotivity_ca_CaLeServerInterface_caLeGattServerNotificationSentCallback(
                 g_obj_bluetoothDevice = NULL;
             }
 
-            ca_mutex_lock(g_threadSendNotifyMutex);
+            oc_mutex_lock(g_threadSendNotifyMutex);
             g_isSignalSetFlag = true;
-            ca_cond_signal(g_threadSendNotifyCond);
-            ca_mutex_unlock(g_threadSendNotifyMutex);
+            oc_cond_signal(g_threadSendNotifyCond);
+            oc_mutex_unlock(g_threadSendNotifyMutex);
             return;
         }
     }
@@ -2409,11 +2409,11 @@ Java_org_iotivity_ca_CaLeServerInterface_caLeGattServerNotificationSentCallback(
         }
 
         // next data can be sent
-        ca_mutex_lock(g_threadSendNotifyMutex);
+        oc_mutex_lock(g_threadSendNotifyMutex);
         OIC_LOG(DEBUG, TAG, "g_isSignalSetFlag is set true and signal");
         g_isSignalSetFlag = true;
-        ca_cond_signal(g_threadSendNotifyCond);
-        ca_mutex_unlock(g_threadSendNotifyMutex);
+        oc_cond_signal(g_threadSendNotifyCond);
+        oc_mutex_unlock(g_threadSendNotifyMutex);
     }
 
 }
@@ -2542,9 +2542,9 @@ CAResult_t CAStopLEGattServer()
         g_obj_bluetoothDevice = NULL;
     }
 
-    ca_mutex_lock(g_threadSendNotifyMutex);
-    ca_cond_signal(g_threadSendNotifyCond);
-    ca_mutex_unlock(g_threadSendNotifyMutex);
+    oc_mutex_lock(g_threadSendNotifyMutex);
+    oc_cond_signal(g_threadSendNotifyCond);
+    oc_mutex_unlock(g_threadSendNotifyMutex);
 
     g_isStartServer = false;
 
@@ -2570,9 +2570,9 @@ void CATerminateLEGattServer()
 
 void CASetLEReqRespServerCallback(CABLEDataReceivedCallback callback)
 {
-    ca_mutex_lock(g_bleReqRespCbMutex);
+    oc_mutex_lock(g_bleReqRespCbMutex);
     g_CABLEServerDataReceivedCallback = callback;
-    ca_mutex_unlock(g_bleReqRespCbMutex);
+    oc_mutex_unlock(g_bleReqRespCbMutex);
 }
 
 void CASetBLEServerErrorHandleCallback(CABLEErrorHandleCallback callback)
@@ -2616,50 +2616,50 @@ CAResult_t CALEServerInitMutexVaraibles()
 {
     if (NULL == g_bleReqRespCbMutex)
     {
-        g_bleReqRespCbMutex = ca_mutex_new();
+        g_bleReqRespCbMutex = oc_mutex_new();
         if (NULL == g_bleReqRespCbMutex)
         {
-            OIC_LOG(ERROR, TAG, "ca_mutex_new has failed");
+            OIC_LOG(ERROR, TAG, "oc_mutex_new has failed");
             return CA_STATUS_FAILED;
         }
     }
 
     if (NULL == g_bleClientBDAddressMutex)
     {
-        g_bleClientBDAddressMutex = ca_mutex_new();
+        g_bleClientBDAddressMutex = oc_mutex_new();
         if (NULL == g_bleClientBDAddressMutex)
         {
-            OIC_LOG(ERROR, TAG, "ca_mutex_new has failed");
+            OIC_LOG(ERROR, TAG, "oc_mutex_new has failed");
             return CA_STATUS_FAILED;
         }
     }
 
     if (NULL == g_connectedDeviceListMutex)
     {
-        g_connectedDeviceListMutex = ca_mutex_new();
+        g_connectedDeviceListMutex = oc_mutex_new();
         if (NULL == g_connectedDeviceListMutex)
         {
-            OIC_LOG(ERROR, TAG, "ca_mutex_new has failed");
+            OIC_LOG(ERROR, TAG, "oc_mutex_new has failed");
             return CA_STATUS_FAILED;
         }
     }
 
     if (NULL == g_threadSendMutex)
     {
-        g_threadSendMutex = ca_mutex_new();
+        g_threadSendMutex = oc_mutex_new();
         if (NULL == g_threadSendMutex)
         {
-            OIC_LOG(ERROR, TAG, "ca_mutex_new has failed");
+            OIC_LOG(ERROR, TAG, "oc_mutex_new has failed");
             return CA_STATUS_FAILED;
         }
     }
 
     if (NULL == g_threadSendNotifyMutex)
     {
-        g_threadSendNotifyMutex = ca_mutex_new();
+        g_threadSendNotifyMutex = oc_mutex_new();
         if (NULL == g_threadSendNotifyMutex)
         {
-            OIC_LOG(ERROR, TAG, "ca_mutex_new has failed");
+            OIC_LOG(ERROR, TAG, "oc_mutex_new has failed");
             return CA_STATUS_FAILED;
         }
     }
@@ -2669,19 +2669,19 @@ CAResult_t CALEServerInitMutexVaraibles()
 
 void CALEServerTerminateMutexVaraibles()
 {
-    ca_mutex_free(g_bleReqRespCbMutex);
+    oc_mutex_free(g_bleReqRespCbMutex);
     g_bleReqRespCbMutex = NULL;
 
-    ca_mutex_free(g_bleClientBDAddressMutex);
+    oc_mutex_free(g_bleClientBDAddressMutex);
     g_bleClientBDAddressMutex = NULL;
 
-    ca_mutex_free(g_connectedDeviceListMutex);
+    oc_mutex_free(g_connectedDeviceListMutex);
     g_connectedDeviceListMutex = NULL;
 
-    ca_mutex_free(g_threadSendMutex);
+    oc_mutex_free(g_threadSendMutex);
     g_threadSendMutex = NULL;
 
-    ca_mutex_free(g_threadSendNotifyMutex);
+    oc_mutex_free(g_threadSendNotifyMutex);
     g_threadSendNotifyMutex = NULL;
 }
 
index e7706f1..c16186b 100644 (file)
@@ -29,7 +29,7 @@
 #include <boards.h>
 #include <RBL_nRF8001.h>
 
-#include "pdu.h"
+#include <coap/pdu.h>
 #include "caleinterface.h"
 #include "oic_malloc.h"
 #include "caadapterutils.h"
@@ -68,7 +68,7 @@ static size_t g_packetDataLen = 0;
 
 void CAGetTCPHeaderDetails(unsigned char* recvBuffer, size_t *headerlen)
 {
-    coap_transport_type transport = coap_get_tcp_header_type_from_initbyte(
+    coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(
         ((unsigned char *)recvBuffer)[0] >> 4);
     *headerlen = coap_get_tcp_header_length_for_transport(transport);
 }
@@ -90,7 +90,7 @@ void CACheckLEDataInternal()
                 return;
             }
 
-            while (CAIsLEDataAvailable())
+            while (CAIsLEDataAvailable() && g_receivedDataLen <= bufSize)
             {
                 g_coapBuffer[g_receivedDataLen++] = CALEReadData();
             }
index e459eb0..abce764 100644 (file)
@@ -26,7 +26,7 @@
 
 #include "caleinterface.h"
 #include "cacommon.h"
-#include "camutex.h"
+#include "octhread.h"
 #include "caadapterutils.h"
 #ifndef SINGLE_THREAD
 #include "caqueueingthread.h"
@@ -38,7 +38,7 @@
 #include "oic_malloc.h"
 #include "oic_string.h"
 #include "caremotehandler.h"
-#include "pdu.h"
+#include <coap/pdu.h>
 
 /**
  * Logging tag for module name.
@@ -97,19 +97,19 @@ static CABLEAdapter_t g_adapterType = ADAPTER_EMPTY;
  * Mutex to synchronize the task to be executed on the GattServer
  * function calls.
  */
-static ca_mutex g_bleIsServerMutex = NULL;
+static oc_mutex g_bleIsServerMutex = NULL;
 
 /**
  * Mutex to synchronize the callback to be called for the network
  * changes.
  */
-static ca_mutex g_bleNetworkCbMutex = NULL;
+static oc_mutex g_bleNetworkCbMutex = NULL;
 
 /**
  * Mutex to synchronize the updates of the local LE address of the
  * adapter.
  */
-static ca_mutex g_bleLocalAddressMutex = NULL;
+static oc_mutex g_bleLocalAddressMutex = NULL;
 
 /**
  * Reference to thread pool.
@@ -119,28 +119,28 @@ static ca_thread_pool_t g_bleAdapterThreadPool = NULL;
 /**
  * Mutex to synchronize the task to be pushed to thread pool.
  */
-static ca_mutex g_bleAdapterThreadPoolMutex = NULL;
+static oc_mutex g_bleAdapterThreadPoolMutex = NULL;
 
 /**
  * Mutex to synchronize the queing of the data from SenderQueue.
  */
-static ca_mutex g_bleClientSendDataMutex = NULL;
+static oc_mutex g_bleClientSendDataMutex = NULL;
 
 /**
  * Mutex to synchronize the queing of the data from ReceiverQueue.
  */
-static ca_mutex g_bleReceiveDataMutex = NULL;
+static oc_mutex g_bleReceiveDataMutex = NULL;
 
 /**
  * Mutex to synchronize the queing of the data from SenderQueue.
  */
-static ca_mutex g_bleServerSendDataMutex = NULL;
+static oc_mutex g_bleServerSendDataMutex = NULL;
 
 /**
  * Mutex to synchronize the callback to be called for the
  * adapterReqResponse.
  */
-static ca_mutex g_bleAdapterReqRespCbMutex = NULL;
+static oc_mutex g_bleAdapterReqRespCbMutex = NULL;
 
 /**
  * Callback to be called when network packet received from either
@@ -449,7 +449,7 @@ static void CALEDataDestroyer(void *data, uint32_t size);
  * @param[in] address        target address to remove data in queue.
  */
 static void CALERemoveSendQueueData(CAQueueingThread_t *queueHandle,
-                                    ca_mutex mutex,
+                                    oc_mutex mutex,
                                     const char* address);
 
 /**
@@ -497,13 +497,13 @@ static CAResult_t CAInitLEServerQueues()
 {
     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
 
-    ca_mutex_lock(g_bleAdapterThreadPoolMutex);
+    oc_mutex_lock(g_bleAdapterThreadPoolMutex);
 
     CAResult_t result = CAInitLEServerSenderQueue();
     if (CA_STATUS_OK != result)
     {
         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleServerSenderQueue failed");
-        ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
+        oc_mutex_unlock(g_bleAdapterThreadPoolMutex);
         return CA_STATUS_FAILED;
     }
 
@@ -511,7 +511,7 @@ static CAResult_t CAInitLEServerQueues()
     if (!g_bleServerSenderInfo)
     {
         OIC_LOG(ERROR, CALEADAPTER_TAG, "memory allocation failed!");
-        ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
+        oc_mutex_unlock(g_bleAdapterThreadPoolMutex);
         return CA_MEMORY_ALLOC_FAILED;
     }
 
@@ -520,13 +520,13 @@ static CAResult_t CAInitLEServerQueues()
     {
         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEReceiverQueue failed");
         u_arraylist_free(&g_bleServerSenderInfo);
-        ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
+        oc_mutex_unlock(g_bleAdapterThreadPoolMutex);
         return CA_STATUS_FAILED;
     }
 
     g_dataBleReceiverHandlerState = true;
 
-    ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
+    oc_mutex_unlock(g_bleAdapterThreadPoolMutex);
 
     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
     return CA_STATUS_OK;
@@ -536,13 +536,13 @@ static CAResult_t CAInitLEClientQueues()
 {
     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
 
-    ca_mutex_lock(g_bleAdapterThreadPoolMutex);
+    oc_mutex_lock(g_bleAdapterThreadPoolMutex);
 
     CAResult_t result = CAInitLEClientSenderQueue();
     if (CA_STATUS_OK != result)
     {
         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleClientSenderQueue failed");
-        ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
+        oc_mutex_unlock(g_bleAdapterThreadPoolMutex);
         return CA_STATUS_FAILED;
     }
 
@@ -550,7 +550,7 @@ static CAResult_t CAInitLEClientQueues()
     if (!g_bleClientSenderInfo)
     {
         OIC_LOG(ERROR, CALEADAPTER_TAG, "memory allocation failed!");
-        ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
+        oc_mutex_unlock(g_bleAdapterThreadPoolMutex);
         return CA_MEMORY_ALLOC_FAILED;
     }
 
@@ -559,13 +559,13 @@ static CAResult_t CAInitLEClientQueues()
     {
         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEReceiverQueue failed");
         u_arraylist_free(&g_bleClientSenderInfo);
-        ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
+        oc_mutex_unlock(g_bleAdapterThreadPoolMutex);
         return CA_STATUS_FAILED;
     }
 
     g_dataBleReceiverHandlerState = true;
 
-    ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
+    oc_mutex_unlock(g_bleAdapterThreadPoolMutex);
 
     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
     return CA_STATUS_OK;
@@ -704,12 +704,12 @@ static void CAStopLEQueues()
 {
     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CAStopLEQueues");
 
-    ca_mutex_lock(g_bleReceiveDataMutex);
+    oc_mutex_lock(g_bleReceiveDataMutex);
     if (NULL != g_bleReceiverQueue)
     {
         CAQueueingThreadStop(g_bleReceiverQueue);
     }
-    ca_mutex_unlock(g_bleReceiveDataMutex);
+    oc_mutex_unlock(g_bleReceiveDataMutex);
 
     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT - CAStopLEQueues");
 }
@@ -781,7 +781,7 @@ static void CALEDataReceiverHandler(void *threadData)
 {
     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CALEDataReceiverHandler");
 
-    ca_mutex_lock(g_bleReceiveDataMutex);
+    oc_mutex_lock(g_bleReceiveDataMutex);
 
     if (g_dataBleReceiverHandlerState)
     {
@@ -791,21 +791,21 @@ static void CALEDataReceiverHandler(void *threadData)
         if (!bleData)
         {
             OIC_LOG(DEBUG, CALEADAPTER_TAG, "Invalid bleData!");
-            ca_mutex_unlock(g_bleReceiveDataMutex);
+            oc_mutex_unlock(g_bleReceiveDataMutex);
             return;
         }
 
         if (!(bleData->senderInfo))
         {
             OIC_LOG(ERROR, CALEADAPTER_TAG, "sender info is not available");
-            ca_mutex_unlock(g_bleReceiveDataMutex);
+            oc_mutex_unlock(g_bleReceiveDataMutex);
             return;
         }
 
         if (!(bleData->remoteEndpoint))
         {
             OIC_LOG(ERROR, CALEADAPTER_TAG, "Client RemoteEndPoint NULL!!");
-            ca_mutex_unlock(g_bleReceiveDataMutex);
+            oc_mutex_unlock(g_bleReceiveDataMutex);
             return;
         }
 
@@ -828,7 +828,7 @@ static void CALEDataReceiverHandler(void *threadData)
             OIC_LOG_V(ERROR, CALEADAPTER_TAG,
                       "this packet is not valid for this app(port mismatch[mine:%d, packet:%d])",
                       g_localBLESourcePort, destPort);
-            ca_mutex_unlock(g_bleReceiveDataMutex);
+            oc_mutex_unlock(g_bleReceiveDataMutex);
             return;
         }
 
@@ -866,7 +866,7 @@ static void CALEDataReceiverHandler(void *threadData)
             else
             {
                 OIC_LOG(ERROR, CALEADAPTER_TAG, "This packet is wrong packet! ignore.");
-                ca_mutex_unlock(g_bleReceiveDataMutex);
+                oc_mutex_unlock(g_bleReceiveDataMutex);
                 return;
             }
 
@@ -874,7 +874,7 @@ static void CALEDataReceiverHandler(void *threadData)
             if (!newSender)
             {
                 OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed for new sender");
-                ca_mutex_unlock(g_bleReceiveDataMutex);
+                oc_mutex_unlock(g_bleReceiveDataMutex);
                 return;
             }
             newSender->recvDataLen = 0;
@@ -890,7 +890,7 @@ static void CALEDataReceiverHandler(void *threadData)
             {
                 OIC_LOG(ERROR, CALEADAPTER_TAG, "Total Data Length is parsed as 0!!!");
                 OICFree(newSender);
-                ca_mutex_unlock(g_bleReceiveDataMutex);
+                oc_mutex_unlock(g_bleReceiveDataMutex);
                 return;
             }
 
@@ -908,7 +908,7 @@ static void CALEDataReceiverHandler(void *threadData)
             {
                 OIC_LOG(ERROR, CALEADAPTER_TAG, "defragData is NULL!");
                 OICFree(newSender);
-                ca_mutex_unlock(g_bleReceiveDataMutex);
+                oc_mutex_unlock(g_bleReceiveDataMutex);
                 return;
             }
 
@@ -923,7 +923,7 @@ static void CALEDataReceiverHandler(void *threadData)
                 OIC_LOG(ERROR, CALEADAPTER_TAG, "remoteEndpoint is NULL!");
                 OICFree(newSender->defragData);
                 OICFree(newSender);
-                ca_mutex_unlock(g_bleReceiveDataMutex);
+                oc_mutex_unlock(g_bleReceiveDataMutex);
                 return;
             }
 
@@ -933,7 +933,7 @@ static void CALEDataReceiverHandler(void *threadData)
                 OICFree(newSender->defragData);
                 CAFreeEndpoint(newSender->remoteEndpoint);
                 OICFree(newSender);
-                ca_mutex_unlock(g_bleReceiveDataMutex);
+                oc_mutex_unlock(g_bleReceiveDataMutex);
                 return;
             }
             memcpy(newSender->defragData,
@@ -954,7 +954,7 @@ static void CALEDataReceiverHandler(void *threadData)
                 OICFree(newSender->defragData);
                 CAFreeEndpoint(newSender->remoteEndpoint);
                 OICFree(newSender);
-                ca_mutex_unlock(g_bleReceiveDataMutex);
+                oc_mutex_unlock(g_bleReceiveDataMutex);
                 return;
             }
             senderInfo = newSender;
@@ -970,7 +970,7 @@ static void CALEDataReceiverHandler(void *threadData)
                 u_arraylist_remove(bleData->senderInfo, senderIndex);
                 OICFree(senderInfo->defragData);
                 OICFree(senderInfo);
-                ca_mutex_unlock(g_bleReceiveDataMutex);
+                oc_mutex_unlock(g_bleReceiveDataMutex);
                 return;
             }
             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Copying the data of length [%d]",
@@ -985,7 +985,7 @@ static void CALEDataReceiverHandler(void *threadData)
 
         if (senderInfo->totalDataLen == senderInfo->recvDataLen)
         {
-            ca_mutex_lock(g_bleAdapterReqRespCbMutex);
+            oc_mutex_lock(g_bleAdapterReqRespCbMutex);
             if (NULL == g_networkPacketReceivedCallback)
             {
                 OIC_LOG(ERROR, CALEADAPTER_TAG, "gReqRespCallback is NULL!");
@@ -993,8 +993,8 @@ static void CALEDataReceiverHandler(void *threadData)
                 u_arraylist_remove(bleData->senderInfo, senderIndex);
                 OICFree(senderInfo->defragData);
                 OICFree(senderInfo);
-                ca_mutex_unlock(g_bleAdapterReqRespCbMutex);
-                ca_mutex_unlock(g_bleReceiveDataMutex);
+                oc_mutex_unlock(g_bleAdapterReqRespCbMutex);
+                oc_mutex_unlock(g_bleReceiveDataMutex);
                 return;
             }
 
@@ -1008,14 +1008,14 @@ static void CALEDataReceiverHandler(void *threadData)
             g_networkPacketReceivedCallback(&tmp,
                                             senderInfo->defragData,
                                             senderInfo->recvDataLen);
-            ca_mutex_unlock(g_bleAdapterReqRespCbMutex);
+            oc_mutex_unlock(g_bleAdapterReqRespCbMutex);
             u_arraylist_remove(bleData->senderInfo, senderIndex);
             senderInfo->remoteEndpoint = NULL;
             senderInfo->defragData = NULL;
             OICFree(senderInfo);
         }
     }
-    ca_mutex_unlock(g_bleReceiveDataMutex);
+    oc_mutex_unlock(g_bleReceiveDataMutex);
     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
 }
 
@@ -2025,20 +2025,20 @@ static CAResult_t CAInitLEAdapterMutex()
 
     if (NULL == g_bleIsServerMutex)
     {
-        g_bleIsServerMutex = ca_mutex_new();
+        g_bleIsServerMutex = oc_mutex_new();
         if (NULL == g_bleIsServerMutex)
         {
-            OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
+            OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
             return CA_STATUS_FAILED;
         }
     }
 
     if (NULL == g_bleNetworkCbMutex)
     {
-        g_bleNetworkCbMutex = ca_mutex_new();
+        g_bleNetworkCbMutex = oc_mutex_new();
         if (NULL == g_bleNetworkCbMutex)
         {
-            OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
+            OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
             CATerminateLEAdapterMutex();
             return CA_STATUS_FAILED;
         }
@@ -2046,10 +2046,10 @@ static CAResult_t CAInitLEAdapterMutex()
 
     if (NULL == g_bleLocalAddressMutex)
     {
-        g_bleLocalAddressMutex = ca_mutex_new();
+        g_bleLocalAddressMutex = oc_mutex_new();
         if (NULL == g_bleLocalAddressMutex)
         {
-            OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
+            OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
             CATerminateLEAdapterMutex();
             return CA_STATUS_FAILED;
         }
@@ -2057,10 +2057,10 @@ static CAResult_t CAInitLEAdapterMutex()
 
     if (NULL == g_bleAdapterThreadPoolMutex)
     {
-        g_bleAdapterThreadPoolMutex = ca_mutex_new();
+        g_bleAdapterThreadPoolMutex = oc_mutex_new();
         if (NULL == g_bleAdapterThreadPoolMutex)
         {
-            OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
+            OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
             CATerminateLEAdapterMutex();
             return CA_STATUS_FAILED;
         }
@@ -2068,10 +2068,10 @@ static CAResult_t CAInitLEAdapterMutex()
 
     if (NULL == g_bleClientSendDataMutex)
     {
-        g_bleClientSendDataMutex = ca_mutex_new();
+        g_bleClientSendDataMutex = oc_mutex_new();
         if (NULL == g_bleClientSendDataMutex)
         {
-            OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
+            OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
             CATerminateLEAdapterMutex();
             return CA_STATUS_FAILED;
         }
@@ -2079,10 +2079,10 @@ static CAResult_t CAInitLEAdapterMutex()
 
     if (NULL == g_bleServerSendDataMutex)
     {
-        g_bleServerSendDataMutex = ca_mutex_new();
+        g_bleServerSendDataMutex = oc_mutex_new();
         if (NULL == g_bleServerSendDataMutex)
         {
-            OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
+            OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
             CATerminateLEAdapterMutex();
             return CA_STATUS_FAILED;
         }
@@ -2090,10 +2090,10 @@ static CAResult_t CAInitLEAdapterMutex()
 
     if (NULL == g_bleAdapterReqRespCbMutex)
     {
-        g_bleAdapterReqRespCbMutex = ca_mutex_new();
+        g_bleAdapterReqRespCbMutex = oc_mutex_new();
         if (NULL == g_bleAdapterReqRespCbMutex)
         {
-            OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
+            OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
             CATerminateLEAdapterMutex();
             return CA_STATUS_FAILED;
         }
@@ -2101,10 +2101,10 @@ static CAResult_t CAInitLEAdapterMutex()
 
     if (NULL == g_bleReceiveDataMutex)
     {
-        g_bleReceiveDataMutex = ca_mutex_new();
+        g_bleReceiveDataMutex = oc_mutex_new();
         if (NULL == g_bleReceiveDataMutex)
         {
-            OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
+            OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
             return CA_STATUS_FAILED;
         }
     }
@@ -2117,28 +2117,28 @@ static void CATerminateLEAdapterMutex()
 {
     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CATerminateLEAdapterMutex");
 
-    ca_mutex_free(g_bleIsServerMutex);
+    oc_mutex_free(g_bleIsServerMutex);
     g_bleIsServerMutex = NULL;
 
-    ca_mutex_free(g_bleNetworkCbMutex);
+    oc_mutex_free(g_bleNetworkCbMutex);
     g_bleNetworkCbMutex = NULL;
 
-    ca_mutex_free(g_bleLocalAddressMutex);
+    oc_mutex_free(g_bleLocalAddressMutex);
     g_bleLocalAddressMutex = NULL;
 
-    ca_mutex_free(g_bleAdapterThreadPoolMutex);
+    oc_mutex_free(g_bleAdapterThreadPoolMutex);
     g_bleAdapterThreadPoolMutex = NULL;
 
-    ca_mutex_free(g_bleClientSendDataMutex);
+    oc_mutex_free(g_bleClientSendDataMutex);
     g_bleClientSendDataMutex = NULL;
 
-    ca_mutex_free(g_bleServerSendDataMutex);
+    oc_mutex_free(g_bleServerSendDataMutex);
     g_bleServerSendDataMutex = NULL;
 
-    ca_mutex_free(g_bleAdapterReqRespCbMutex);
+    oc_mutex_free(g_bleAdapterReqRespCbMutex);
     g_bleAdapterReqRespCbMutex = NULL;
 
-    ca_mutex_free(g_bleReceiveDataMutex);
+    oc_mutex_free(g_bleReceiveDataMutex);
     g_bleReceiveDataMutex = NULL;
 
     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
@@ -2356,9 +2356,9 @@ static CAResult_t CALEAdapterGattServerStart()
     */
     if (CA_STATUS_OK == result)
     {
-        ca_mutex_lock(g_bleServerSendDataMutex);
+        oc_mutex_lock(g_bleServerSendDataMutex);
         result = CAQueueingThreadStart(g_bleServerSendQueueHandle);
-        ca_mutex_unlock(g_bleServerSendDataMutex);
+        oc_mutex_unlock(g_bleServerSendDataMutex);
 
         if (CA_STATUS_OK != result)
         {
@@ -2379,12 +2379,12 @@ static CAResult_t CALEAdapterGattServerStop()
     OIC_LOG(DEBUG, CALEADAPTER_TAG, "CALEAdapterGattServerStop");
 
     CAResult_t result = CAStopLEGattServer();
-    ca_mutex_lock(g_bleServerSendDataMutex);
+    oc_mutex_lock(g_bleServerSendDataMutex);
     if (CA_STATUS_OK == result)
     {
         result = CAQueueingThreadStop(g_bleServerSendQueueHandle);
     }
-    ca_mutex_unlock(g_bleServerSendDataMutex);
+    oc_mutex_unlock(g_bleServerSendDataMutex);
 
     return result;
 #else
@@ -2405,9 +2405,9 @@ static CAResult_t CALEAdapterGattClientStart()
     */
     if (CA_STATUS_OK == result)
     {
-        ca_mutex_lock(g_bleClientSendDataMutex);
+        oc_mutex_lock(g_bleClientSendDataMutex);
         result = CAQueueingThreadStart(g_bleClientSendQueueHandle);
-        ca_mutex_unlock(g_bleClientSendDataMutex);
+        oc_mutex_unlock(g_bleClientSendDataMutex);
 
         if (CA_STATUS_OK != result)
         {
@@ -2427,9 +2427,9 @@ static CAResult_t CALEAdapterGattClientStop()
     OIC_LOG(DEBUG, CALEADAPTER_TAG, "CALEAdapterGattClientStop");
     CAStopLEGattClient();
 
-    ca_mutex_lock(g_bleClientSendDataMutex);
+    oc_mutex_lock(g_bleClientSendDataMutex);
     CAResult_t result = CAQueueingThreadStop(g_bleClientSendQueueHandle);
-    ca_mutex_unlock(g_bleClientSendDataMutex);
+    oc_mutex_unlock(g_bleClientSendDataMutex);
 
     return result;
 #else
@@ -2534,7 +2534,7 @@ static CAResult_t CAStopLE()
     CAStopLEQueues();
 #endif
 
-    ca_mutex_lock(g_bleIsServerMutex);
+    oc_mutex_lock(g_bleIsServerMutex);
     switch (g_adapterType)
     {
         case ADAPTER_SERVER:
@@ -2550,7 +2550,7 @@ static CAResult_t CAStopLE()
         default:
             break;
     }
-    ca_mutex_unlock(g_bleIsServerMutex);
+    oc_mutex_unlock(g_bleIsServerMutex);
 
     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
 
@@ -2567,7 +2567,7 @@ static void CATerminateLE()
     CASetLEReqRespAdapterCallback(NULL);
     CATerminateLENetworkMonitor();
 
-    ca_mutex_lock(g_bleIsServerMutex);
+    oc_mutex_lock(g_bleIsServerMutex);
     switch (g_adapterType)
     {
         case ADAPTER_SERVER:
@@ -2584,7 +2584,7 @@ static void CATerminateLE()
             break;
     }
     g_adapterType = ADAPTER_EMPTY;
-    ca_mutex_unlock(g_bleIsServerMutex);
+    oc_mutex_unlock(g_bleIsServerMutex);
 
 #ifndef SINGLE_THREAD
     CATerminateLEQueues();
@@ -2608,7 +2608,7 @@ static CAResult_t CAStartLEListeningServer()
     }
 #endif
 
-    ca_mutex_lock(g_bleIsServerMutex);
+    oc_mutex_lock(g_bleIsServerMutex);
     switch (g_adapterType)
     {
         case ADAPTER_CLIENT:
@@ -2619,7 +2619,7 @@ static CAResult_t CAStartLEListeningServer()
         default:
             g_adapterType = ADAPTER_SERVER;
     }
-    ca_mutex_unlock(g_bleIsServerMutex);
+    oc_mutex_unlock(g_bleIsServerMutex);
 
     result = CAGetLEAdapterState();
     if (CA_STATUS_OK != result)
@@ -2665,7 +2665,7 @@ static CAResult_t CAStartLEDiscoveryServer()
     }
 #endif
 
-    ca_mutex_lock(g_bleIsServerMutex);
+    oc_mutex_lock(g_bleIsServerMutex);
     switch (g_adapterType)
     {
         case ADAPTER_SERVER:
@@ -2676,7 +2676,7 @@ static CAResult_t CAStartLEDiscoveryServer()
         default:
             g_adapterType = ADAPTER_CLIENT;
     }
-    ca_mutex_unlock(g_bleIsServerMutex);
+    oc_mutex_unlock(g_bleIsServerMutex);
 
     result = CAGetLEAdapterState();
     if (CA_STATUS_OK != result)
@@ -2727,14 +2727,14 @@ static int32_t CASendLEUnicastData(const CAEndpoint_t *endpoint,
         OIC_LOG(ERROR, CALEADAPTER_TAG, "g_adapterType is Empty");
     }
 
-    ca_mutex_lock(g_bleIsServerMutex);
+    oc_mutex_lock(g_bleIsServerMutex);
     if (ADAPTER_SERVER == g_adapterType ||
             (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_RESPONSE_DATA == dataType))
     {
         result = CALEAdapterServerSendData(endpoint, data, dataLen);
         if (CA_STATUS_OK != result)
         {
-            ca_mutex_unlock(g_bleIsServerMutex);
+            oc_mutex_unlock(g_bleIsServerMutex);
             OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast data for server failed");
             if (g_errorHandler)
             {
@@ -2752,7 +2752,7 @@ static int32_t CASendLEUnicastData(const CAEndpoint_t *endpoint,
         result = CALEAdapterClientSendData(endpoint, data, dataLen);
         if (CA_STATUS_OK != result)
         {
-            ca_mutex_unlock(g_bleIsServerMutex);
+            oc_mutex_unlock(g_bleIsServerMutex);
             OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast data for client failed" );
 
              if (g_errorHandler)
@@ -2762,7 +2762,7 @@ static int32_t CASendLEUnicastData(const CAEndpoint_t *endpoint,
             return -1;
         }
     }
-    ca_mutex_unlock(g_bleIsServerMutex);
+    oc_mutex_unlock(g_bleIsServerMutex);
 
     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
     return dataLen;
@@ -2792,14 +2792,14 @@ static int32_t CASendLEMulticastData(const CAEndpoint_t *endpoint,
         OIC_LOG(ERROR, CALEADAPTER_TAG, "g_adapterType is Empty");
     }
 
-    ca_mutex_lock(g_bleIsServerMutex);
+    oc_mutex_lock(g_bleIsServerMutex);
     if (ADAPTER_SERVER == g_adapterType ||
             (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_RESPONSE_DATA == dataType))
     {
         result = CALEAdapterServerSendData(NULL, data, dataLen);
         if (CA_STATUS_OK != result)
         {
-            ca_mutex_unlock(g_bleIsServerMutex);
+            oc_mutex_unlock(g_bleIsServerMutex);
 
             OIC_LOG(ERROR, CALEADAPTER_TAG, "Send multicast data for server failed" );
 
@@ -2818,7 +2818,7 @@ static int32_t CASendLEMulticastData(const CAEndpoint_t *endpoint,
         result = CALEAdapterClientSendData(NULL, data, dataLen);
         if (CA_STATUS_OK != result)
         {
-            ca_mutex_unlock(g_bleIsServerMutex);
+            oc_mutex_unlock(g_bleIsServerMutex);
 
             OIC_LOG(ERROR, CALEADAPTER_TAG, "Send Multicast data for client failed" );
 
@@ -2829,7 +2829,7 @@ static int32_t CASendLEMulticastData(const CAEndpoint_t *endpoint,
             return -1;
         }
     }
-    ca_mutex_unlock(g_bleIsServerMutex);
+    oc_mutex_unlock(g_bleIsServerMutex);
 
     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT - CASendLEMulticastData");
     return dataLen;
@@ -2877,9 +2877,9 @@ static CAResult_t CAGetLEInterfaceInformation(CAEndpoint_t **info, uint32_t *siz
     }
 
     OICStrcpy((*info)->addr, sizeof((*info)->addr), local_address);
-    ca_mutex_lock(g_bleLocalAddressMutex);
+    oc_mutex_lock(g_bleLocalAddressMutex);
     OICStrcpy(g_localBLEAddress, sizeof(g_localBLEAddress), local_address);
-    ca_mutex_unlock(g_bleLocalAddressMutex);
+    oc_mutex_unlock(g_bleLocalAddressMutex);
 
     (*info)->adapter = CA_ADAPTER_GATT_BTLE;
     *size = 1;
@@ -2894,10 +2894,10 @@ static CAResult_t CALERegisterNetworkNotifications(CAAdapterChangeCallback netCa
 {
     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
 
-    ca_mutex_lock(g_bleNetworkCbMutex);
+    oc_mutex_lock(g_bleNetworkCbMutex);
     g_networkCallback = netCallback;
     g_connectionCallback = connCallback;
-    ca_mutex_unlock(g_bleNetworkCbMutex);
+    oc_mutex_unlock(g_bleNetworkCbMutex);
     CAResult_t res = CA_STATUS_OK;
     if (netCallback)
     {
@@ -2938,7 +2938,7 @@ static void CALEConnectionStateChangedCb(CATransportAdapter_t adapter, const cha
     (void)adapter;
 
 #ifdef __TIZEN__
-    ca_mutex_lock(g_bleIsServerMutex);
+    oc_mutex_lock(g_bleIsServerMutex);
     switch (g_adapterType)
     {
         case ADAPTER_SERVER:
@@ -2954,7 +2954,7 @@ static void CALEConnectionStateChangedCb(CATransportAdapter_t adapter, const cha
         default:
             break;
     }
-    ca_mutex_unlock(g_bleIsServerMutex);
+    oc_mutex_unlock(g_bleIsServerMutex);
 #endif
 
     if(!isConnected)
@@ -2990,12 +2990,12 @@ static void CALEConnectionStateChangedCb(CATransportAdapter_t adapter, const cha
     CAEndpoint_t localEndpoint = { .adapter = CA_ADAPTER_GATT_BTLE };
     OICStrcpy(localEndpoint.addr, sizeof(localEndpoint.addr), address);
 
-    ca_mutex_lock(g_bleNetworkCbMutex);
+    oc_mutex_lock(g_bleNetworkCbMutex);
     if (g_connectionCallback)
     {
         g_connectionCallback(&localEndpoint, isConnected);
     }
-    ca_mutex_unlock(g_bleNetworkCbMutex);
+    oc_mutex_unlock(g_bleNetworkCbMutex);
 
     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
 }
@@ -3006,7 +3006,7 @@ static void CALEDeviceStateChangedCb(CAAdapterState_t adapter_state)
 
     if (CA_ADAPTER_ENABLED == adapter_state)
     {
-        ca_mutex_lock(g_bleIsServerMutex);
+        oc_mutex_lock(g_bleIsServerMutex);
         switch (g_adapterType)
         {
             case ADAPTER_SERVER:
@@ -3022,11 +3022,11 @@ static void CALEDeviceStateChangedCb(CAAdapterState_t adapter_state)
             default:
                 break;
         }
-        ca_mutex_unlock(g_bleIsServerMutex);
+        oc_mutex_unlock(g_bleIsServerMutex);
     }
     else
     {
-        ca_mutex_lock(g_bleIsServerMutex);
+        oc_mutex_lock(g_bleIsServerMutex);
         switch (g_adapterType)
         {
             case ADAPTER_SERVER:
@@ -3042,10 +3042,10 @@ static void CALEDeviceStateChangedCb(CAAdapterState_t adapter_state)
             default:
                 break;
         }
-        ca_mutex_unlock(g_bleIsServerMutex);
+        oc_mutex_unlock(g_bleIsServerMutex);
     }
 
-    ca_mutex_lock(g_bleNetworkCbMutex);
+    oc_mutex_lock(g_bleNetworkCbMutex);
     if (NULL != g_networkCallback)
     {
         g_networkCallback(CA_ADAPTER_GATT_BTLE, adapter_state);
@@ -3054,7 +3054,7 @@ static void CALEDeviceStateChangedCb(CAAdapterState_t adapter_state)
     {
         OIC_LOG(ERROR, CALEADAPTER_TAG, "g_networkCallback is NULL");
     }
-    ca_mutex_unlock(g_bleNetworkCbMutex);
+    oc_mutex_unlock(g_bleNetworkCbMutex);
 
     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
 }
@@ -3087,9 +3087,9 @@ static CAResult_t CALEAdapterClientSendData(const CAEndpoint_t *remoteEndpoint,
         return CA_MEMORY_ALLOC_FAILED;
     }
     // Add message to send queue
-    ca_mutex_lock(g_bleClientSendDataMutex);
+    oc_mutex_lock(g_bleClientSendDataMutex);
     CAQueueingThreadAddData(g_bleClientSendQueueHandle, bleData, sizeof(CALEData_t));
-    ca_mutex_unlock(g_bleClientSendDataMutex);
+    oc_mutex_unlock(g_bleClientSendDataMutex);
 #endif
     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
     return CA_STATUS_OK;
@@ -3139,11 +3139,11 @@ static CAResult_t CALEAdapterServerSendData(const CAEndpoint_t *remoteEndpoint,
     }
 
     // Add message to send queue
-    ca_mutex_lock(g_bleServerSendDataMutex);
+    oc_mutex_lock(g_bleServerSendDataMutex);
     CAQueueingThreadAddData(g_bleServerSendQueueHandle,
                             bleData,
                             sizeof(CALEData_t));
-    ca_mutex_unlock(g_bleServerSendDataMutex);
+    oc_mutex_unlock(g_bleServerSendDataMutex);
 #endif
     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
     return CA_STATUS_OK;
@@ -3176,6 +3176,7 @@ static CAResult_t CALEAdapterServerReceivedData(const char *remoteAddress,
                                             g_singleThreadReceiveData->recvDataLen);
         }
         g_singleThreadReceiveData->remoteEndpoint = NULL;
+        OICFree(g_singleThreadReceiveData->defragData);
         g_singleThreadReceiveData->defragData = NULL;
         OICFree(g_singleThreadReceiveData);
         g_singleThreadReceiveData = NULL;
@@ -3276,9 +3277,9 @@ static void CASetLEAdapterThreadPoolHandle(ca_thread_pool_t handle)
 {
     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
 
-    ca_mutex_lock(g_bleAdapterThreadPoolMutex);
+    oc_mutex_lock(g_bleAdapterThreadPoolMutex);
     g_bleAdapterThreadPool = handle;
-    ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
+    oc_mutex_unlock(g_bleAdapterThreadPoolMutex);
 
     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
 }
@@ -3287,11 +3288,11 @@ static void CASetLEReqRespAdapterCallback(CANetworkPacketReceivedCallback callba
 {
     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
 
-    ca_mutex_lock(g_bleAdapterReqRespCbMutex);
+    oc_mutex_lock(g_bleAdapterReqRespCbMutex);
 
     g_networkPacketReceivedCallback = callback;
 
-    ca_mutex_unlock(g_bleAdapterReqRespCbMutex);
+    oc_mutex_unlock(g_bleAdapterReqRespCbMutex);
 
     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
 }
@@ -3319,7 +3320,7 @@ static void CALEErrorHandler(const char *remoteAddress,
 }
 
 #ifndef SINGLE_THREAD
-static void CALERemoveSendQueueData(CAQueueingThread_t *queueHandle, ca_mutex mutex,
+static void CALERemoveSendQueueData(CAQueueingThread_t *queueHandle, oc_mutex mutex,
                                     const char* address)
 {
     OIC_LOG(DEBUG, CALEADAPTER_TAG, "CALERemoveSendQueueData");
@@ -3327,7 +3328,7 @@ static void CALERemoveSendQueueData(CAQueueingThread_t *queueHandle, ca_mutex mu
     VERIFY_NON_NULL_VOID(queueHandle, CALEADAPTER_TAG, "queueHandle");
     VERIFY_NON_NULL_VOID(address, CALEADAPTER_TAG, "address");
 
-    ca_mutex_lock(mutex);
+    oc_mutex_lock(mutex);
     while (u_queue_get_size(queueHandle->dataQueue) > 0)
     {
         OIC_LOG(DEBUG, CALEADAPTER_TAG, "get data from queue");
@@ -3354,7 +3355,7 @@ static void CALERemoveSendQueueData(CAQueueingThread_t *queueHandle, ca_mutex mu
             }
         }
     }
-    ca_mutex_unlock(mutex);
+    oc_mutex_unlock(mutex);
 }
 
 static void CALERemoveReceiveQueueData(u_arraylist_t *dataInfoList, const char* address)
@@ -3371,7 +3372,7 @@ static void CALERemoveReceiveQueueData(u_arraylist_t *dataInfoList, const char*
     if (CA_STATUS_OK == CALEGetPortsFromSenderInfo(address, dataInfoList, portList))
     {
         uint32_t arrayLength = u_arraylist_length(portList);
-        for (int i = 0; i < arrayLength; i++)
+        for (uint32_t i = 0; i < arrayLength; i++)
         {
             uint16_t port = u_arraylist_get(portList, i);
             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "port : %X", port);
@@ -3418,7 +3419,7 @@ static CAResult_t CALEGetPortsFromSenderInfo(const char *leAddress,
 
         if (!strncmp(info->remoteEndpoint->addr, leAddress, addrLength))
         {
-            u_arraylist_add(portList, (void *) info->remoteEndpoint->port);
+            u_arraylist_add(portList, (void *)info->remoteEndpoint->port);
         }
     }
 
index 57aa4eb..ce3417f 100644 (file)
@@ -55,13 +55,13 @@ static bool CALESetUpBlueZObjects(CALEContext * context);
 
 static bool CALECheckStarted()
 {
-    ca_mutex_lock(g_context.lock);
+    oc_mutex_lock(g_context.lock);
 
     bool const started =
         (g_context.event_loop != NULL
          && g_main_loop_is_running(g_context.event_loop));
 
-    ca_mutex_unlock(g_context.lock);
+    oc_mutex_unlock(g_context.lock);
 
     /**
      * @todo Fix potential TOCTOU race condition.  A LE transport
@@ -206,7 +206,7 @@ static void CALEHandleInterfaceAdded(GList ** proxy_list,
         return;
     }
 
-    ca_mutex_lock(g_context.lock);
+    oc_mutex_lock(g_context.lock);
 
     /*
       Add the object information to the list.
@@ -217,7 +217,7 @@ static void CALEHandleInterfaceAdded(GList ** proxy_list,
     */
     *proxy_list = g_list_prepend(*proxy_list, proxy);
 
-    ca_mutex_unlock(g_context.lock);
+    oc_mutex_unlock(g_context.lock);
 
     /**
      * Let the thread that may be blocked waiting for Devices to be
@@ -230,7 +230,7 @@ static void CALEHandleInterfaceAdded(GList ** proxy_list,
      */
     if (strcmp(interface, BLUEZ_DEVICE_INTERFACE) == 0)
     {
-        ca_cond_signal(g_context.condition);
+        oc_cond_signal(g_context.condition);
     }
 }
 
@@ -329,7 +329,7 @@ static void CALEOnInterfacesRemoved(GDBusConnection * connection,
         gchar const * path = NULL;
         g_variant_get_child(parameters, 0, "&o", &path);
 
-        ca_mutex_lock(g_context.lock);
+        oc_mutex_lock(g_context.lock);
 
         for (GList * l = *list; l != NULL; l = g_list_next(l))
         {
@@ -352,7 +352,7 @@ static void CALEOnInterfacesRemoved(GDBusConnection * connection,
             }
         }
 
-        ca_mutex_unlock(g_context.lock);
+        oc_mutex_unlock(g_context.lock);
 
         g_variant_unref(child);
     }
@@ -405,12 +405,12 @@ static void CALESubscribeToSignals(CALEContext * context,
                      G_CALLBACK(CALEOnInterfaceProxyPropertiesChanged),
                      context);
 
-    ca_mutex_lock(context->lock);
+    oc_mutex_lock(context->lock);
 
     context->interfaces_added_sub_id   = interfaces_added_sub_id;
     context->interfaces_removed_sub_id = interfaces_removed_sub_id;
 
-    ca_mutex_unlock(context->lock);
+    oc_mutex_unlock(context->lock);
 }
 
 static bool CALESetUpDBus(CALEContext * context)
@@ -471,10 +471,10 @@ static bool CALESetUpDBus(CALEContext * context)
 
     CALESubscribeToSignals(context, connection, object_manager);
 
-    ca_mutex_lock(context->lock);
+    oc_mutex_lock(context->lock);
     context->connection     = connection;
     context->object_manager = object_manager;
-    ca_mutex_unlock(context->lock);
+    oc_mutex_unlock(context->lock);
 
     success = CALESetUpBlueZObjects(context);
 
@@ -490,7 +490,7 @@ static void CALETearDownDBus(CALEContext * context)
       global state, and pushing resource finalization outside the global
       lock.
     */
-    ca_mutex_lock(context->lock);
+    oc_mutex_lock(context->lock);
 
     GDBusConnection * const connection = context->connection;
     context->connection = NULL;
@@ -513,7 +513,7 @@ static void CALETearDownDBus(CALEContext * context)
     context->interfaces_added_sub_id   = 0;
     context->interfaces_removed_sub_id = 0;
 
-    ca_mutex_unlock(context->lock);
+    oc_mutex_unlock(context->lock);
 
     // Destroy the device proxies list.
     g_list_free_full(devices, g_object_unref);
@@ -599,9 +599,9 @@ static bool CALESetUpBlueZObjects(CALEContext * context)
         return success;
     }
 
-    ca_mutex_lock(context->lock);
+    oc_mutex_lock(context->lock);
     context->objects = objects;
-    ca_mutex_unlock(context->lock);
+    oc_mutex_unlock(context->lock);
 
     /*
       Create a proxies to the org.bluez.Adapter1 D-Bus objects that
@@ -617,9 +617,9 @@ static bool CALESetUpBlueZObjects(CALEContext * context)
     // An empty adapters list is NULL.
     if (success && adapters != NULL)
     {
-        ca_mutex_lock(context->lock);
+        oc_mutex_lock(context->lock);
         context->adapters = adapters;
-        ca_mutex_unlock(context->lock);
+        oc_mutex_unlock(context->lock);
     }
 
     /*
@@ -635,9 +635,9 @@ static bool CALESetUpBlueZObjects(CALEContext * context)
     // An empty device list is NULL.
     if (success && devices != NULL)
     {
-        ca_mutex_lock(context->lock);
+        oc_mutex_lock(context->lock);
         context->devices = devices;
-        ca_mutex_unlock(context->lock);
+        oc_mutex_unlock(context->lock);
     }
 
     return success;
@@ -677,12 +677,12 @@ static void CALEStartEventLoop(void * data)
     */
     if (CALESetUpDBus(&g_context))
     {
-        ca_mutex_lock(context->lock);
+        oc_mutex_lock(context->lock);
 
         assert(context->event_loop == NULL);
         context->event_loop = event_loop;
 
-        ca_mutex_unlock(context->lock);
+        oc_mutex_unlock(context->lock);
 
         /*
           Add an idle handler that notifies a thread waiting for the
@@ -714,12 +714,12 @@ static void CALEStartEventLoop(void * data)
 
 static void CALEStopEventLoop(CALEContext * context)
 {
-    ca_mutex_lock(context->lock);
+    oc_mutex_lock(context->lock);
 
     GMainLoop * const event_loop = context->event_loop;
     context->event_loop = NULL;
 
-    ca_mutex_unlock(context->lock);
+    oc_mutex_unlock(context->lock);
 
     if (event_loop != NULL)
     {
@@ -749,13 +749,13 @@ static bool CALEWaitForNonEmptyList(GList * const * list,
 {
     bool success = false;
 
-    ca_mutex_lock(g_context.lock);
+    oc_mutex_lock(g_context.lock);
 
     for (int i = 0; *list == NULL && i < retries; ++i)
     {
-        if (ca_cond_wait_for(g_context.condition,
+        if (oc_cond_wait_for(g_context.condition,
                              g_context.lock,
-                             timeout) == CA_WAIT_SUCCESS)
+                             timeout) == OC_WAIT_SUCCESS)
         {
             /*
               Condition variable was signaled before the timeout was
@@ -765,7 +765,7 @@ static bool CALEWaitForNonEmptyList(GList * const * list,
         }
     }
 
-    ca_mutex_unlock(g_context.lock);
+    oc_mutex_unlock(g_context.lock);
 
     return success;
 }
@@ -882,7 +882,7 @@ CAResult_t CAGetLEAdapterState()
 {
     CAResult_t result = CA_ADAPTER_NOT_ENABLED;
 
-    ca_mutex_lock(g_context.lock);
+    oc_mutex_lock(g_context.lock);
 
     for (GList * l = g_context.adapters; l != NULL; l = l->next)
     {
@@ -912,7 +912,7 @@ CAResult_t CAGetLEAdapterState()
         }
     }
 
-    ca_mutex_unlock(g_context.lock);
+    oc_mutex_unlock(g_context.lock);
 
     return result;
 }
@@ -928,8 +928,8 @@ CAResult_t CAInitializeLENetworkMonitor()
      * @see @c CAStartLEAdapter() for further details.
      */
 
-    g_context.lock      = ca_mutex_new();
-    g_context.condition = ca_cond_new();
+    g_context.lock      = oc_mutex_new();
+    g_context.condition = oc_cond_new();
 
     static int const PSHARED        = 0;  // shared between threads
     static unsigned int const VALUE = 0;  // force sem_wait() to block
@@ -968,7 +968,7 @@ void CATerminateLENetworkMonitor()
 
     (void) sem_destroy(&g_context.le_started);
 
-    ca_mutex_lock(g_context.lock);
+    oc_mutex_lock(g_context.lock);
 
     g_context.on_device_state_changed = NULL;
     g_context.on_server_received_data = NULL;
@@ -978,21 +978,21 @@ void CATerminateLENetworkMonitor()
     g_context.on_client_error         = NULL;
     g_context.on_server_error         = NULL;
 
-    ca_cond_free(g_context.condition);
+    oc_cond_free(g_context.condition);
     g_context.condition = NULL;
 
-    ca_mutex_unlock(g_context.lock);
+    oc_mutex_unlock(g_context.lock);
 
-    ca_mutex_free(g_context.lock);
+    oc_mutex_free(g_context.lock);
     g_context.lock = NULL;
 }
 
 CAResult_t CASetLEAdapterStateChangedCb(
     CALEDeviceStateChangedCallback callback)
 {
-    ca_mutex_lock(g_context.lock);
+    oc_mutex_lock(g_context.lock);
     g_context.on_device_state_changed = callback;
-    ca_mutex_unlock(g_context.lock);
+    oc_mutex_unlock(g_context.lock);
 
     return CA_STATUS_OK;
 }
@@ -1054,7 +1054,7 @@ CAResult_t CAGetLEAddress(char **local_address)
 
     *local_address = NULL;
 
-    ca_mutex_lock(g_context.lock);
+    oc_mutex_lock(g_context.lock);
 
     for (GList * l = g_context.adapters; l != NULL; l = l->next)
     {
@@ -1098,7 +1098,7 @@ CAResult_t CAGetLEAddress(char **local_address)
         break;
     }
 
-    ca_mutex_unlock(g_context.lock);
+    oc_mutex_unlock(g_context.lock);
 
     return *local_address != NULL ? CA_STATUS_OK : CA_STATUS_FAILED;
 }
@@ -1128,9 +1128,9 @@ void CATerminateLEGattServer()
 
 void CASetLEReqRespServerCallback(CABLEDataReceivedCallback callback)
 {
-    ca_mutex_lock(g_context.lock);
+    oc_mutex_lock(g_context.lock);
     g_context.on_server_received_data = callback;
-    ca_mutex_unlock(g_context.lock);
+    oc_mutex_unlock(g_context.lock);
 }
 
 CAResult_t CAUpdateCharacteristicsToGattClient(char const * address,
@@ -1157,9 +1157,9 @@ CAResult_t CAStartLEGattClient()
         return result;
     }
 
-    ca_mutex_lock(g_context.lock);
+    oc_mutex_lock(g_context.lock);
     bool found_peripherals = (g_context.devices != NULL);
-    ca_mutex_unlock(g_context.lock);
+    oc_mutex_unlock(g_context.lock);
 
     if (!found_peripherals)
     {
@@ -1265,44 +1265,44 @@ CAResult_t CAUpdateCharacteristicsToAllGattServers(uint8_t const * data,
 
 void CASetLEReqRespClientCallback(CABLEDataReceivedCallback callback)
 {
-    ca_mutex_lock(g_context.lock);
+    oc_mutex_lock(g_context.lock);
     g_context.on_client_received_data = callback;
-    ca_mutex_unlock(g_context.lock);
+    oc_mutex_unlock(g_context.lock);
 }
 
 void CASetLEServerThreadPoolHandle(ca_thread_pool_t handle)
 {
-    ca_mutex_lock(g_context.lock);
+    oc_mutex_lock(g_context.lock);
     g_context.server_thread_pool = handle;
-    ca_mutex_unlock(g_context.lock);
+    oc_mutex_unlock(g_context.lock);
 }
 
 void CASetLEClientThreadPoolHandle(ca_thread_pool_t handle)
 {
-    ca_mutex_lock(g_context.lock);
+    oc_mutex_lock(g_context.lock);
     g_context.client_thread_pool = handle;
-    ca_mutex_unlock(g_context.lock);
+    oc_mutex_unlock(g_context.lock);
 }
 
 CAResult_t CAUnSetLEAdapterStateChangedCb()
 {
-    ca_mutex_lock(g_context.lock);
+    oc_mutex_lock(g_context.lock);
     g_context.on_device_state_changed = NULL;
-    ca_mutex_unlock(g_context.lock);
+    oc_mutex_unlock(g_context.lock);
 
     return CA_STATUS_OK;
 }
 
 void CASetBLEClientErrorHandleCallback(CABLEErrorHandleCallback callback)
 {
-    ca_mutex_lock(g_context.lock);
+    oc_mutex_lock(g_context.lock);
     g_context.on_client_error = callback;
-    ca_mutex_unlock(g_context.lock);
+    oc_mutex_unlock(g_context.lock);
 }
 
 void CASetBLEServerErrorHandleCallback(CABLEErrorHandleCallback callback)
 {
-    ca_mutex_lock(g_context.lock);
+    oc_mutex_lock(g_context.lock);
     g_context.on_server_error = callback;
-    ca_mutex_unlock(g_context.lock);
+    oc_mutex_unlock(g_context.lock);
 }
index 874e3a2..39daf5e 100644 (file)
@@ -254,7 +254,7 @@ static void CACentralDisconnect(CALEContext * context)
 {
     assert(context != NULL);
 
-    ca_mutex_lock(context->lock);
+    oc_mutex_lock(context->lock);
 
     for (GList * l = context->devices; l != NULL; l = l->next)
     {
@@ -280,7 +280,7 @@ static void CACentralDisconnect(CALEContext * context)
         }
     }
 
-    ca_mutex_unlock(context->lock);
+    oc_mutex_unlock(context->lock);
 }
 
 // -----------------------------------------------------------------------
@@ -295,7 +295,7 @@ CAResult_t CACentralStart(CALEContext * context)
       Synchronize access to the adapter information using the base
       context lock since we don't own the adapters.
      */
-    ca_mutex_lock(context->lock);
+    oc_mutex_lock(context->lock);
 
     /**
      * Start discovery on all detected adapters.
@@ -309,7 +309,7 @@ CAResult_t CACentralStart(CALEContext * context)
                    CACentralStartDiscoveryImpl,
                    &result);
 
-    ca_mutex_unlock(context->lock);
+    oc_mutex_unlock(context->lock);
 
     return result;
 }
@@ -343,14 +343,14 @@ CAResult_t CACentralStartDiscovery(CALEContext * context)
       Synchronize access to the adapter information using the base
       context lock since we don't own the adapters.
      */
-    ca_mutex_lock(context->lock);
+    oc_mutex_lock(context->lock);
 
     // Start discovery on all detected adapters.
     g_list_foreach(context->adapters,
                    CACentralStartDiscoveryImpl,
                    &result);
 
-    ca_mutex_unlock(context->lock);
+    oc_mutex_unlock(context->lock);
 
     return result;
 }
@@ -365,7 +365,7 @@ CAResult_t CACentralStopDiscovery(CALEContext * context)
       Synchronize access to the adapter information using the base
       context lock since we don't own the adapters.
      */
-    ca_mutex_lock(context->lock);
+    oc_mutex_lock(context->lock);
 
     // Stop discovery on all detected adapters.
     g_list_foreach(context->adapters,
@@ -376,7 +376,7 @@ CAResult_t CACentralStopDiscovery(CALEContext * context)
      * @todo Stop notifications on all response characteristics.
      */
 
-    ca_mutex_unlock(context->lock);
+    oc_mutex_unlock(context->lock);
 
     return result;
 }
@@ -431,14 +431,14 @@ bool CACentralConnectToAll(CALEContext * context)
 {
     bool connected = true;
 
-    ca_mutex_lock(context->lock);
+    oc_mutex_lock(context->lock);
 
     // Connect to the LE peripherals, if we're not already connected.
     g_list_foreach(context->devices,
                    CACentralConnectToDevice,
                    &connected);
 
-    ca_mutex_unlock(context->lock);
+    oc_mutex_unlock(context->lock);
 
     return connected;
 }
index 5972837..ea30505 100644 (file)
@@ -336,9 +336,9 @@ bool CAGattRequestCharacteristicInitialize(struct CAGattService * s,
         return false;
     }
 
-    ca_mutex_lock(context->lock);
+    oc_mutex_lock(context->lock);
     c->recv_info.on_packet_received = context->on_server_received_data;
-    ca_mutex_unlock(context->lock);
+    oc_mutex_unlock(context->lock);
 
     c->recv_info.peer    = peer;
     c->recv_info.context = context;
index 2888c7b..299f54e 100644 (file)
@@ -70,7 +70,7 @@ typedef struct _CAGattClientContext
     GHashTable * address_map;
 
     /// Mutex used to synchronize access to context fields.
-    ca_mutex lock;
+    oc_mutex lock;
 
 } CAGattClientContext;
 
@@ -108,7 +108,7 @@ static void CAGattClientOnCharacteristicPropertiesChanged(
     char const * const object_path =
         g_dbus_proxy_get_object_path(characteristic);
 
-    ca_mutex_lock(g_context.lock);
+    oc_mutex_lock(g_context.lock);
 
     char * const address =
         g_hash_table_lookup(g_context.address_map, object_path);
@@ -145,7 +145,7 @@ static void CAGattClientOnCharacteristicPropertiesChanged(
         }
     }
 
-    ca_mutex_unlock(g_context.lock);
+    oc_mutex_unlock(g_context.lock);
 }
 
 // ---------------------------------------------------------------------
@@ -483,7 +483,7 @@ static void CAGattClientOnDevicePropertiesChanged(
     {
         CALEContext * const context = user_data;
 
-        ca_mutex_lock(g_context.lock);
+        oc_mutex_lock(g_context.lock);
 
         CAGattClientSetupService(device,
                                  g_context.characteristic_map,
@@ -491,7 +491,7 @@ static void CAGattClientOnDevicePropertiesChanged(
                                  services_prop,
                                  context);
 
-        ca_mutex_unlock(g_context.lock);
+        oc_mutex_unlock(g_context.lock);
 
         g_variant_unref(services_prop);
     }
@@ -499,7 +499,7 @@ static void CAGattClientOnDevicePropertiesChanged(
 
 CAResult_t CAGattClientInitialize(CALEContext * context)
 {
-    g_context.lock = ca_mutex_new();
+    g_context.lock = oc_mutex_new();
 
     /*
       Map Bluetooth MAC address to OIC Transport Profile
@@ -521,7 +521,7 @@ CAResult_t CAGattClientInitialize(CALEContext * context)
                               OICFree,
                               OICFree);
 
-    ca_mutex_lock(context->lock);
+    oc_mutex_lock(context->lock);
 
     for (GList * l = context->devices; l != NULL; l = l->next)
     {
@@ -545,14 +545,14 @@ CAResult_t CAGattClientInitialize(CALEContext * context)
                                  context);
     }
 
-    ca_mutex_unlock(context->lock);
+    oc_mutex_unlock(context->lock);
 
-    ca_mutex_lock(g_context.lock);
+    oc_mutex_lock(g_context.lock);
 
     g_context.characteristic_map = characteristic_map;
     g_context.address_map = address_map;
 
-    ca_mutex_unlock(g_context.lock);
+    oc_mutex_unlock(g_context.lock);
 
     return CA_STATUS_OK;
 }
@@ -564,7 +564,7 @@ void CAGattClientDestroy()
         return;  // Initialization did not complete.
     }
 
-    ca_mutex_lock(g_context.lock);
+    oc_mutex_lock(g_context.lock);
 
     if (g_context.characteristic_map != NULL)
     {
@@ -578,9 +578,9 @@ void CAGattClientDestroy()
         g_context.address_map = NULL;
     }
 
-    ca_mutex_unlock(g_context.lock);
+    oc_mutex_unlock(g_context.lock);
 
-    ca_mutex_free(g_context.lock);
+    oc_mutex_free(g_context.lock);
     g_context.lock = NULL;
 
     /*
@@ -636,7 +636,7 @@ static CAResult_t CAGattClientSendDataImpl(GDBusProxy * characteristic,
 
         g_error_free(error);
 
-        ca_mutex_lock(context->lock);
+        oc_mutex_lock(context->lock);
 
         if (context->on_client_error != NULL)
         {
@@ -650,7 +650,7 @@ static CAResult_t CAGattClientSendDataImpl(GDBusProxy * characteristic,
                                      CA_STATUS_FAILED);
         }
 
-        ca_mutex_unlock(context->lock);
+        oc_mutex_unlock(context->lock);
 
         return CA_STATUS_FAILED;
     }
@@ -669,7 +669,7 @@ CAResult_t CAGattClientSendData(char const * address,
 
     CAResult_t result = CA_STATUS_FAILED;
 
-    ca_mutex_lock(g_context.lock);
+    oc_mutex_lock(g_context.lock);
 
     GDBusProxy * const characteristic =
         G_DBUS_PROXY(
@@ -691,7 +691,7 @@ CAResult_t CAGattClientSendData(char const * address,
                                       length,
                                       context);
 
-    ca_mutex_unlock(g_context.lock);
+    oc_mutex_unlock(g_context.lock);
 
     return result;
 }
@@ -704,12 +704,12 @@ CAResult_t CAGattClientSendDataToAll(uint8_t const * data,
 
     CAResult_t result = CA_STATUS_FAILED;
 
-    ca_mutex_lock(g_context.lock);
+    oc_mutex_lock(g_context.lock);
 
     if (g_context.characteristic_map == NULL)
     {
         // Remote OIC GATT service was not found prior to getting here.
-        ca_mutex_unlock(g_context.lock);
+        oc_mutex_unlock(g_context.lock);
         return result;
     }
 
@@ -737,7 +737,7 @@ CAResult_t CAGattClientSendDataToAll(uint8_t const * data,
         }
     }
 
-    ca_mutex_unlock(g_context.lock);
+    oc_mutex_unlock(g_context.lock);
 
     return result;
 }
index e0db333..2e734af 100644 (file)
@@ -20,7 +20,7 @@
 #define CA_BLE_LINUX_CONTEXT_H
 
 #include "caadapterinterface.h"
-#include "camutex.h"
+#include "octhread.h"
 #include "cathreadpool.h"
 #include "caleinterface.h"
 
@@ -149,7 +149,7 @@ typedef struct _CALEContext
     CABLEErrorHandleCallback on_server_error;
 
     /// Mutex used to synchronize access to context fields.
-    ca_mutex lock;
+    oc_mutex lock;
 
     /**
      * BlueZ adapter list initialization condition variable.
@@ -163,7 +163,7 @@ typedef struct _CALEContext
      *
      * @see @c GMainLoop documentation for further details.
      */
-    ca_cond condition;
+    oc_cond condition;
 
     /**
      * Semaphore that indicates completed start of the LE transport.
index 9966198..cd29611 100644 (file)
@@ -39,13 +39,13 @@ static CAPeripheralContext g_context = {
 
 static bool CAPeripheralCheckStarted()
 {
-    ca_mutex_lock(g_context.lock);
+    oc_mutex_lock(g_context.lock);
 
     bool const started =
         (g_context.event_loop != NULL
          && g_main_loop_is_running(g_context.event_loop));
 
-    ca_mutex_unlock(g_context.lock);
+    oc_mutex_unlock(g_context.lock);
 
     /**
      * @todo Fix potential TOCTOU race condition.  A peripheral could
@@ -59,11 +59,11 @@ static bool CAPeripheralCheckStarted()
 static bool CAPeripheralAdaptersFound(CALEContext * context)
 {
     // Check if BlueZ detected bluetooth hardware adapters.
-    ca_mutex_lock(context->lock);
+    oc_mutex_lock(context->lock);
 
     bool const found = (context->adapters != NULL);
 
-    ca_mutex_unlock(context->lock);
+    oc_mutex_unlock(context->lock);
 
     if (!found)
     {
@@ -162,7 +162,7 @@ static bool CAPeripheralRegisterGattServices(
 
     bool success = true;
 
-    ca_mutex_lock(context->lock);
+    oc_mutex_lock(context->lock);
 
     for (GList * l = context->gatt_services; l != NULL; l = l->next)
     {
@@ -209,7 +209,7 @@ static bool CAPeripheralRegisterGattServices(
         g_variant_unref(ret);
     }
 
-    ca_mutex_unlock(context->lock);
+    oc_mutex_unlock(context->lock);
 
     return success;
 }
@@ -224,7 +224,7 @@ static bool CAPeripheralRegisterAdvertisements(
       LE Advertisement Manager.
     */
 
-    ca_mutex_lock(context->lock);
+    oc_mutex_lock(context->lock);
 
     char const * const advertisement_path =
         g_dbus_interface_skeleton_get_object_path(
@@ -310,7 +310,7 @@ static bool CAPeripheralRegisterAdvertisements(
         success = true;
     }
 
-    ca_mutex_unlock(context->lock);
+    oc_mutex_unlock(context->lock);
 
     return success;
 }
@@ -383,14 +383,14 @@ static CAResult_t CAPeripheralSetDiscoverability(
       Synchronize access to the adapter information using the base
       context lock since we don't own the adapter_infos.
      */
-    ca_mutex_lock(context->lock);
+    oc_mutex_lock(context->lock);
 
     // Make all detected adapters discoverable.
     g_list_foreach(context->adapters,
                    discoverability_func,
                    &result);
 
-    ca_mutex_unlock(context->lock);
+    oc_mutex_unlock(context->lock);
 
     return result;
 }
@@ -447,9 +447,9 @@ static void CAPeripheralOnNameLost(GDBusConnection * connection,
  */
 static gboolean CAPeripheralEventLoopStarted(gpointer user_data)
 {
-    ca_cond const condition = user_data;
+    oc_cond const condition = user_data;
 
-    ca_cond_signal(condition);  // For service registration
+    oc_cond_signal(condition);  // For service registration
 
     return G_SOURCE_REMOVE;
 }
@@ -515,7 +515,7 @@ static void CAPeripheralStartEventLoop(void * data)
                 "manager interface.");
     }
 
-    ca_mutex_lock(g_context.lock);
+    oc_mutex_lock(g_context.lock);
 
     assert(g_context.event_loop == NULL);
     g_context.event_loop = event_loop;
@@ -542,7 +542,7 @@ static void CAPeripheralStartEventLoop(void * data)
                                 context->connection,
                                 advertising_managers);
 
-    ca_mutex_unlock(g_context.lock);
+    oc_mutex_unlock(g_context.lock);
 
     /*
       Add an idle handler that notifies a thread waiting for the
@@ -571,12 +571,12 @@ static void CAPeripheralStartEventLoop(void * data)
 
 static void CAPeripheralStopEventLoop(CAPeripheralContext * context)
 {
-    ca_mutex_lock(context->lock);
+    oc_mutex_lock(context->lock);
 
     GMainLoop * const event_loop = context->event_loop;
     context->event_loop = NULL;
 
-    ca_mutex_unlock(context->lock);
+    oc_mutex_unlock(context->lock);
 
     if (event_loop != NULL)
     {
@@ -596,14 +596,14 @@ static void CAPeripheralStopEventLoop(CAPeripheralContext * context)
 
 void CAPeripheralInitialize()
 {
-    g_context.lock      = ca_mutex_new();
-    g_context.condition = ca_cond_new();
+    g_context.lock      = oc_mutex_new();
+    g_context.condition = oc_cond_new();
 }
 
 void CAPeripheralFinalize()
 {
-    ca_cond_free(g_context.condition);
-    ca_mutex_free(g_context.lock);
+    oc_cond_free(g_context.condition);
+    oc_mutex_free(g_context.lock);
 }
 
 CAResult_t CAPeripheralStart(CALEContext * context)
@@ -653,21 +653,21 @@ CAResult_t CAPeripheralStart(CALEContext * context)
     static uint64_t const timeout =
         2 * MICROSECS_PER_SEC;  // Microseconds
 
-    ca_mutex_lock(g_context.lock);
+    oc_mutex_lock(g_context.lock);
 
     for (int i = 0;
          g_context.gatt_services == NULL && i < max_retries;
          ++i)
     {
-        if (ca_cond_wait_for(g_context.condition,
+        if (oc_cond_wait_for(g_context.condition,
                              g_context.lock,
-                             timeout) == CA_WAIT_SUCCESS)
+                             timeout) == OC_WAIT_SUCCESS)
         {
             result = CA_STATUS_OK;
         }
     }
 
-    ca_mutex_unlock(g_context.lock);
+    oc_mutex_unlock(g_context.lock);
 
     if (result != CA_STATUS_OK)
     {
@@ -718,7 +718,7 @@ CAResult_t CAPeripheralStop()
 
     CAPeripheralStopEventLoop(&g_context);
 
-    ca_mutex_lock(g_context.lock);
+    oc_mutex_lock(g_context.lock);
 
     guint const owner_id = g_context.owner_id;
     g_context.owner_id = 0;
@@ -728,7 +728,7 @@ CAResult_t CAPeripheralStop()
 
     g_context.base = NULL;
 
-    ca_mutex_unlock(g_context.lock);
+    oc_mutex_unlock(g_context.lock);
 
     CALEAdvertisementDestroy(&g_context.advertisement);
 
@@ -741,9 +741,9 @@ CAResult_t CAPeripheralStop()
 
 void CAPeripheralForEachService(GFunc func, void * user_data)
 {
-    ca_mutex_lock(g_context.lock);
+    oc_mutex_lock(g_context.lock);
 
     g_list_foreach(g_context.gatt_services, func, user_data);
 
-    ca_mutex_unlock(g_context.lock);
+    oc_mutex_unlock(g_context.lock);
 }
index 419edb4..2333cb9 100644 (file)
@@ -78,7 +78,7 @@ typedef struct _CAPeripheralContext
     GMainLoop * event_loop;
 
     /// Mutex used to synchronize access to context fields.
-    ca_mutex lock;
+    oc_mutex lock;
 
     /**
      * Service registration condition variable.
@@ -90,7 +90,7 @@ typedef struct _CAPeripheralContext
      *
      * @see @c GMainLoop documentation for further details.
      */
-    ca_cond condition;
+    oc_cond condition;
 
 } CAPeripheralContext;
 
index c50ba1b..921fbd6 100644 (file)
@@ -51,7 +51,7 @@ bool CAGattRecv(CAGattRecvInfo * info,
 {
     uint32_t sent_length = 0;
 
-    ca_mutex_lock(info->context->lock);
+    oc_mutex_lock(info->context->lock);
 
     bool const success =
         info->on_packet_received(info->peer,
@@ -59,7 +59,7 @@ bool CAGattRecv(CAGattRecvInfo * info,
                                  length,
                                  &sent_length) == CA_STATUS_OK;
 
-    ca_mutex_unlock(info->context->lock);
+    oc_mutex_unlock(info->context->lock);
 
     return success && length == sent_length;
 }
index ac0f8f3..50148bd 100644 (file)
@@ -44,11 +44,11 @@ bool CAGetBlueZManagedObjectProxies(GList ** proxies,
     */
     bool success = true;
 
-    ca_mutex_lock(context->lock);
+    oc_mutex_lock(context->lock);
 
     if (context->objects == NULL)
     {
-        ca_mutex_unlock(context->lock);
+        oc_mutex_unlock(context->lock);
         return success;
     }
 
@@ -84,7 +84,7 @@ bool CAGetBlueZManagedObjectProxies(GList ** proxies,
         }
     }
 
-    ca_mutex_unlock(context->lock);
+    oc_mutex_unlock(context->lock);
 
     return success;
 }
index f402124..dc33e14 100644 (file)
@@ -30,7 +30,7 @@
 #include <pthread.h>
 #include <gio/gio.h>
 
-#include "camutex.h"
+#include "octhread.h"
 #include "uarraylist.h"
 #include "caqueueingthread.h"
 #include "caadapterutils.h"
@@ -61,7 +61,7 @@ static u_arraylist_t *g_multicastDataList = NULL;
 /**
  * Mutex to synchronize the access to Pending multicast data list.
  */
-static ca_mutex g_multicastDataListMutex = NULL;
+static oc_mutex g_multicastDataListMutex = NULL;
 
 /**
  * List of devices discovered.
@@ -71,17 +71,17 @@ static u_arraylist_t *g_deviceDiscoveredList = NULL;
 /**
  * Mutex to synchronize the access to discovered devices list.
  */
-static ca_mutex g_deviceDiscoveredListMutex = NULL;
+static oc_mutex g_deviceDiscoveredListMutex = NULL;
 
 /**
  * Condition to start the timer for scanning.
  */
-static ca_cond g_startTimerCond = NULL;
+static oc_cond g_startTimerCond = NULL;
 
 /**
  * Condition for scanning Time interval.
  */
-static ca_cond g_scanningTimeCond = NULL;
+static oc_cond g_scanningTimeCond = NULL;
 
 /**
  * This contains the list of OIC services a client connect tot.
@@ -91,7 +91,7 @@ static LEServerInfoList *g_LEServerList = NULL;
 /**
  * Mutex to synchronize access to BleServiceList.
  */
-static ca_mutex g_LEServerListMutex = NULL;
+static oc_mutex g_LEServerListMutex = NULL;
 
 /**
  * Boolean variable to keep the state of the GATT Client.
@@ -102,34 +102,34 @@ static bool g_isLEGattClientStarted = false;
  * Mutex to synchronize access to the requestResponse callback to be called
  * when the data needs to be sent from GATTClient.
  */
-static ca_mutex g_LEReqRespClientCbMutex = NULL;
+static oc_mutex g_LEReqRespClientCbMutex = NULL;
 
 /**
  * Mutex to synchronize access to the requestResponse callback to be called
  * when the data needs to be sent from GATTClient.
  */
-static ca_mutex g_LEClientConnectMutex = NULL;
+static oc_mutex g_LEClientConnectMutex = NULL;
 
 /**
  * Mutex to synchronize the calls to be done to the platform from GATTClient
  * interfaces from different threads.
  */
-static ca_mutex g_LEClientStateMutex = NULL;
+static oc_mutex g_LEClientStateMutex = NULL;
 
 /**
  * Mutex to synchronize the task to be pushed to thread pool.
  */
-static ca_mutex g_LEClientThreadPoolMutex = NULL;
+static oc_mutex g_LEClientThreadPoolMutex = NULL;
 
 /**
  * Mutex to synchronize the task to write characteristic one packet after another.
  */
-static ca_mutex g_threadWriteCharacteristicMutex = NULL;
+static oc_mutex g_threadWriteCharacteristicMutex = NULL;
 
 /**
  * Condition for Writing characteristic.
  */
-static ca_cond g_threadWriteCharacteristicCond = NULL;
+static oc_cond g_threadWriteCharacteristicCond = NULL;
 
 /**
  * Flag to check status of write characteristic.
@@ -164,7 +164,7 @@ bool CALEIsDeviceDiscovered(const char * address)
     OIC_LOG(DEBUG, TAG, "IN");
     if (g_deviceDiscoveredList)
     {
-        ca_mutex_lock(g_deviceDiscoveredListMutex);
+        oc_mutex_lock(g_deviceDiscoveredListMutex);
         uint32_t arrayLength = u_arraylist_length(g_deviceDiscoveredList);
         for (int i = 0; i < arrayLength; i++)
         {
@@ -172,12 +172,12 @@ bool CALEIsDeviceDiscovered(const char * address)
             if (0 == strcasecmp(deviceAddr, address))
             {
                 OIC_LOG(DEBUG, TAG, "Device Found");
-                ca_mutex_unlock(g_deviceDiscoveredListMutex);
+                oc_mutex_unlock(g_deviceDiscoveredListMutex);
                 return true;
             }
 
         }
-        ca_mutex_unlock(g_deviceDiscoveredListMutex);
+        oc_mutex_unlock(g_deviceDiscoveredListMutex);
     }
     OIC_LOG(DEBUG, TAG, "OUT");
     return false;
@@ -190,11 +190,11 @@ void CALEGattCharacteristicChangedCb(bt_gatt_h characteristic,
     OIC_LOG(DEBUG, TAG, "IN");
     OIC_LOG_V(DEBUG, TAG, "Changed characteristic value length [%d]", valueLen);
 
-    ca_mutex_lock(g_LEReqRespClientCbMutex);
+    oc_mutex_lock(g_LEReqRespClientCbMutex);
     if (NULL == g_LEClientDataReceivedCallback)
     {
         OIC_LOG(ERROR, TAG, "Request response callback is not set");
-        ca_mutex_unlock(g_LEReqRespClientCbMutex);
+        oc_mutex_unlock(g_LEReqRespClientCbMutex);
         return;
     }
 
@@ -203,7 +203,7 @@ void CALEGattCharacteristicChangedCb(bt_gatt_h characteristic,
 
     OIC_LOG_V(DEBUG, TAG, "Sent data Length is %d", sentLength);
 
-    ca_mutex_unlock(g_LEReqRespClientCbMutex);
+    oc_mutex_unlock(g_LEReqRespClientCbMutex);
 
     OIC_LOG(DEBUG, TAG, "OUT");
 }
@@ -219,11 +219,11 @@ void CALEGattCharacteristicWriteCb(int result, bt_gatt_h reqHandle, void *userDa
     }
     else
     {
-        ca_mutex_lock(g_threadWriteCharacteristicMutex);
+        oc_mutex_lock(g_threadWriteCharacteristicMutex);
         OIC_LOG(DEBUG, TAG, "g_isSignalSetFlag is set true and signal");
         g_isSignalSetFlag = true;
-        ca_cond_signal(g_threadWriteCharacteristicCond);
-        ca_mutex_unlock(g_threadWriteCharacteristicMutex);
+        oc_cond_signal(g_threadWriteCharacteristicCond);
+        oc_mutex_unlock(g_threadWriteCharacteristicMutex);
     }
 
     OIC_LOG(DEBUG, TAG, "OUT ");
@@ -242,14 +242,14 @@ void CALEGattConnectionStateChanged(bool connected, const char *remoteAddress)
         OIC_LOG(ERROR, TAG, "CALEGattStartDeviceDiscovery Failed");
     }
     // Signal the start timer.
-    ca_cond_signal(g_scanningTimeCond);
+    oc_cond_signal(g_scanningTimeCond);
 
     if (!connected)
     {
         OIC_LOG_V(DEBUG, TAG, "DisConnected from [%s] ", remoteAddress);
-        ca_mutex_lock(g_LEServerListMutex);
+        oc_mutex_lock(g_LEServerListMutex);
         CARemoveLEServerInfoFromList(&g_LEServerList, remoteAddress);
-        ca_mutex_unlock(g_LEServerListMutex);
+        oc_mutex_unlock(g_LEServerListMutex);
     }
     else
     {
@@ -262,12 +262,12 @@ void CALEGattConnectionStateChanged(bool connected, const char *remoteAddress)
             return;
         }
 
-        ca_mutex_lock(g_LEClientThreadPoolMutex);
+        oc_mutex_lock(g_LEClientThreadPoolMutex);
         if (NULL == g_LEClientThreadPool)
         {
             OIC_LOG(ERROR, TAG, "g_LEClientThreadPool is NULL");
             OICFree(addr);
-            ca_mutex_unlock(g_LEClientThreadPoolMutex);
+            oc_mutex_unlock(g_LEClientThreadPoolMutex);
             return;
         }
 
@@ -278,7 +278,7 @@ void CALEGattConnectionStateChanged(bool connected, const char *remoteAddress)
             OIC_LOG_V(ERROR, TAG, "ca_thread_pool_add_task failed with ret [%d]", ret);
             OICFree(addr);
         }
-        ca_mutex_unlock(g_LEClientThreadPoolMutex);
+        oc_mutex_unlock(g_LEClientThreadPoolMutex);
     }
     OIC_LOG(DEBUG, TAG, "OUT");
 }
@@ -308,7 +308,7 @@ void CALEAdapterScanResultCb(int result, bt_adapter_le_device_scan_result_info_s
     // Stop the scan before invoking bt_gatt_connect().
     CALEGattStopDeviceScanning();
 
-    ca_mutex_lock(g_deviceDiscoveredListMutex);
+    oc_mutex_lock(g_deviceDiscoveredListMutex);
     // Add the the device Discovered list.
     if (NULL == g_deviceDiscoveredList)
     {
@@ -319,12 +319,12 @@ void CALEAdapterScanResultCb(int result, bt_adapter_le_device_scan_result_info_s
     if (NULL == deviceAddr)
     {
         OIC_LOG_V(ERROR, TAG, "Device address is NULL");
-        ca_mutex_unlock(g_deviceDiscoveredListMutex);
+        oc_mutex_unlock(g_deviceDiscoveredListMutex);
         return;
     }
 
     u_arraylist_add(g_deviceDiscoveredList, (void *) deviceAddr);
-    ca_mutex_unlock(g_deviceDiscoveredListMutex);
+    oc_mutex_unlock(g_deviceDiscoveredListMutex);
 
     size_t len = strlen(scanInfo->remote_address);
 
@@ -336,12 +336,12 @@ void CALEAdapterScanResultCb(int result, bt_adapter_le_device_scan_result_info_s
     OIC_LOG_V(DEBUG, TAG,
               "Trying to do Gatt connection to [%s]", addr);
 
-    ca_mutex_lock(g_LEClientThreadPoolMutex);
+    oc_mutex_lock(g_LEClientThreadPoolMutex);
     if (NULL == g_LEClientThreadPool)
     {
         OIC_LOG(ERROR, TAG, "g_LEClientThreadPool is NULL");
         OICFree(addr);
-        ca_mutex_unlock(g_LEClientThreadPoolMutex);
+        oc_mutex_unlock(g_LEClientThreadPoolMutex);
         return;
     }
 
@@ -352,7 +352,7 @@ void CALEAdapterScanResultCb(int result, bt_adapter_le_device_scan_result_info_s
                   "ca_thread_pool_add_task failed with ret [%d]", res);
         OICFree(addr);
     }
-    ca_mutex_unlock(g_LEClientThreadPoolMutex);
+    oc_mutex_unlock(g_LEClientThreadPoolMutex);
     OIC_LOG(DEBUG, TAG, "OUT");
 }
 
@@ -360,9 +360,9 @@ void CASetLEClientThreadPoolHandle(ca_thread_pool_t handle)
 {
     OIC_LOG(DEBUG, TAG, "IN");
 
-    ca_mutex_lock(g_LEClientThreadPoolMutex);
+    oc_mutex_lock(g_LEClientThreadPoolMutex);
     g_LEClientThreadPool = handle;
-    ca_mutex_unlock(g_LEClientThreadPoolMutex);
+    oc_mutex_unlock(g_LEClientThreadPoolMutex);
 
     OIC_LOG(DEBUG, TAG, "OUT");
 }
@@ -371,11 +371,11 @@ void CASetLEReqRespClientCallback(CABLEDataReceivedCallback callback)
 {
     OIC_LOG(DEBUG, TAG, "IN");
 
-    ca_mutex_lock(g_LEReqRespClientCbMutex);
+    oc_mutex_lock(g_LEReqRespClientCbMutex);
 
     g_LEClientDataReceivedCallback = callback;
 
-    ca_mutex_unlock(g_LEReqRespClientCbMutex);
+    oc_mutex_unlock(g_LEReqRespClientCbMutex);
 
     OIC_LOG(DEBUG, TAG, "OUT");
 }
@@ -389,11 +389,11 @@ CAResult_t CAStartLEGattClient()
 {
     OIC_LOG(DEBUG, TAG, "IN");
 
-    ca_mutex_lock(g_LEClientStateMutex);
+    oc_mutex_lock(g_LEClientStateMutex);
     if (true  == g_isLEGattClientStarted)
     {
         OIC_LOG(ERROR, TAG, "Gatt Client is already running!!");
-        ca_mutex_unlock(g_LEClientStateMutex);
+        oc_mutex_unlock(g_LEClientStateMutex);
         return CA_STATUS_FAILED;
     }
 
@@ -401,20 +401,20 @@ CAResult_t CAStartLEGattClient()
     if (CA_STATUS_OK != result)
     {
         OIC_LOG(ERROR, TAG, "CABleGattSetCallbacks Failed");
-        ca_mutex_unlock(g_LEClientStateMutex);
+        oc_mutex_unlock(g_LEClientStateMutex);
         CATerminateLEGattClient();
         return CA_STATUS_FAILED;
     }
 
     g_isLEGattClientStarted = true;
-    ca_mutex_unlock(g_LEClientStateMutex);
+    oc_mutex_unlock(g_LEClientStateMutex);
 
-    ca_mutex_lock(g_LEClientThreadPoolMutex);
+    oc_mutex_lock(g_LEClientThreadPoolMutex);
     if (NULL == g_LEClientThreadPool)
     {
         OIC_LOG(ERROR, TAG, "gBleServerThreadPool is NULL");
         CATerminateGattClientMutexVariables();
-        ca_mutex_unlock(g_LEClientThreadPoolMutex);
+        oc_mutex_unlock(g_LEClientThreadPoolMutex);
         return CA_STATUS_FAILED;
     }
 
@@ -424,10 +424,10 @@ CAResult_t CAStartLEGattClient()
     {
         OIC_LOG(ERROR, TAG, "ca_thread_pool_add_task failed");
         CATerminateGattClientMutexVariables();
-        ca_mutex_unlock(g_LEClientThreadPoolMutex);
+        oc_mutex_unlock(g_LEClientThreadPoolMutex);
         return CA_STATUS_FAILED;
     }
-    ca_mutex_unlock(g_LEClientThreadPoolMutex);
+    oc_mutex_unlock(g_LEClientThreadPoolMutex);
 
     OIC_LOG(DEBUG, TAG, "OUT");
     return CA_STATUS_OK;
@@ -438,19 +438,19 @@ void CAStartTimerThread(void *data)
     OIC_LOG(DEBUG, TAG, "IN");
     while (g_isLEGattClientStarted)
     {
-        ca_mutex_lock(g_multicastDataListMutex);
+        oc_mutex_lock(g_multicastDataListMutex);
         if (!g_isMulticastInProgress)
         {
             OIC_LOG(DEBUG, TAG, "waiting....");
-            ca_cond_wait(g_startTimerCond, g_multicastDataListMutex);
+            oc_cond_wait(g_startTimerCond, g_multicastDataListMutex);
             OIC_LOG(DEBUG, TAG, "Wake up");
             g_isMulticastInProgress = true;
         }
 
         // Timed conditional wait for stopping the scan.
-        CAWaitResult_t ret = ca_cond_wait_for(g_scanningTimeCond, g_multicastDataListMutex,
+        CAWaitResult_t ret = oc_cond_wait_for(g_scanningTimeCond, g_multicastDataListMutex,
                                               TIMEOUT);
-        if (CA_WAIT_TIMEDOUT == ret)
+        if (OC_WAIT_TIMEDOUT == ret)
         {
             OIC_LOG(DEBUG, TAG, "Scan is timed Out");
             // Call stop scan.
@@ -460,14 +460,14 @@ void CAStartTimerThread(void *data)
             u_arraylist_destroy(g_multicastDataList);
             g_multicastDataList = NULL;
 
-            ca_mutex_lock(g_deviceDiscoveredListMutex);
+            oc_mutex_lock(g_deviceDiscoveredListMutex);
             u_arraylist_destroy(g_deviceDiscoveredList);
             g_deviceDiscoveredList = NULL;
-            ca_mutex_unlock(g_deviceDiscoveredListMutex);
+            oc_mutex_unlock(g_deviceDiscoveredListMutex);
 
             g_isMulticastInProgress = false;
         }
-        ca_mutex_unlock(g_multicastDataListMutex);
+        oc_mutex_unlock(g_multicastDataListMutex);
     }
 
     OIC_LOG(DEBUG, TAG, "OUT");
@@ -477,12 +477,12 @@ void CAStopLEGattClient()
 {
     OIC_LOG(DEBUG,  TAG, "IN");
 
-    ca_mutex_lock(g_LEClientStateMutex);
+    oc_mutex_lock(g_LEClientStateMutex);
 
     if (false == g_isLEGattClientStarted)
     {
         OIC_LOG(ERROR, TAG, "Gatt Client is not running to stop");
-        ca_mutex_unlock(g_LEClientStateMutex);
+        oc_mutex_unlock(g_LEClientStateMutex);
         return;
     }
 
@@ -493,34 +493,34 @@ void CAStopLEGattClient()
     g_isLEGattClientStarted = false;
 
     // Signal the conditions waiting in Start timer.
-    ca_cond_signal(g_startTimerCond);
-    ca_cond_signal(g_scanningTimeCond);
+    oc_cond_signal(g_startTimerCond);
+    oc_cond_signal(g_scanningTimeCond);
 
     // Destroy the multicast data list and device list if not empty.
     if (NULL != g_multicastDataList)
     {
-        ca_mutex_lock(g_multicastDataListMutex);
+        oc_mutex_lock(g_multicastDataListMutex);
         u_arraylist_destroy(g_multicastDataList);
         g_multicastDataList = NULL;
-        ca_mutex_unlock(g_multicastDataListMutex);
+        oc_mutex_unlock(g_multicastDataListMutex);
     }
 
     if (NULL != g_deviceDiscoveredList)
     {
-        ca_mutex_lock(g_deviceDiscoveredListMutex);
+        oc_mutex_lock(g_deviceDiscoveredListMutex);
         u_arraylist_destroy(g_deviceDiscoveredList);
         g_deviceDiscoveredList = NULL;
-        ca_mutex_unlock(g_deviceDiscoveredListMutex);
+        oc_mutex_unlock(g_deviceDiscoveredListMutex);
     }
 
-    ca_mutex_lock(g_LEServerListMutex);
+    oc_mutex_lock(g_LEServerListMutex);
     CAFreeLEServerList(g_LEServerList);
     g_LEServerList = NULL;
-    ca_mutex_unlock(g_LEServerListMutex);
+    oc_mutex_unlock(g_LEServerListMutex);
 
-    ca_mutex_lock(g_threadWriteCharacteristicMutex);
-    ca_cond_signal(g_threadWriteCharacteristicCond);
-    ca_mutex_unlock(g_threadWriteCharacteristicMutex);
+    oc_mutex_lock(g_threadWriteCharacteristicMutex);
+    oc_cond_signal(g_threadWriteCharacteristicCond);
+    oc_mutex_unlock(g_threadWriteCharacteristicMutex);
 
     CAResetRegisteredServiceCount();
 
@@ -543,7 +543,7 @@ void CAStopLEGattClient()
         OIC_LOG(ERROR, TAG, "g_eventLoop context is NULL");
     }
 
-    ca_mutex_unlock(g_LEClientStateMutex);
+    oc_mutex_unlock(g_LEClientStateMutex);
 
     OIC_LOG(DEBUG,  TAG, "OUT");
 }
@@ -575,110 +575,110 @@ CAResult_t CAInitGattClientMutexVariables()
     OIC_LOG(DEBUG,  TAG, "IN");
     if (NULL == g_LEClientStateMutex)
     {
-        g_LEClientStateMutex = ca_mutex_new();
+        g_LEClientStateMutex = oc_mutex_new();
         if (NULL == g_LEClientStateMutex)
         {
-            OIC_LOG(ERROR, TAG, "ca_mutex_new failed");
+            OIC_LOG(ERROR, TAG, "oc_mutex_new failed");
             return CA_STATUS_FAILED;
         }
     }
 
     if (NULL == g_LEServerListMutex)
     {
-        g_LEServerListMutex = ca_mutex_new();
+        g_LEServerListMutex = oc_mutex_new();
         if (NULL == g_LEServerListMutex)
         {
-            OIC_LOG(ERROR, TAG, "ca_mutex_new failed");
+            OIC_LOG(ERROR, TAG, "oc_mutex_new failed");
             return CA_STATUS_FAILED;
         }
     }
 
     if (NULL == g_LEReqRespClientCbMutex)
     {
-        g_LEReqRespClientCbMutex = ca_mutex_new();
+        g_LEReqRespClientCbMutex = oc_mutex_new();
         if (NULL == g_LEReqRespClientCbMutex)
         {
-            OIC_LOG(ERROR, TAG, "ca_mutex_new failed");
+            OIC_LOG(ERROR, TAG, "oc_mutex_new failed");
             return CA_STATUS_FAILED;
         }
     }
 
     if (NULL == g_LEClientThreadPoolMutex)
     {
-        g_LEClientThreadPoolMutex = ca_mutex_new();
+        g_LEClientThreadPoolMutex = oc_mutex_new();
         if (NULL == g_LEClientThreadPoolMutex)
         {
-            OIC_LOG(ERROR, TAG, "ca_mutex_new failed");
+            OIC_LOG(ERROR, TAG, "oc_mutex_new failed");
             return CA_STATUS_FAILED;
         }
     }
 
     if (NULL == g_LEClientConnectMutex)
     {
-        g_LEClientConnectMutex = ca_mutex_new();
+        g_LEClientConnectMutex = oc_mutex_new();
         if (NULL == g_LEClientConnectMutex)
         {
-            OIC_LOG(ERROR, TAG, "ca_mutex_new failed");
+            OIC_LOG(ERROR, TAG, "oc_mutex_new failed");
             return CA_STATUS_FAILED;
         }
     }
 
     if (NULL == g_multicastDataListMutex)
     {
-        g_multicastDataListMutex = ca_mutex_new();
+        g_multicastDataListMutex = oc_mutex_new();
         if (NULL == g_multicastDataListMutex)
         {
-            OIC_LOG(ERROR, TAG, "ca_mutex_new failed");
+            OIC_LOG(ERROR, TAG, "oc_mutex_new failed");
             return CA_STATUS_FAILED;
         }
     }
 
     if (NULL == g_deviceDiscoveredListMutex)
     {
-        g_deviceDiscoveredListMutex = ca_mutex_new();
+        g_deviceDiscoveredListMutex = oc_mutex_new();
         if (NULL == g_deviceDiscoveredListMutex)
         {
-            OIC_LOG(ERROR, TAG, "ca_mutex_new failed");
+            OIC_LOG(ERROR, TAG, "oc_mutex_new failed");
             return CA_STATUS_FAILED;
         }
     }
 
     if (NULL == g_threadWriteCharacteristicMutex)
     {
-        g_threadWriteCharacteristicMutex = ca_mutex_new();
+        g_threadWriteCharacteristicMutex = oc_mutex_new();
         if (NULL == g_threadWriteCharacteristicMutex)
         {
-            OIC_LOG(ERROR, TAG, "ca_mutex_new has failed");
+            OIC_LOG(ERROR, TAG, "oc_mutex_new has failed");
             return CA_STATUS_FAILED;
         }
     }
 
     if (NULL == g_startTimerCond)
     {
-        g_startTimerCond = ca_cond_new();
+        g_startTimerCond = oc_cond_new();
         if (NULL == g_startTimerCond)
         {
-            OIC_LOG(ERROR, TAG, "ca_cond_new failed");
+            OIC_LOG(ERROR, TAG, "oc_cond_new failed");
             return CA_STATUS_FAILED;
         }
     }
 
     if (NULL == g_scanningTimeCond)
     {
-        g_scanningTimeCond = ca_cond_new();
+        g_scanningTimeCond = oc_cond_new();
         if (NULL == g_scanningTimeCond)
         {
-            OIC_LOG(ERROR, TAG, "ca_cond_new failed");
+            OIC_LOG(ERROR, TAG, "oc_cond_new failed");
             return CA_STATUS_FAILED;
         }
     }
 
     if (NULL == g_threadWriteCharacteristicCond)
     {
-        g_threadWriteCharacteristicCond = ca_cond_new();
+        g_threadWriteCharacteristicCond = oc_cond_new();
         if (NULL == g_threadWriteCharacteristicCond)
         {
-            OIC_LOG(ERROR, TAG, "ca_cond_new failed");
+            OIC_LOG(ERROR, TAG, "oc_cond_new failed");
             return CA_STATUS_FAILED;
         }
     }
@@ -691,37 +691,37 @@ void CATerminateGattClientMutexVariables()
 {
     OIC_LOG(DEBUG,  TAG, "IN");
 
-    ca_mutex_free(g_LEClientStateMutex);
+    oc_mutex_free(g_LEClientStateMutex);
     g_LEClientStateMutex = NULL;
 
-    ca_mutex_free(g_LEServerListMutex);
+    oc_mutex_free(g_LEServerListMutex);
     g_LEServerListMutex = NULL;
 
-    ca_mutex_free(g_LEReqRespClientCbMutex);
+    oc_mutex_free(g_LEReqRespClientCbMutex);
     g_LEReqRespClientCbMutex = NULL;
 
-    ca_mutex_free(g_LEClientConnectMutex);
+    oc_mutex_free(g_LEClientConnectMutex);
     g_LEClientConnectMutex = NULL;
 
-    ca_mutex_free(g_LEClientThreadPoolMutex);
+    oc_mutex_free(g_LEClientThreadPoolMutex);
     g_LEClientThreadPoolMutex = NULL;
 
-    ca_mutex_free(g_multicastDataListMutex);
+    oc_mutex_free(g_multicastDataListMutex);
     g_multicastDataListMutex = NULL;
 
-    ca_mutex_free(g_deviceDiscoveredListMutex);
+    oc_mutex_free(g_deviceDiscoveredListMutex);
     g_deviceDiscoveredListMutex = NULL;
 
-    ca_mutex_free(g_threadWriteCharacteristicMutex);
+    oc_mutex_free(g_threadWriteCharacteristicMutex);
     g_threadWriteCharacteristicMutex = NULL;
 
-    ca_cond_free(g_startTimerCond);
+    oc_cond_free(g_startTimerCond);
     g_startTimerCond = NULL;
 
-    ca_cond_free(g_scanningTimeCond);
+    oc_cond_free(g_scanningTimeCond);
     g_scanningTimeCond = NULL;
 
-    ca_cond_free(g_threadWriteCharacteristicCond);
+    oc_cond_free(g_threadWriteCharacteristicCond);
     g_threadWriteCharacteristicCond = NULL;
     g_isSignalSetFlag = false;
 
@@ -812,14 +812,14 @@ CAResult_t CALEGattConnect(const char *remoteAddress)
     VERIFY_NON_NULL_RET(remoteAddress, TAG,
                         "remote address is NULL", CA_STATUS_FAILED);
 
-    ca_mutex_lock(g_LEClientConnectMutex);
+    oc_mutex_lock(g_LEClientConnectMutex);
     bool isConnected = false;
     int ret = bt_device_is_profile_connected(remoteAddress, BT_PROFILE_GATT, &isConnected);
     if (BT_ERROR_NONE != ret)
     {
         OIC_LOG_V(ERROR, TAG, "bt_device_is_profile_connected Failed with ret value [%s] ",
                   CALEGetErrorMsg(ret));
-        ca_mutex_unlock(g_LEClientConnectMutex);
+        oc_mutex_unlock(g_LEClientConnectMutex);
         return CA_STATUS_FAILED;
     }
 
@@ -832,7 +832,7 @@ CAResult_t CALEGattConnect(const char *remoteAddress)
         {
             OIC_LOG_V(ERROR, TAG, "bt_gatt_connect Failed with ret value [%s] ",
                       CALEGetErrorMsg(ret));
-            ca_mutex_unlock(g_LEClientConnectMutex);
+            oc_mutex_unlock(g_LEClientConnectMutex);
             return CA_STATUS_FAILED;
         }
     }
@@ -844,17 +844,17 @@ CAResult_t CALEGattConnect(const char *remoteAddress)
         if (NULL == addr)
         {
             OIC_LOG(ERROR, TAG, "addr is NULL");
-            ca_mutex_unlock(g_LEClientConnectMutex);
+            oc_mutex_unlock(g_LEClientConnectMutex);
             return CA_STATUS_FAILED;
         }
 
-        ca_mutex_lock(g_LEClientThreadPoolMutex);
+        oc_mutex_lock(g_LEClientThreadPoolMutex);
         if (NULL == g_LEClientThreadPool)
         {
             OIC_LOG(ERROR, TAG, "g_LEClientThreadPool is NULL");
             OICFree(addr);
-            ca_mutex_unlock(g_LEClientThreadPoolMutex);
-            ca_mutex_unlock(g_LEClientConnectMutex);
+            oc_mutex_unlock(g_LEClientThreadPoolMutex);
+            oc_mutex_unlock(g_LEClientConnectMutex);
             return CA_STATUS_FAILED;
         }
 
@@ -865,9 +865,9 @@ CAResult_t CALEGattConnect(const char *remoteAddress)
             OIC_LOG_V(ERROR, TAG, "ca_thread_pool_add_task failed with ret [%d]", result);
             OICFree(addr);
         }
-        ca_mutex_unlock(g_LEClientThreadPoolMutex);
+        oc_mutex_unlock(g_LEClientThreadPoolMutex);
     }
-    ca_mutex_unlock(g_LEClientConnectMutex);
+    oc_mutex_unlock(g_LEClientConnectMutex);
 
     OIC_LOG(DEBUG, TAG, "OUT");
     return result;
@@ -1004,7 +1004,7 @@ CAResult_t CALEGattDiscoverServices(const char *remoteAddress)
     serverInfo->writeChar = writeChrHandle;
     serverInfo->remoteAddress = OICStrdup(remoteAddress);
 
-    ca_mutex_lock(g_LEServerListMutex);
+    oc_mutex_lock(g_LEServerListMutex);
     CAResult_t result = CAAddLEServerInfoToList(&g_LEServerList, serverInfo);
     if (CA_STATUS_OK != result)
     {
@@ -1013,12 +1013,12 @@ CAResult_t CALEGattDiscoverServices(const char *remoteAddress)
         CALEGattDisConnect(remoteAddress);
         return CA_STATUS_FAILED;
     }
-    ca_mutex_unlock(g_LEServerListMutex);
+    oc_mutex_unlock(g_LEServerListMutex);
 
     // Send the data of pending multicast data list if any.
     if (g_multicastDataList)
     {
-        ca_mutex_lock(g_multicastDataListMutex);
+        oc_mutex_lock(g_multicastDataListMutex);
         uint32_t arrayLength = u_arraylist_length(g_multicastDataList);
         for (int i = 0; i < arrayLength; i++)
         {
@@ -1031,7 +1031,7 @@ CAResult_t CALEGattDiscoverServices(const char *remoteAddress)
             CAUpdateCharacteristicsToGattServer(remoteAddress, multicastData->data,
                                                 multicastData->dataLen, LE_UNICAST, 0);
         }
-        ca_mutex_unlock(g_multicastDataListMutex);
+        oc_mutex_unlock(g_multicastDataListMutex);
     }
 
     OIC_LOG(DEBUG, TAG, "OUT");
@@ -1055,7 +1055,7 @@ CAResult_t  CAUpdateCharacteristicsToGattServer(const char *remoteAddress,
     LEServerInfo *leServerInfo = NULL;
     CAResult_t ret =  CA_STATUS_FAILED;
 
-    ca_mutex_lock(g_LEServerListMutex);
+    oc_mutex_lock(g_LEServerListMutex);
     if (LE_UNICAST == type)
     {
         ret = CAGetLEServerInfo(g_LEServerList, remoteAddress, &leServerInfo);
@@ -1064,7 +1064,7 @@ CAResult_t  CAUpdateCharacteristicsToGattServer(const char *remoteAddress,
     {
         ret = CAGetLEServerInfoByPosition(g_LEServerList, position, &leServerInfo);
     }
-    ca_mutex_unlock(g_LEServerListMutex);
+    oc_mutex_unlock(g_LEServerListMutex);
 
     if (CA_STATUS_OK != ret)
     {
@@ -1099,23 +1099,23 @@ CAResult_t  CAUpdateCharacteristicsToGattServer(const char *remoteAddress,
 
     // wait for callback for write Characteristic with success to sent data
     OIC_LOG_V(DEBUG, TAG, "callback flag is %d", g_isSignalSetFlag);
-    ca_mutex_lock(g_threadWriteCharacteristicMutex);
+    oc_mutex_lock(g_threadWriteCharacteristicMutex);
     if (!g_isSignalSetFlag)
     {
         OIC_LOG(DEBUG, TAG, "wait for callback to notify writeCharacteristic is success");
-        if (CA_WAIT_SUCCESS != ca_cond_wait_for(g_threadWriteCharacteristicCond,
+        if (OC_WAIT_SUCCESS != oc_cond_wait_for(g_threadWriteCharacteristicCond,
                                   g_threadWriteCharacteristicMutex,
                                   WAIT_TIME_WRITE_CHARACTERISTIC))
         {
             OIC_LOG(ERROR, TAG, "there is no response. write has failed");
             g_isSignalSetFlag = false;
-            ca_mutex_unlock(g_threadWriteCharacteristicMutex);
+            oc_mutex_unlock(g_threadWriteCharacteristicMutex);
             return CA_SEND_FAILED;
         }
     }
     // reset flag set by writeCharacteristic Callback
     g_isSignalSetFlag = false;
-    ca_mutex_unlock(g_threadWriteCharacteristicMutex);
+    oc_mutex_unlock(g_threadWriteCharacteristicMutex);
 
     OIC_LOG(DEBUG, TAG, "OUT");
     return CA_STATUS_OK;
@@ -1167,13 +1167,13 @@ CAResult_t CAUpdateCharacteristicsToAllGattServers(const uint8_t *data, uint32_t
     memcpy(multicastData->data, data, dataLen);
     multicastData->dataLen = dataLen;
 
-    ca_mutex_lock(g_multicastDataListMutex);
+    oc_mutex_lock(g_multicastDataListMutex);
     if (NULL == g_multicastDataList)
     {
         g_multicastDataList = u_arraylist_create();
     }
     u_arraylist_add(g_multicastDataList, (void *)multicastData);
-    ca_mutex_unlock(g_multicastDataListMutex);
+    oc_mutex_unlock(g_multicastDataListMutex);
 
     // Start the scanning.
     CAResult_t result = CALEGattStartDeviceScanning();
@@ -1184,7 +1184,7 @@ CAResult_t CAUpdateCharacteristicsToAllGattServers(const uint8_t *data, uint32_t
     }
 
     // Start the timer by signalling it.
-    ca_cond_signal(g_startTimerCond);
+    oc_cond_signal(g_startTimerCond);
 
 exit:
     OIC_LOG(DEBUG, TAG, "OUT ");
index 2e2156b..9fde840 100644 (file)
@@ -32,7 +32,7 @@
 #include <bluetooth_internal.h>
 #include <bluetooth_type.h>
 
-#include "camutex.h"
+#include "octhread.h"
 #include "caleadapter.h"
 #include "caadapterutils.h"
 #include "oic_string.h"
@@ -57,13 +57,13 @@ static CALEConnectionStateChangedCallback g_bleConnectionStateChangedCallback =
  * Mutex to synchronize access to the deviceStateChanged Callback when the state
  *           of the LE adapter gets change.
  */
-static ca_mutex g_bleDeviceStateChangedCbMutex = NULL;
+static oc_mutex g_bleDeviceStateChangedCbMutex = NULL;
 
 /**
  * Mutex to synchronize access to the ConnectionStateChanged Callback when the state
  * of the LE adapter gets change.
  */
-static ca_mutex g_bleConnectionStateChangedCbMutex = NULL;
+static oc_mutex g_bleConnectionStateChangedCbMutex = NULL;
 
 /**
 * This is the callback which will be called when the adapter state gets changed.
@@ -96,21 +96,21 @@ CAResult_t CAInitializeLENetworkMonitor()
 
     if (NULL == g_bleDeviceStateChangedCbMutex)
     {
-        g_bleDeviceStateChangedCbMutex = ca_mutex_new();
+        g_bleDeviceStateChangedCbMutex = oc_mutex_new();
         if (NULL == g_bleDeviceStateChangedCbMutex)
         {
-            OIC_LOG(ERROR, TAG, "ca_mutex_new failed");
+            OIC_LOG(ERROR, TAG, "oc_mutex_new failed");
             return CA_STATUS_FAILED;
         }
     }
 
     if (NULL == g_bleConnectionStateChangedCbMutex)
     {
-        g_bleConnectionStateChangedCbMutex = ca_mutex_new();
+        g_bleConnectionStateChangedCbMutex = oc_mutex_new();
         if (NULL == g_bleConnectionStateChangedCbMutex)
         {
-            OIC_LOG(ERROR, TAG, "ca_mutex_new failed");
-            ca_mutex_free(g_bleDeviceStateChangedCbMutex);
+            OIC_LOG(ERROR, TAG, "oc_mutex_new failed");
+            oc_mutex_free(g_bleDeviceStateChangedCbMutex);
             return CA_STATUS_FAILED;
         }
     }
@@ -124,10 +124,10 @@ void CATerminateLENetworkMonitor()
 {
     OIC_LOG(DEBUG, TAG, "IN");
 
-    ca_mutex_free(g_bleDeviceStateChangedCbMutex);
+    oc_mutex_free(g_bleDeviceStateChangedCbMutex);
     g_bleDeviceStateChangedCbMutex = NULL;
 
-    ca_mutex_free(g_bleConnectionStateChangedCbMutex);
+    oc_mutex_free(g_bleConnectionStateChangedCbMutex);
     g_bleConnectionStateChangedCbMutex = NULL;
 
     OIC_LOG(DEBUG, TAG, "OUT");
@@ -243,9 +243,9 @@ CAResult_t CAGetLEAddress(char **local_address)
 CAResult_t CASetLEAdapterStateChangedCb(CALEDeviceStateChangedCallback callback)
 {
     OIC_LOG(DEBUG, TAG, "IN");
-    ca_mutex_lock(g_bleDeviceStateChangedCbMutex);
+    oc_mutex_lock(g_bleDeviceStateChangedCbMutex);
     g_bleDeviceStateChangedCallback = callback;
-    ca_mutex_unlock(g_bleDeviceStateChangedCbMutex);
+    oc_mutex_unlock(g_bleDeviceStateChangedCbMutex);
     OIC_LOG(DEBUG, TAG, "OUT");
     return CA_STATUS_OK;
 }
@@ -253,9 +253,9 @@ CAResult_t CASetLEAdapterStateChangedCb(CALEDeviceStateChangedCallback callback)
 CAResult_t CAUnSetLEAdapterStateChangedCb()
 {
     OIC_LOG(DEBUG, TAG, "IN");
-    ca_mutex_lock(g_bleDeviceStateChangedCbMutex);
+    oc_mutex_lock(g_bleDeviceStateChangedCbMutex);
     g_bleDeviceStateChangedCallback = NULL;
-    ca_mutex_unlock(g_bleDeviceStateChangedCbMutex);
+    oc_mutex_unlock(g_bleDeviceStateChangedCbMutex);
     OIC_LOG(DEBUG, TAG, "OUT");
     return CA_STATUS_OK;
 }
@@ -263,9 +263,9 @@ CAResult_t CAUnSetLEAdapterStateChangedCb()
 CAResult_t CASetLENWConnectionStateChangedCb(CALEConnectionStateChangedCallback callback)
 {
     OIC_LOG(DEBUG, TAG, "IN");
-    ca_mutex_lock(g_bleConnectionStateChangedCbMutex);
+    oc_mutex_lock(g_bleConnectionStateChangedCbMutex);
     g_bleConnectionStateChangedCallback = callback;
-    ca_mutex_unlock(g_bleConnectionStateChangedCbMutex);
+    oc_mutex_unlock(g_bleConnectionStateChangedCbMutex);
     OIC_LOG(DEBUG, TAG, "OUT");
     return CA_STATUS_OK;
 }
@@ -273,9 +273,9 @@ CAResult_t CASetLENWConnectionStateChangedCb(CALEConnectionStateChangedCallback
 CAResult_t CAUnsetLENWConnectionStateChangedCb()
 {
     OIC_LOG(DEBUG, TAG, "IN");
-    ca_mutex_lock(g_bleConnectionStateChangedCbMutex);
+    oc_mutex_lock(g_bleConnectionStateChangedCbMutex);
     g_bleConnectionStateChangedCallback = NULL;
-    ca_mutex_unlock(g_bleConnectionStateChangedCbMutex);
+    oc_mutex_unlock(g_bleConnectionStateChangedCbMutex);
     OIC_LOG(DEBUG, TAG, "OUT");
     return CA_STATUS_OK;
 }
@@ -285,12 +285,12 @@ void CALEAdapterStateChangedCb(int result, bt_adapter_state_e adapter_state,
 {
     OIC_LOG(DEBUG, TAG, "IN");
 
-    ca_mutex_lock(g_bleDeviceStateChangedCbMutex);
+    oc_mutex_lock(g_bleDeviceStateChangedCbMutex);
 
     if (NULL == g_bleDeviceStateChangedCallback)
     {
         OIC_LOG(ERROR, TAG, "g_bleDeviceStateChangedCallback is NULL!");
-        ca_mutex_unlock(g_bleDeviceStateChangedCbMutex);
+        oc_mutex_unlock(g_bleDeviceStateChangedCbMutex);
         return;
     }
 
@@ -298,7 +298,7 @@ void CALEAdapterStateChangedCb(int result, bt_adapter_state_e adapter_state,
     {
         OIC_LOG(DEBUG, TAG, "Adapter is disabled");
         g_bleDeviceStateChangedCallback(CA_ADAPTER_DISABLED);
-        ca_mutex_unlock(g_bleDeviceStateChangedCbMutex);
+        oc_mutex_unlock(g_bleDeviceStateChangedCbMutex);
         return;
     }
 
@@ -312,7 +312,7 @@ void CALEAdapterStateChangedCb(int result, bt_adapter_state_e adapter_state,
     }
 
     g_bleDeviceStateChangedCallback(CA_ADAPTER_ENABLED);
-    ca_mutex_unlock(g_bleDeviceStateChangedCbMutex);
+    oc_mutex_unlock(g_bleDeviceStateChangedCbMutex);
 
     OIC_LOG(DEBUG, TAG, "OUT");
 }
@@ -324,17 +324,17 @@ void CALENWConnectionStateChangedCb(int result, bool connected,
 
     VERIFY_NON_NULL_VOID(remoteAddress, TAG, "remote address is NULL");
 
-    ca_mutex_lock(g_bleConnectionStateChangedCbMutex);
+    oc_mutex_lock(g_bleConnectionStateChangedCbMutex);
     char *addr = OICStrdup(remoteAddress);
     if (NULL == addr)
     {
         OIC_LOG(ERROR, TAG, "addr is NULL");
-        ca_mutex_unlock(g_bleConnectionStateChangedCbMutex);
+        oc_mutex_unlock(g_bleConnectionStateChangedCbMutex);
         return;
     }
     g_bleConnectionStateChangedCallback(CA_ADAPTER_GATT_BTLE, addr, connected);
     OICFree(addr);
-    ca_mutex_unlock(g_bleConnectionStateChangedCbMutex);
+    oc_mutex_unlock(g_bleConnectionStateChangedCbMutex);
 
     OIC_LOG(DEBUG, TAG, "OUT");
 }
index 532ec6a..fdf2e0a 100644 (file)
@@ -21,7 +21,7 @@
 #include "caleserver.h"
 #include "cacommon.h"
 #include "cacommonutil.h"
-#include "camutex.h"
+#include "octhread.h"
 #include "caqueueingthread.h"
 #include "cagattservice.h"
 #include "oic_string.h"
@@ -82,28 +82,28 @@ static bool g_isLEGattServerStarted = false;
 /**
  * Mutex to synchronize the calls to start and stop server.
  */
-static ca_mutex g_leServerStateMutex = NULL;
+static oc_mutex g_leServerStateMutex = NULL;
 
 /**
  * Mutex to synchronize writing operations on the characteristics.
  */
-static  ca_mutex g_leCharacteristicMutex = NULL;
+static  oc_mutex g_leCharacteristicMutex = NULL;
 
 /**
  * Mutex to synchronize to creation of OIC service.
  */
-static  ca_mutex g_leServiceMutex = NULL;
+static  oc_mutex g_leServiceMutex = NULL;
 
 /**
  * Mutex to synchronize access to the requestResponse callback to be called
  * when the data needs to be sent from GATTClient.
  */
-static  ca_mutex g_leReqRespCbMutex = NULL;
+static  oc_mutex g_leReqRespCbMutex = NULL;
 
 /**
  * Mutex to synchronize the task to be pushed to thread pool.
  */
-static ca_mutex g_leServerThreadPoolMutex = NULL;
+static oc_mutex g_leServerThreadPoolMutex = NULL;
 
 /**
  * Reference to threadpool.
@@ -123,7 +123,7 @@ static LEClientInfoList *g_LEClientList = NULL;
 /**
  * Mutex to synchronize access to LE ClientList.
  */
-static ca_mutex g_LEClientListMutex = NULL;
+static oc_mutex g_LEClientListMutex = NULL;
 
 void CALEGattServerConnectionStateChanged(bool connected, const char *remoteAddress)
 {
@@ -133,23 +133,23 @@ void CALEGattServerConnectionStateChanged(bool connected, const char *remoteAddr
     {
         OIC_LOG_V(DEBUG, TAG, "Connected to [%s]", remoteAddress);
         char *addr = OICStrdup(remoteAddress);
-        ca_mutex_lock(g_LEClientListMutex);
+        oc_mutex_lock(g_LEClientListMutex);
         CAResult_t result  = CAAddLEClientInfoToList(&g_LEClientList, addr);
         if (CA_STATUS_OK != result)
         {
             OIC_LOG(ERROR, TAG, "CAAddLEClientInfoToList failed");
-            ca_mutex_unlock(g_LEClientListMutex);
+            oc_mutex_unlock(g_LEClientListMutex);
             OICFree(addr);
             return;
         }
-        ca_mutex_unlock(g_LEClientListMutex);
+        oc_mutex_unlock(g_LEClientListMutex);
     }
     else
     {
         OIC_LOG_V(DEBUG, TAG, "Disconnected from [%s]", remoteAddress);
-        ca_mutex_lock(g_LEClientListMutex);
+        oc_mutex_lock(g_LEClientListMutex);
         CARemoveLEClientInfoFromList(&g_LEClientList, remoteAddress);
-        ca_mutex_unlock(g_LEClientListMutex);
+        oc_mutex_unlock(g_LEClientListMutex);
     }
 }
 
@@ -163,11 +163,11 @@ CAResult_t CAStartLEGattServer()
 {
     OIC_LOG(DEBUG, TAG, "IN");
 
-    ca_mutex_lock(g_leServerStateMutex);
+    oc_mutex_lock(g_leServerStateMutex);
     if (true == g_isLEGattServerStarted)
     {
         OIC_LOG(ERROR, TAG, "Gatt Server is already running");
-        ca_mutex_unlock(g_leServerStateMutex);
+        oc_mutex_unlock(g_leServerStateMutex);
         return CA_STATUS_OK;
     }
 
@@ -175,7 +175,7 @@ CAResult_t CAStartLEGattServer()
     if (CA_STATUS_OK != ret)
     {
         OIC_LOG_V(ERROR, TAG, "CAInitLEGattServer failed[%d]", ret);
-        ca_mutex_unlock(g_leServerStateMutex);
+        oc_mutex_unlock(g_leServerStateMutex);
         CATerminateLEGattServer();
         return CA_STATUS_FAILED;
     }
@@ -186,7 +186,7 @@ CAResult_t CAStartLEGattServer()
     if (CA_STATUS_OK != ret)
     {
         OIC_LOG_V(ERROR, TAG, "CAAddNewLEServiceInGattServer failed[%d]", ret);
-        ca_mutex_unlock(g_leServerStateMutex);
+        oc_mutex_unlock(g_leServerStateMutex);
         CATerminateLEGattServer();
         return CA_STATUS_FAILED;
     }
@@ -200,7 +200,7 @@ CAResult_t CAStartLEGattServer()
     if (CA_STATUS_OK != ret)
     {
         OIC_LOG_V(ERROR, TAG, "CAAddNewCharacteristicsToGattServer failed[%d]", ret);
-        ca_mutex_unlock(g_leServerStateMutex);
+        oc_mutex_unlock(g_leServerStateMutex);
         CATerminateLEGattServer();
         return CA_STATUS_FAILED;
     }
@@ -214,7 +214,7 @@ CAResult_t CAStartLEGattServer()
     if (CA_STATUS_OK != ret )
     {
         OIC_LOG_V(ERROR, TAG, "CAAddNewCharacteristicsToGattServer failed[%d]", ret);
-        ca_mutex_unlock(g_leServerStateMutex);
+        oc_mutex_unlock(g_leServerStateMutex);
         CATerminateLEGattServer();
         return CA_STATUS_FAILED;
     }
@@ -223,7 +223,7 @@ CAResult_t CAStartLEGattServer()
     if (CA_STATUS_OK != ret )
     {
         OIC_LOG_V(ERROR, TAG, "CARegisterLEServicewithGattServer failed[%d]", ret);
-        ca_mutex_unlock(g_leServerStateMutex);
+        oc_mutex_unlock(g_leServerStateMutex);
         CATerminateLEGattServer();
         return CA_STATUS_FAILED;
     }
@@ -232,14 +232,14 @@ CAResult_t CAStartLEGattServer()
     if (CA_STATUS_OK != ret)
     {
         OIC_LOG_V(ERROR, TAG, "CALEStartAdvertise failed[%d]", ret);
-        ca_mutex_unlock(g_leServerStateMutex);
+        oc_mutex_unlock(g_leServerStateMutex);
         CATerminateLEGattServer();
         return CA_STATUS_FAILED;
     }
 
     g_isLEGattServerStarted = true;
 
-    ca_mutex_unlock(g_leServerStateMutex);
+    oc_mutex_unlock(g_leServerStateMutex);
 
     OIC_LOG(DEBUG, TAG, "OUT");
     return CA_STATUS_OK;
@@ -332,21 +332,21 @@ CAResult_t CAStopLEGattServer()
 {
     OIC_LOG(DEBUG, TAG, "IN");
 
-    ca_mutex_lock(g_leServerStateMutex);
+    oc_mutex_lock(g_leServerStateMutex);
 
     if (false == g_isLEGattServerStarted)
     {
         OIC_LOG(ERROR, TAG, "Gatt Server is not running to stop");
-        ca_mutex_unlock(g_leServerStateMutex);
+        oc_mutex_unlock(g_leServerStateMutex);
         return CA_STATUS_OK;
     }
 
     g_isLEGattServerStarted = false;
 
-    ca_mutex_lock(g_LEClientListMutex);
+    oc_mutex_lock(g_LEClientListMutex);
     CADisconnectAllClient(g_LEClientList);
     g_LEClientList = NULL;
-    ca_mutex_unlock(g_LEClientListMutex);
+    oc_mutex_unlock(g_LEClientListMutex);
 
     CAResult_t res = CALEStopAdvertise();
     {
@@ -380,7 +380,7 @@ CAResult_t CAStopLEGattServer()
         OIC_LOG(ERROR, TAG, "g_eventLoop context is NULL");
     }
 
-    ca_mutex_unlock(g_leServerStateMutex);
+    oc_mutex_unlock(g_leServerStateMutex);
 
     OIC_LOG(DEBUG, TAG, "OUT");
     return CA_STATUS_OK;
@@ -406,18 +406,18 @@ void CATerminateLEGattServer()
     OIC_LOG(DEBUG, TAG, "IN");
 
     // Service and characteristics path will be freed by the platform.
-    ca_mutex_lock(g_leServiceMutex);
+    oc_mutex_lock(g_leServiceMutex);
     g_gattSvcPath = NULL;
-    ca_mutex_unlock(g_leServiceMutex);
+    oc_mutex_unlock(g_leServiceMutex);
 
-    ca_mutex_lock(g_leCharacteristicMutex);
+    oc_mutex_lock(g_leCharacteristicMutex);
     g_gattReadCharPath = NULL;
     g_gattWriteCharPath = NULL;
-    ca_mutex_unlock(g_leCharacteristicMutex);
+    oc_mutex_unlock(g_leCharacteristicMutex);
 
-    ca_mutex_lock(g_leServerThreadPoolMutex);
+    oc_mutex_lock(g_leServerThreadPoolMutex);
     g_leServerThreadPool = NULL;
-    ca_mutex_unlock(g_leServerThreadPoolMutex);
+    oc_mutex_unlock(g_leServerThreadPoolMutex);
 
     // Terminating all mutex variables.
     CATerminateGattServerMutexVariables();
@@ -429,60 +429,60 @@ CAResult_t CAInitGattServerMutexVariables()
     OIC_LOG(DEBUG, TAG, "IN");
     if (NULL == g_leServerStateMutex)
     {
-        g_leServerStateMutex = ca_mutex_new();
+        g_leServerStateMutex = oc_mutex_new();
         if (NULL == g_leServerStateMutex)
         {
-            OIC_LOG(ERROR, TAG, "ca_mutex_new failed");
+            OIC_LOG(ERROR, TAG, "oc_mutex_new failed");
             return CA_STATUS_FAILED;
         }
     }
 
     if (NULL == g_leServiceMutex)
     {
-        g_leServiceMutex = ca_mutex_new();
+        g_leServiceMutex = oc_mutex_new();
         if (NULL == g_leServiceMutex)
         {
-            OIC_LOG(ERROR, TAG, "ca_mutex_new failed");
+            OIC_LOG(ERROR, TAG, "oc_mutex_new failed");
             return CA_STATUS_FAILED;
         }
     }
 
     if (NULL == g_leCharacteristicMutex)
     {
-        g_leCharacteristicMutex = ca_mutex_new();
+        g_leCharacteristicMutex = oc_mutex_new();
         if (NULL == g_leCharacteristicMutex)
         {
-            OIC_LOG(ERROR, TAG, "ca_mutex_new failed");
+            OIC_LOG(ERROR, TAG, "oc_mutex_new failed");
             return CA_STATUS_FAILED;
         }
     }
 
     if (NULL == g_leReqRespCbMutex)
     {
-        g_leReqRespCbMutex = ca_mutex_new();
+        g_leReqRespCbMutex = oc_mutex_new();
         if (NULL == g_leReqRespCbMutex)
         {
-            OIC_LOG(ERROR, TAG, "ca_mutex_new failed");
+            OIC_LOG(ERROR, TAG, "oc_mutex_new failed");
             return CA_STATUS_FAILED;
         }
     }
 
     if (NULL == g_leServerThreadPoolMutex)
     {
-        g_leServerThreadPoolMutex = ca_mutex_new();
+        g_leServerThreadPoolMutex = oc_mutex_new();
         if (NULL == g_leServerThreadPoolMutex)
         {
-            OIC_LOG(ERROR, TAG, "ca_mutex_new failed");
+            OIC_LOG(ERROR, TAG, "oc_mutex_new failed");
             return CA_STATUS_FAILED;
         }
     }
 
     if (NULL == g_LEClientListMutex)
     {
-        g_LEClientListMutex = ca_mutex_new();
+        g_LEClientListMutex = oc_mutex_new();
         if (NULL == g_LEClientListMutex)
         {
-            OIC_LOG(ERROR, TAG, "ca_mutex_new failed");
+            OIC_LOG(ERROR, TAG, "oc_mutex_new failed");
             return CA_STATUS_FAILED;
         }
     }
@@ -494,22 +494,22 @@ CAResult_t CAInitGattServerMutexVariables()
 void CATerminateGattServerMutexVariables()
 {
     OIC_LOG(DEBUG, TAG, "IN");
-    ca_mutex_free(g_leServerStateMutex);
+    oc_mutex_free(g_leServerStateMutex);
     g_leServerStateMutex = NULL;
 
-    ca_mutex_free(g_leServiceMutex);
+    oc_mutex_free(g_leServiceMutex);
     g_leServiceMutex = NULL;
 
-    ca_mutex_free(g_leCharacteristicMutex);
+    oc_mutex_free(g_leCharacteristicMutex);
     g_leCharacteristicMutex = NULL;
 
-    ca_mutex_free(g_leReqRespCbMutex);
+    oc_mutex_free(g_leReqRespCbMutex);
     g_leReqRespCbMutex = NULL;
 
-    ca_mutex_free(g_leServerThreadPoolMutex);
+    oc_mutex_free(g_leServerThreadPoolMutex);
     g_leServerThreadPoolMutex = NULL;
 
-    ca_mutex_free(g_LEClientListMutex);
+    oc_mutex_free(g_LEClientListMutex);
     g_LEClientListMutex = NULL;
 
     OIC_LOG(DEBUG, TAG, "OUT");
@@ -579,9 +579,9 @@ CAResult_t CADeInitLEGattServer()
 void CASetLEServerThreadPoolHandle(ca_thread_pool_t handle)
 {
     OIC_LOG(DEBUG, TAG, "IN");
-    ca_mutex_lock(g_leServerThreadPoolMutex);
+    oc_mutex_lock(g_leServerThreadPoolMutex);
     g_leServerThreadPool = handle;
-    ca_mutex_unlock(g_leServerThreadPoolMutex);
+    oc_mutex_unlock(g_leServerThreadPoolMutex);
     OIC_LOG(DEBUG, TAG, "OUT");
 }
 
@@ -595,16 +595,16 @@ CAResult_t CAAddNewLEServiceInGattServer(const char *serviceUUID)
 
     bt_gatt_service_type_e type = BT_GATT_SERVICE_TYPE_PRIMARY;
 
-    ca_mutex_lock(g_leServiceMutex);
+    oc_mutex_lock(g_leServiceMutex);
     int ret = bt_gatt_service_create(serviceUUID, type, &g_gattSvcPath);
     if (0 != ret)
     {
-        ca_mutex_unlock(g_leServiceMutex);
+        oc_mutex_unlock(g_leServiceMutex);
         OIC_LOG_V(ERROR, TAG, "bt_gatt_service_create failed with ret [%s]",
                     CALEGetErrorMsg(ret));
         return CA_STATUS_FAILED;
     }
-    ca_mutex_unlock(g_leServiceMutex);
+    oc_mutex_unlock(g_leServiceMutex);
 
     if (g_gattSvcPath)
     {
@@ -639,11 +639,11 @@ void CALEGattRemoteCharacteristicWriteCb(char *remoteAddress, bt_gatt_server_h s
 
     memcpy(data, charValue, charValueLen);
 
-    ca_mutex_lock(g_leReqRespCbMutex);
+    oc_mutex_lock(g_leReqRespCbMutex);
     if (NULL == g_leServerDataReceivedCallback)
     {
         OIC_LOG(ERROR, TAG, "gReqRespCallback is NULL!");
-        ca_mutex_unlock(g_leReqRespCbMutex);
+        oc_mutex_unlock(g_leReqRespCbMutex);
         OICFree(data);
         return;
     }
@@ -652,7 +652,7 @@ void CALEGattRemoteCharacteristicWriteCb(char *remoteAddress, bt_gatt_server_h s
     uint32_t sentLength = 0;
     g_leServerDataReceivedCallback(remoteAddress, data, charValueLen,
                                     &sentLength);
-    ca_mutex_unlock(g_leReqRespCbMutex);
+    oc_mutex_unlock(g_leReqRespCbMutex);
     OICFree(data);
     OIC_LOG(DEBUG, TAG, "OUT");
 }
@@ -740,7 +740,7 @@ CAResult_t CAAddNewCharacteristicsToGattServer(const bt_gatt_h svcPath, const ch
         return CA_STATUS_FAILED;
     }
 
-    ca_mutex_lock(g_leCharacteristicMutex);
+    oc_mutex_lock(g_leCharacteristicMutex);
 
     if (read)
     {
@@ -752,7 +752,7 @@ CAResult_t CAAddNewCharacteristicsToGattServer(const bt_gatt_h svcPath, const ch
                                         &descriptor);
         if (0 != ret)
         {
-            ca_mutex_unlock(g_leCharacteristicMutex);
+            oc_mutex_unlock(g_leCharacteristicMutex);
             OIC_LOG_V(ERROR, TAG,
                       "bt_gatt_descriptor_create  failed with ret[%s]",
                       CALEGetErrorMsg(ret));
@@ -762,7 +762,7 @@ CAResult_t CAAddNewCharacteristicsToGattServer(const bt_gatt_h svcPath, const ch
         ret = bt_gatt_characteristic_add_descriptor(charPath, descriptor);
         if (0 != ret)
         {
-            ca_mutex_unlock(g_leCharacteristicMutex);
+            oc_mutex_unlock(g_leCharacteristicMutex);
             OIC_LOG_V(ERROR, TAG,
                       "bt_gatt_characteristic_add_descriptor  failed with ret[%s]",
                       CALEGetErrorMsg(ret));
@@ -776,7 +776,7 @@ CAResult_t CAAddNewCharacteristicsToGattServer(const bt_gatt_h svcPath, const ch
         g_gattWriteCharPath = charPath;
     }
 
-    ca_mutex_unlock(g_leCharacteristicMutex);
+    oc_mutex_unlock(g_leCharacteristicMutex);
 
     OIC_LOG(DEBUG, TAG, "OUT");
     return CA_STATUS_OK;
@@ -792,12 +792,12 @@ CAResult_t CAUpdateCharacteristicsToGattClient(const char *address, const uint8_
 
     OIC_LOG_V(DEBUG, TAG, "Client's Unicast address for sending data [%s]", address);
 
-    ca_mutex_lock(g_leCharacteristicMutex);
+    oc_mutex_lock(g_leCharacteristicMutex);
 
     if (NULL  == g_gattReadCharPath)
     {
         OIC_LOG(ERROR, TAG, "g_gattReadCharPath is NULL");
-        ca_mutex_unlock(g_leCharacteristicMutex);
+        oc_mutex_unlock(g_leCharacteristicMutex);
         return CA_STATUS_FAILED;
     }
 
@@ -806,7 +806,7 @@ CAResult_t CAUpdateCharacteristicsToGattClient(const char *address, const uint8_
     {
         OIC_LOG_V(ERROR, TAG,
                   "bt_gatt_set_value failed with return [%s]", CALEGetErrorMsg(ret));
-        ca_mutex_unlock(g_leCharacteristicMutex);
+        oc_mutex_unlock(g_leCharacteristicMutex);
         return CA_STATUS_FAILED;
     }
 
@@ -816,11 +816,11 @@ CAResult_t CAUpdateCharacteristicsToGattClient(const char *address, const uint8_
     {
         OIC_LOG_V(ERROR, TAG,
                   "bt_gatt_server_notify failed with return [%s]", CALEGetErrorMsg(ret));
-        ca_mutex_unlock(g_leCharacteristicMutex);
+        oc_mutex_unlock(g_leCharacteristicMutex);
         return CA_STATUS_FAILED;
     }
 
-    ca_mutex_unlock(g_leCharacteristicMutex);
+    oc_mutex_unlock(g_leCharacteristicMutex);
 
     OIC_LOG(DEBUG, TAG, "OUT");
     return CA_STATUS_OK;
@@ -832,12 +832,12 @@ CAResult_t CAUpdateCharacteristicsToAllGattClients(const uint8_t *charValue, uin
 
     VERIFY_NON_NULL(charValue, TAG, "charValue");
 
-    ca_mutex_lock(g_leCharacteristicMutex);
+    oc_mutex_lock(g_leCharacteristicMutex);
 
     if (NULL  == g_gattReadCharPath)
     {
         OIC_LOG(ERROR, TAG, "g_gattReadCharPath is NULL");
-        ca_mutex_unlock(g_leCharacteristicMutex);
+        oc_mutex_unlock(g_leCharacteristicMutex);
         return CA_STATUS_FAILED;
     }
 
@@ -845,7 +845,7 @@ CAResult_t CAUpdateCharacteristicsToAllGattClients(const uint8_t *charValue, uin
     if (0 != ret)
     {
         OIC_LOG_V(ERROR, TAG, "bt_gatt_set_value failed with return[%s]", CALEGetErrorMsg(ret));
-        ca_mutex_unlock(g_leCharacteristicMutex);
+        oc_mutex_unlock(g_leCharacteristicMutex);
         return CA_STATUS_FAILED;
     }
 
@@ -855,11 +855,11 @@ CAResult_t CAUpdateCharacteristicsToAllGattClients(const uint8_t *charValue, uin
     {
         OIC_LOG_V(ERROR, TAG,
                   "bt_gatt_server_notify failed with return[%s]", CALEGetErrorMsg(ret));
-        ca_mutex_unlock(g_leCharacteristicMutex);
+        oc_mutex_unlock(g_leCharacteristicMutex);
         return CA_STATUS_FAILED;
     }
 
-    ca_mutex_unlock(g_leCharacteristicMutex);
+    oc_mutex_unlock(g_leCharacteristicMutex);
 
     OIC_LOG(DEBUG, TAG, "OUT");
     return CA_STATUS_OK;
@@ -869,9 +869,9 @@ void CASetLEReqRespServerCallback(CABLEDataReceivedCallback callback)
 {
     OIC_LOG(DEBUG, TAG, "IN");
 
-    ca_mutex_lock(g_leReqRespCbMutex);
+    oc_mutex_lock(g_leReqRespCbMutex);
     g_leServerDataReceivedCallback = callback;
-    ca_mutex_unlock(g_leReqRespCbMutex);
+    oc_mutex_unlock(g_leReqRespCbMutex);
 
     OIC_LOG(DEBUG, TAG, "OUT");
 }
index 60882e7..76f8ca4 100644 (file)
@@ -41,7 +41,7 @@
 #include "cablockwisetransfer.h"
 #include "oic_malloc.h"
 #include "oic_string.h"
-#include "camutex.h"
+#include "octhread.h"
 #include "logger.h"
 
 #define TAG "OIC_CA_BWT"
@@ -126,20 +126,20 @@ CAResult_t CAInitBlockWiseMutexVariables()
 {
     if (!g_context.blockDataListMutex)
     {
-        g_context.blockDataListMutex = ca_mutex_new();
+        g_context.blockDataListMutex = oc_mutex_new();
         if (!g_context.blockDataListMutex)
         {
-            OIC_LOG(ERROR, TAG, "ca_mutex_new has failed");
+            OIC_LOG(ERROR, TAG, "oc_mutex_new has failed");
             return CA_STATUS_FAILED;
         }
     }
 
     if (!g_context.blockDataSenderMutex)
     {
-        g_context.blockDataSenderMutex = ca_mutex_new();
+        g_context.blockDataSenderMutex = oc_mutex_new();
         if (!g_context.blockDataSenderMutex)
         {
-            OIC_LOG(ERROR, TAG, "ca_mutex_new has failed");
+            OIC_LOG(ERROR, TAG, "oc_mutex_new has failed");
             CATerminateBlockWiseMutexVariables();
             return CA_STATUS_FAILED;
         }
@@ -152,13 +152,13 @@ void CATerminateBlockWiseMutexVariables()
 {
     if (g_context.blockDataListMutex)
     {
-        ca_mutex_free(g_context.blockDataListMutex);
+        oc_mutex_free(g_context.blockDataListMutex);
         g_context.blockDataListMutex = NULL;
     }
 
     if (g_context.blockDataSenderMutex)
     {
-        ca_mutex_free(g_context.blockDataSenderMutex);
+        oc_mutex_free(g_context.blockDataSenderMutex);
         g_context.blockDataSenderMutex = NULL;
     }
 }
@@ -266,9 +266,9 @@ CAResult_t CAAddSendThreadQueue(const CAData_t *sendData, const CABlockDataID_t
 
     if (g_context.sendThreadFunc)
     {
-        ca_mutex_lock(g_context.blockDataSenderMutex);
+        oc_mutex_lock(g_context.blockDataSenderMutex);
         g_context.sendThreadFunc(cloneData);
-        ca_mutex_unlock(g_context.blockDataSenderMutex);
+        oc_mutex_unlock(g_context.blockDataSenderMutex);
     }
     else
     {
@@ -307,12 +307,12 @@ CAResult_t CAReceiveBlockWiseData(coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
 {
     OIC_LOG(DEBUG, TAG, "CAReceiveBlockWiseData");
     VERIFY_NON_NULL(pdu, TAG, "pdu");
-    VERIFY_NON_NULL(pdu->hdr, TAG, "pdu->hdr");
+    VERIFY_NON_NULL(pdu->transport_hdr, TAG, "pdu->transport_hdr");
     VERIFY_NON_NULL(endpoint, TAG, "endpoint");
     VERIFY_NON_NULL(receivedData, TAG, "receivedData");
 
     // check if received message type is CA_MSG_RESET
-    if (CA_EMPTY == pdu->hdr->coap_hdr_udp_t.code)
+    if (CA_EMPTY == pdu->transport_hdr->udp.code)
     {
         OIC_LOG(DEBUG, TAG, "code is CA_EMPTY..");
 
@@ -392,8 +392,8 @@ CAResult_t CAReceiveBlockWiseData(coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
     if (!isBlock1 && !isBlock2)
     {
         CABlockDataID_t* blockDataID = CACreateBlockDatablockId(
-                (CAToken_t)pdu->hdr->coap_hdr_udp_t.token,
-                pdu->hdr->coap_hdr_udp_t.token_length,
+                (CAToken_t)pdu->transport_hdr->udp.token,
+                pdu->transport_hdr->udp.token_length,
                 endpoint->port);
         if (NULL == blockDataID || blockDataID->idLength < 1)
         {
@@ -402,7 +402,7 @@ CAResult_t CAReceiveBlockWiseData(coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
             return CA_STATUS_FAILED;
         }
 
-        uint32_t code = CA_RESPONSE_CODE(pdu->hdr->coap_hdr_udp_t.code);
+        uint32_t code = CA_RESPONSE_CODE(pdu->transport_hdr->udp.code);
         if (CA_REQUEST_ENTITY_INCOMPLETE == code)
         {
             CABlockData_t *data = CAGetBlockDataFromBlockDataList(blockDataID);
@@ -496,9 +496,9 @@ CAResult_t CAProcessNextStep(const coap_pdu_t *pdu, const CAData_t *receivedData
             if (data->responseInfo)
             {
                 data->responseInfo->info.type =
-                        (pdu->hdr->coap_hdr_udp_t.type == CA_MSG_CONFIRM) ?
+                        (pdu->transport_hdr->udp.type == CA_MSG_CONFIRM) ?
                                 CA_MSG_ACKNOWLEDGE : CA_MSG_NONCONFIRM;
-                data->responseInfo->info.messageId = pdu->hdr->coap_hdr_udp_t.id;
+                data->responseInfo->info.messageId = pdu->transport_hdr->udp.id;
 
                 res = CAAddSendThreadQueue(data, blockID);
                 if (CA_STATUS_OK != res)
@@ -512,7 +512,7 @@ CAResult_t CAProcessNextStep(const coap_pdu_t *pdu, const CAData_t *receivedData
         case CA_OPTION1_RESPONSE:
         case CA_OPTION2_RESPONSE:
         case CA_OPTION1_REQUEST_BLOCK:
-            res = CASendBlockMessage(pdu, pdu->hdr->coap_hdr_udp_t.type, blockID);
+            res = CASendBlockMessage(pdu, pdu->transport_hdr->udp.type, blockID);
             if (CA_STATUS_OK != res)
             {
                 OIC_LOG(ERROR, TAG, "send has failed");
@@ -571,7 +571,7 @@ CAResult_t CAProcessNextStep(const coap_pdu_t *pdu, const CAData_t *receivedData
             }
             else if (receivedData->responseInfo)
             {
-                res = CASendBlockMessage(pdu, pdu->hdr->coap_hdr_udp_t.type, blockID);
+                res = CASendBlockMessage(pdu, pdu->transport_hdr->udp.type, blockID);
                 if (CA_STATUS_OK != res)
                 {
                     OIC_LOG(ERROR, TAG, "send has failed");
@@ -605,7 +605,7 @@ CAResult_t CASendBlockMessage(const coap_pdu_t *pdu, CAMessageType_t msgType,
                               const CABlockDataID_t *blockID)
 {
     VERIFY_NON_NULL(pdu, TAG, "pdu");
-    VERIFY_NON_NULL(pdu->hdr, TAG, "pdu->hdr");
+    VERIFY_NON_NULL(pdu->transport_hdr, TAG, "pdu->transport_hdr");
     VERIFY_NON_NULL(blockID, TAG, "blockID");
 
     CAData_t *data = CAGetDataSetFromBlockDataList(blockID);
@@ -629,13 +629,13 @@ CAResult_t CASendBlockMessage(const coap_pdu_t *pdu, CAMessageType_t msgType,
             break;
     }
 
-    uint32_t code = pdu->hdr->coap_hdr_udp_t.code;
+    uint32_t code = pdu->transport_hdr->udp.code;
     if (CA_GET == code || CA_POST == code || CA_PUT == code || CA_DELETE == code)
     {
         if (data->responseInfo)
         {
             OIC_LOG(DEBUG, TAG, "set response info");
-            data->responseInfo->info.messageId = pdu->hdr->coap_hdr_udp_t.id;
+            data->responseInfo->info.messageId = pdu->transport_hdr->udp.id;
             data->responseInfo->info.type = sentMsgType;
             data->responseInfo->result = CA_CONTINUE;
         }
@@ -673,7 +673,7 @@ CAResult_t CASendErrorMessage(const coap_pdu_t *pdu, uint8_t status,
                               CAResponseResult_t responseResult, const CABlockDataID_t *blockID)
 {
     VERIFY_NON_NULL(pdu, TAG, "pdu");
-    VERIFY_NON_NULL(pdu->hdr, TAG, "pdu->hdr");
+    VERIFY_NON_NULL(pdu->transport_hdr, TAG, "pdu->transport_hdr");
     VERIFY_NON_NULL(blockID, TAG, "blockID");
 
     // create error responseInfo
@@ -685,7 +685,7 @@ CAResult_t CASendErrorMessage(const coap_pdu_t *pdu, uint8_t status,
     }
 
     CAMessageType_t sentMsgType = CA_MSG_NONCONFIRM;
-    switch (pdu->hdr->coap_hdr_udp_t.type)
+    switch (pdu->transport_hdr->udp.type)
     {
         case CA_MSG_CONFIRM:
             sentMsgType = CA_MSG_ACKNOWLEDGE;
@@ -693,6 +693,8 @@ CAResult_t CASendErrorMessage(const coap_pdu_t *pdu, uint8_t status,
         case CA_MSG_ACKNOWLEDGE:
             sentMsgType = CA_MSG_CONFIRM;
             break;
+        default:
+            sentMsgType = CA_MSG_NONCONFIRM;
     }
 
     CAData_t *cloneData = NULL;
@@ -707,20 +709,20 @@ CAResult_t CASendErrorMessage(const coap_pdu_t *pdu, uint8_t status,
 
         if (cloneData->responseInfo)
         {
-            cloneData->responseInfo->info.messageId = pdu->hdr->coap_hdr_udp_t.id;
+            cloneData->responseInfo->info.messageId = pdu->transport_hdr->udp.id;
             cloneData->responseInfo->info.type = sentMsgType;
             cloneData->responseInfo->result = responseResult;
         }
         else
         {
-            CAInfo_t responseData = { .tokenLength = pdu->hdr->coap_hdr_udp_t.token_length };
+            CAInfo_t responseData = { .tokenLength = pdu->transport_hdr->udp.token_length };
             responseData.token = (CAToken_t) OICMalloc(responseData.tokenLength);
             if (!responseData.token)
             {
                 OIC_LOG(ERROR, TAG, "out of memory");
                 return CA_MEMORY_ALLOC_FAILED;
             }
-            memcpy(responseData.token, pdu->hdr->coap_hdr_udp_t.token, responseData.tokenLength);
+            memcpy(responseData.token, pdu->transport_hdr->udp.token, responseData.tokenLength);
 
             cloneData->responseInfo = (CAResponseInfo_t*) OICCalloc(1, sizeof(CAResponseInfo_t));
             if (!cloneData->responseInfo)
@@ -752,9 +754,9 @@ CAResult_t CASendErrorMessage(const coap_pdu_t *pdu, uint8_t status,
     // add data to send thread
     if (g_context.sendThreadFunc)
     {
-        ca_mutex_lock(g_context.blockDataSenderMutex);
+        oc_mutex_lock(g_context.blockDataSenderMutex);
         g_context.sendThreadFunc(cloneData);
-        ca_mutex_unlock(g_context.blockDataSenderMutex);
+        oc_mutex_unlock(g_context.blockDataSenderMutex);
     }
     else
     {
@@ -859,15 +861,15 @@ CAResult_t CASetNextBlockOption1(coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
 {
     OIC_LOG(INFO, TAG, "CASetNextBlockOption1");
     VERIFY_NON_NULL(pdu, TAG, "pdu");
-    VERIFY_NON_NULL(pdu->hdr, TAG, "pdu->hdr");
+    VERIFY_NON_NULL(pdu->transport_hdr, TAG, "pdu->transport_hdr");
     VERIFY_NON_NULL(endpoint, TAG, "endpoint");
     VERIFY_NON_NULL(receivedData, TAG, "receivedData");
 
     OIC_LOG_V(INFO, TAG, "num:%d, M:%d, sze:%d", block.num, block.m, block.szx);
 
     CABlockDataID_t* blockDataID = CACreateBlockDatablockId(
-            (CAToken_t)pdu->hdr->coap_hdr_udp_t.token,
-            pdu->hdr->coap_hdr_udp_t.token_length,
+            (CAToken_t)pdu->transport_hdr->udp.token,
+            pdu->transport_hdr->udp.token_length,
             endpoint->port);
     if (NULL == blockDataID || blockDataID->idLength < 1)
     {
@@ -887,7 +889,7 @@ CAResult_t CASetNextBlockOption1(coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
     }
 
     uint8_t blockWiseStatus = CA_BLOCK_UNKNOWN;
-    uint32_t code = pdu->hdr->coap_hdr_udp_t.code;
+    uint32_t code = pdu->transport_hdr->udp.code;
     if (CA_GET == code || CA_POST == code || CA_PUT == code || CA_DELETE == code)
     {
         // received message type is request
@@ -940,7 +942,7 @@ CAResult_t CASetNextBlockOption1(coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
     else
     {
         // received message type is response
-        uint32_t code = CA_RESPONSE_CODE(pdu->hdr->coap_hdr_udp_t.code);
+        uint32_t code = CA_RESPONSE_CODE(pdu->transport_hdr->udp.code);
         if (0 == block.m && (CA_REQUEST_ENTITY_INCOMPLETE != code
                 && CA_REQUEST_ENTITY_TOO_LARGE != code))
         {
@@ -1004,13 +1006,13 @@ CAResult_t CASetNextBlockOption2(coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
     OIC_LOG_V(INFO, TAG, "num:%d, M:%d, sze:%d", block.num, block.m, block.szx);
 
     VERIFY_NON_NULL(pdu, TAG, "pdu");
-    VERIFY_NON_NULL(pdu->hdr, TAG, "pdu->hdr");
+    VERIFY_NON_NULL(pdu->transport_hdr, TAG, "pdu->transport_hdr");
     VERIFY_NON_NULL(endpoint, TAG, "endpoint");
     VERIFY_NON_NULL(receivedData, TAG, "receivedData");
 
     CABlockDataID_t* blockDataID = CACreateBlockDatablockId(
-            (CAToken_t)pdu->hdr->coap_hdr_udp_t.token,
-            pdu->hdr->coap_hdr_udp_t.token_length,
+            (CAToken_t)pdu->transport_hdr->udp.token,
+            pdu->transport_hdr->udp.token_length,
             endpoint->port);
     if (NULL == blockDataID || blockDataID->idLength < 1)
     {
@@ -1030,7 +1032,7 @@ CAResult_t CASetNextBlockOption2(coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
     }
 
     uint8_t blockWiseStatus = CA_BLOCK_UNKNOWN;
-    if (0 == block.num && CA_GET == pdu->hdr->coap_hdr_udp_t.code && 0 == block.m)
+    if (0 == block.num && CA_GET == pdu->transport_hdr->udp.code && 0 == block.m)
     {
         OIC_LOG(INFO, TAG, "first block number");
 
@@ -1052,7 +1054,7 @@ CAResult_t CASetNextBlockOption2(coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
     }
     else
     {
-        uint32_t code = pdu->hdr->coap_hdr_udp_t.code;
+        uint32_t code = pdu->transport_hdr->udp.code;
         if (CA_GET == code || CA_POST == code || CA_PUT == code || CA_DELETE == code)
         {
             // received message type is request
@@ -1084,7 +1086,7 @@ CAResult_t CASetNextBlockOption2(coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
                                                                           COAP_OPTION_SIZE2,
                                                                           &(data->payloadLength));
 
-            uint32_t code = CA_RESPONSE_CODE(pdu->hdr->coap_hdr_udp_t.code);
+            uint32_t code = CA_RESPONSE_CODE(pdu->transport_hdr->udp.code);
             if (CA_REQUEST_ENTITY_INCOMPLETE != code && CA_REQUEST_ENTITY_TOO_LARGE != code)
             {
                 // check if received payload is exact
@@ -1162,7 +1164,7 @@ CAResult_t CAUpdateBlockOptionItems(CABlockData_t *currData, const coap_pdu_t *p
 
     // update block data
     CAResult_t res = CA_STATUS_OK;
-    uint32_t code = CA_RESPONSE_CODE(pdu->hdr->coap_hdr_udp_t.code);
+    uint32_t code = CA_RESPONSE_CODE(pdu->transport_hdr->udp.code);
 
     if (CA_REQUEST_ENTITY_INCOMPLETE == code || CA_REQUEST_ENTITY_TOO_LARGE == code)
     {
@@ -1257,10 +1259,10 @@ CAResult_t CANegotiateBlockSize(CABlockData_t *currData, coap_block_t *block,
     VERIFY_NON_NULL(currData, TAG, "currData");
     VERIFY_NON_NULL(block, TAG, "block");
     VERIFY_NON_NULL(pdu, TAG, "pdu");
-    VERIFY_NON_NULL(pdu->hdr, TAG, "pdu->hdr");
+    VERIFY_NON_NULL(pdu->transport_hdr, TAG, "pdu->transport_hdr");
 
     bool isReqMsg = false;
-    uint32_t code = pdu->hdr->coap_hdr_udp_t.code;
+    uint32_t code = pdu->transport_hdr->udp.code;
     if (CA_GET == code || CA_POST == code || CA_PUT == code || CA_DELETE == code)
     {
         isReqMsg = true;
@@ -1357,7 +1359,7 @@ CAResult_t CAUpdateBlockData(CABlockData_t *currData, coap_block_t block,
 CAResult_t CAUpdateMessageId(coap_pdu_t *pdu, const CABlockDataID_t *blockID)
 {
     VERIFY_NON_NULL(pdu, TAG, "pdu");
-    VERIFY_NON_NULL(pdu->hdr, TAG, "pdu->hdr");
+    VERIFY_NON_NULL(pdu->transport_hdr, TAG, "pdu->transport_hdr");
     VERIFY_NON_NULL(blockID, TAG, "blockID");
 
     // if message is sent, update messageId in block-wise transfer list
@@ -1370,7 +1372,7 @@ CAResult_t CAUpdateMessageId(coap_pdu_t *pdu, const CABlockDataID_t *blockID)
 
     if (cadata->requestInfo)
     {
-        cadata->requestInfo->info.messageId = pdu->hdr->coap_hdr_udp_t.id;
+        cadata->requestInfo->info.messageId = pdu->transport_hdr->udp.id;
     }
 
     return CA_STATUS_OK;
@@ -1382,7 +1384,7 @@ CAResult_t CAAddBlockOption(coap_pdu_t **pdu, const CAInfo_t *info,
     OIC_LOG(DEBUG, TAG, "IN-AddBlockOption");
     VERIFY_NON_NULL(pdu, TAG, "pdu");
     VERIFY_NON_NULL((*pdu), TAG, "(*pdu)");
-    VERIFY_NON_NULL((*pdu)->hdr, TAG, "(*pdu)->hdr");
+    VERIFY_NON_NULL((*pdu)->transport_hdr, TAG, "(*pdu)->transport_hdr");
     VERIFY_NON_NULL(info, TAG, "info");
     VERIFY_NON_NULL(endpoint, TAG, "endpoint");
     VERIFY_NON_NULL(options, TAG, "options");
@@ -1396,8 +1398,8 @@ CAResult_t CAAddBlockOption(coap_pdu_t **pdu, const CAInfo_t *info,
     }
 
     CABlockDataID_t* blockDataID = CACreateBlockDatablockId(
-            (CAToken_t)(*pdu)->hdr->coap_hdr_udp_t.token,
-            (*pdu)->hdr->coap_hdr_udp_t.token_length,
+            (CAToken_t)(*pdu)->transport_hdr->udp.token,
+            (*pdu)->transport_hdr->udp.token_length,
             endpoint->port);
     if (NULL == blockDataID || blockDataID->idLength < 1)
     {
@@ -1406,7 +1408,7 @@ CAResult_t CAAddBlockOption(coap_pdu_t **pdu, const CAInfo_t *info,
         goto exit;
     }
 
-    uint32_t repCode = CA_RESPONSE_CODE((*pdu)->hdr->coap_hdr_udp_t.code);
+    uint32_t repCode = CA_RESPONSE_CODE((*pdu)->transport_hdr->udp.code);
     if (CA_REQUEST_ENTITY_INCOMPLETE == repCode)
     {
         OIC_LOG(INFO, TAG, "don't use option");
@@ -1448,7 +1450,7 @@ CAResult_t CAAddBlockOption(coap_pdu_t **pdu, const CAInfo_t *info,
                 OIC_LOG_V(DEBUG, TAG, "[%d] pdu length", (*pdu)->length);
                 coap_add_option(*pdu, COAP_OPTION_KEY(*(coap_option *) opt->data),
                                 COAP_OPTION_LENGTH(*(coap_option *) opt->data),
-                                COAP_OPTION_DATA(*(coap_option *) opt->data), coap_udp);
+                                COAP_OPTION_DATA(*(coap_option *) opt->data));
             }
         }
 
@@ -1467,7 +1469,7 @@ CAResult_t CAAddBlockOption(coap_pdu_t **pdu, const CAInfo_t *info,
         }
     }
 
-    uint32_t code = (*pdu)->hdr->coap_hdr_udp_t.code;
+    uint32_t code = (*pdu)->transport_hdr->udp.code;
     if (CA_GET == code || CA_POST == code || CA_PUT == code || CA_DELETE == code)
     {
         // if received message type is RESET from remote device,
@@ -1496,7 +1498,7 @@ CAResult_t CAAddBlockOption2(coap_pdu_t **pdu, const CAInfo_t *info, size_t data
     OIC_LOG(DEBUG, TAG, "IN-AddBlockOption2");
     VERIFY_NON_NULL(pdu, TAG, "pdu");
     VERIFY_NON_NULL((*pdu), TAG, "(*pdu)");
-    VERIFY_NON_NULL((*pdu)->hdr, TAG, "(*pdu)->hdr");
+    VERIFY_NON_NULL((*pdu)->transport_hdr, TAG, "(*pdu)->transport_hdr");
     VERIFY_NON_NULL(info, TAG, "info");
     VERIFY_NON_NULL(blockID, TAG, "blockID");
     VERIFY_NON_NULL(options, TAG, "options");
@@ -1511,7 +1513,7 @@ CAResult_t CAAddBlockOption2(coap_pdu_t **pdu, const CAInfo_t *info, size_t data
     }
 
     CAResult_t res = CA_STATUS_OK;
-    uint32_t code = (*pdu)->hdr->coap_hdr_udp_t.code;
+    uint32_t code = (*pdu)->transport_hdr->udp.code;
     if (CA_GET != code && CA_POST != code && CA_PUT != code && CA_DELETE != code)
     {
         CASetMoreBitFromBlock(dataLength, block2);
@@ -1601,7 +1603,7 @@ CAResult_t CAAddBlockOption1(coap_pdu_t **pdu, const CAInfo_t *info, size_t data
     OIC_LOG(DEBUG, TAG, "IN-AddBlockOption1");
     VERIFY_NON_NULL(pdu, TAG, "pdu");
     VERIFY_NON_NULL((*pdu), TAG, "(*pdu)");
-    VERIFY_NON_NULL((*pdu)->hdr, TAG, "(*pdu)->hdr");
+    VERIFY_NON_NULL((*pdu)->transport_hdr, TAG, "(*pdu)->transport_hdr");
     VERIFY_NON_NULL(info, TAG, "info");
     VERIFY_NON_NULL(blockID, TAG, "blockID");
     VERIFY_NON_NULL(options, TAG, "options");
@@ -1615,7 +1617,7 @@ CAResult_t CAAddBlockOption1(coap_pdu_t **pdu, const CAInfo_t *info, size_t data
     }
 
     CAResult_t res = CA_STATUS_OK;
-    uint32_t code = (*pdu)->hdr->coap_hdr_udp_t.code;
+    uint32_t code = (*pdu)->transport_hdr->udp.code;
     if (CA_GET == code || CA_POST == code || CA_PUT == code || CA_DELETE == code)
     {
         CASetMoreBitFromBlock(dataLength, block1);
@@ -1744,7 +1746,7 @@ CAResult_t CAAddOptionToPDU(coap_pdu_t *pdu, coap_list_t **options)
             OIC_LOG_V(DEBUG, TAG, "[%d] pdu length", pdu->length);
             int ret = coap_add_option(pdu, COAP_OPTION_KEY(*(coap_option *) opt->data),
                                       COAP_OPTION_LENGTH(*(coap_option *) opt->data),
-                                      COAP_OPTION_DATA(*(coap_option *) opt->data), coap_udp);
+                                      COAP_OPTION_DATA(*(coap_option *) opt->data));
             if (!ret)
             {
                 return CA_STATUS_FAILED;
@@ -2000,23 +2002,23 @@ CAResult_t CAUpdatePayloadData(CABlockData_t *currData, const CAData_t *received
 CAData_t* CACreateNewDataSet(const coap_pdu_t *pdu, const CAEndpoint_t *endpoint)
 {
     VERIFY_NON_NULL_RET(pdu, TAG, "pdu", NULL);
-    VERIFY_NON_NULL_RET(pdu->hdr, TAG, "pdu->hdr", NULL);
+    VERIFY_NON_NULL_RET(pdu->transport_hdr, TAG, "pdu->transport_hdr", NULL);
     VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint", NULL);
 
     CARequestInfo_t* requestInfo = NULL;
     CAResponseInfo_t* responseInfo = NULL;
 
-    uint32_t code = pdu->hdr->coap_hdr_udp_t.code;
+    uint32_t code = pdu->transport_hdr->udp.code;
     if (CA_GET == code || CA_POST == code || CA_PUT == code || CA_DELETE == code)
     {
-        CAInfo_t responseData = { .tokenLength = pdu->hdr->coap_hdr_udp_t.token_length };
+        CAInfo_t responseData = { .tokenLength = pdu->transport_hdr->udp.token_length };
         responseData.token = (CAToken_t) OICMalloc(responseData.tokenLength);
         if (!responseData.token)
         {
             OIC_LOG(ERROR, TAG, "out of memory");
             return NULL;
         }
-        memcpy(responseData.token, pdu->hdr->coap_hdr_udp_t.token, responseData.tokenLength);
+        memcpy(responseData.token, pdu->transport_hdr->udp.token, responseData.tokenLength);
 
         responseInfo = (CAResponseInfo_t*) OICCalloc(1, sizeof(CAResponseInfo_t));
         if (!responseInfo)
@@ -2029,14 +2031,14 @@ CAData_t* CACreateNewDataSet(const coap_pdu_t *pdu, const CAEndpoint_t *endpoint
     }
     else
     {
-        CAInfo_t requestData = { .tokenLength = pdu->hdr->coap_hdr_udp_t.token_length };
+        CAInfo_t requestData = { .tokenLength = pdu->transport_hdr->udp.token_length };
         requestData.token = (CAToken_t) OICMalloc(requestData.tokenLength);
         if (!requestData.token)
         {
             OIC_LOG(ERROR, TAG, "out of memory");
             return NULL;
         }
-        memcpy(requestData.token, pdu->hdr->coap_hdr_udp_t.token, requestData.tokenLength);
+        memcpy(requestData.token, pdu->transport_hdr->udp.token, requestData.tokenLength);
 
         requestInfo = (CARequestInfo_t*) OICCalloc(1, sizeof(CARequestInfo_t));
         if (!requestInfo)
@@ -2059,7 +2061,7 @@ CAData_t* CACreateNewDataSet(const coap_pdu_t *pdu, const CAEndpoint_t *endpoint
 
         CAGetResponseInfoFromPDU(pdu, resInfo, endpoint);
         requestInfo->method = CA_GET;
-        requestInfo->info.messageId = CAGetMessageIdFromPduBinaryData(pdu->hdr, pdu->length);
+        requestInfo->info.messageId = CAGetMessageIdFromPduBinaryData(pdu->transport_hdr, pdu->length);
         requestInfo->info.resourceUri = OICStrdup(resInfo->info.resourceUri);
 
         // after copying the resource uri, destroy response info.
@@ -2228,7 +2230,7 @@ CAResult_t CAUpdateBlockOptionType(const CABlockDataID_t *blockID, uint8_t block
     OIC_LOG(DEBUG, TAG, "IN-UpdateBlockOptionType");
     VERIFY_NON_NULL(blockID, TAG, "blockID");
 
-    ca_mutex_lock(g_context.blockDataListMutex);
+    oc_mutex_lock(g_context.blockDataListMutex);
 
     size_t len = u_arraylist_length(g_context.dataList);
     for (size_t i = 0; i < len; i++)
@@ -2237,12 +2239,12 @@ CAResult_t CAUpdateBlockOptionType(const CABlockDataID_t *blockID, uint8_t block
         if (CABlockidMatches(currData, blockID))
         {
             currData->type = blockType;
-            ca_mutex_unlock(g_context.blockDataListMutex);
+            oc_mutex_unlock(g_context.blockDataListMutex);
             OIC_LOG(DEBUG, TAG, "OUT-UpdateBlockOptionType");
             return CA_STATUS_OK;
         }
     }
-    ca_mutex_unlock(g_context.blockDataListMutex);
+    oc_mutex_unlock(g_context.blockDataListMutex);
 
     OIC_LOG(DEBUG, TAG, "OUT-UpdateBlockOptionType");
     return CA_STATUS_FAILED;
@@ -2253,7 +2255,7 @@ uint8_t CAGetBlockOptionType(const CABlockDataID_t *blockID)
     OIC_LOG(DEBUG, TAG, "IN-GetBlockOptionType");
     VERIFY_NON_NULL_RET(blockID, TAG, "blockID", 0);
 
-    ca_mutex_lock(g_context.blockDataListMutex);
+    oc_mutex_lock(g_context.blockDataListMutex);
 
     size_t len = u_arraylist_length(g_context.dataList);
     for (size_t i = 0; i < len; i++)
@@ -2261,12 +2263,12 @@ uint8_t CAGetBlockOptionType(const CABlockDataID_t *blockID)
         CABlockData_t *currData = (CABlockData_t *) u_arraylist_get(g_context.dataList, i);
         if (CABlockidMatches(currData, blockID))
         {
-            ca_mutex_unlock(g_context.blockDataListMutex);
+            oc_mutex_unlock(g_context.blockDataListMutex);
             OIC_LOG(DEBUG, TAG, "OUT-GetBlockOptionType");
             return currData->type;
         }
     }
-    ca_mutex_unlock(g_context.blockDataListMutex);
+    oc_mutex_unlock(g_context.blockDataListMutex);
 
     OIC_LOG(DEBUG, TAG, "OUT-GetBlockOptionType");
     return 0;
@@ -2276,7 +2278,7 @@ CAData_t *CAGetDataSetFromBlockDataList(const CABlockDataID_t *blockID)
 {
     VERIFY_NON_NULL_RET(blockID, TAG, "blockID", NULL);
 
-    ca_mutex_lock(g_context.blockDataListMutex);
+    oc_mutex_lock(g_context.blockDataListMutex);
 
     size_t len = u_arraylist_length(g_context.dataList);
     for (size_t i = 0; i < len; i++)
@@ -2284,11 +2286,11 @@ CAData_t *CAGetDataSetFromBlockDataList(const CABlockDataID_t *blockID)
         CABlockData_t *currData = (CABlockData_t *) u_arraylist_get(g_context.dataList, i);
         if (CABlockidMatches(currData, blockID))
         {
-            ca_mutex_unlock(g_context.blockDataListMutex);
+            oc_mutex_unlock(g_context.blockDataListMutex);
             return currData->sentData;
         }
     }
-    ca_mutex_unlock(g_context.blockDataListMutex);
+    oc_mutex_unlock(g_context.blockDataListMutex);
 
     return NULL;
 }
@@ -2301,7 +2303,7 @@ CAResult_t CAGetTokenFromBlockDataList(const coap_pdu_t *pdu, const CAEndpoint_t
     VERIFY_NON_NULL(endpoint, TAG, "endpoint");
     VERIFY_NON_NULL(responseInfo, TAG, "responseInfo");
 
-    ca_mutex_lock(g_context.blockDataListMutex);
+    oc_mutex_lock(g_context.blockDataListMutex);
 
     size_t len = u_arraylist_length(g_context.dataList);
     for (size_t i = 0; i < len; i++)
@@ -2314,7 +2316,7 @@ CAResult_t CAGetTokenFromBlockDataList(const coap_pdu_t *pdu, const CAEndpoint_t
 
         if (NULL != currData->sentData && NULL != currData->sentData->requestInfo)
         {
-            if (pdu->hdr->coap_hdr_udp_t.id == currData->sentData->requestInfo->info.messageId &&
+            if (pdu->transport_hdr->udp.id == currData->sentData->requestInfo->info.messageId &&
                     endpoint->adapter == currData->sentData->remoteEndpoint->adapter)
             {
                 if (NULL != currData->sentData->requestInfo->info.token)
@@ -2325,13 +2327,13 @@ CAResult_t CAGetTokenFromBlockDataList(const coap_pdu_t *pdu, const CAEndpoint_t
                     if (NULL == responseInfo->info.token)
                     {
                         OIC_LOG(ERROR, TAG, "out of memory");
-                        ca_mutex_unlock(g_context.blockDataListMutex);
+                        oc_mutex_unlock(g_context.blockDataListMutex);
                         return CA_MEMORY_ALLOC_FAILED;
                     }
                     memcpy(responseInfo->info.token, currData->sentData->requestInfo->info.token,
                            responseInfo->info.tokenLength);
 
-                    ca_mutex_unlock(g_context.blockDataListMutex);
+                    oc_mutex_unlock(g_context.blockDataListMutex);
                     OIC_LOG(DEBUG, TAG, "OUT-CAGetTokenFromBlockDataList");
                     return CA_STATUS_OK;
                 }
@@ -2339,7 +2341,7 @@ CAResult_t CAGetTokenFromBlockDataList(const coap_pdu_t *pdu, const CAEndpoint_t
         }
     }
 
-    ca_mutex_unlock(g_context.blockDataListMutex);
+    oc_mutex_unlock(g_context.blockDataListMutex);
 
     OIC_LOG(DEBUG, TAG, "OUT-CAGetTokenFromBlockDataList");
     return CA_STATUS_FAILED;
@@ -2387,7 +2389,7 @@ CABlockData_t *CAGetBlockDataFromBlockDataList(const CABlockDataID_t *blockID)
 {
     VERIFY_NON_NULL_RET(blockID, TAG, "blockID", NULL);
 
-    ca_mutex_lock(g_context.blockDataListMutex);
+    oc_mutex_lock(g_context.blockDataListMutex);
 
     size_t len = u_arraylist_length(g_context.dataList);
     for (size_t i = 0; i < len; i++)
@@ -2395,11 +2397,11 @@ CABlockData_t *CAGetBlockDataFromBlockDataList(const CABlockDataID_t *blockID)
         CABlockData_t *currData = (CABlockData_t *) u_arraylist_get(g_context.dataList, i);
         if (CABlockidMatches(currData, blockID))
         {
-            ca_mutex_unlock(g_context.blockDataListMutex);
+            oc_mutex_unlock(g_context.blockDataListMutex);
             return currData;
         }
     }
-    ca_mutex_unlock(g_context.blockDataListMutex);
+    oc_mutex_unlock(g_context.blockDataListMutex);
 
     return NULL;
 }
@@ -2409,7 +2411,7 @@ coap_block_t *CAGetBlockOption(const CABlockDataID_t *blockID, uint16_t blockTyp
     OIC_LOG(DEBUG, TAG, "IN-GetBlockOption");
     VERIFY_NON_NULL_RET(blockID, TAG, "blockID", NULL);
 
-    ca_mutex_lock(g_context.blockDataListMutex);
+    oc_mutex_lock(g_context.blockDataListMutex);
 
     size_t len = u_arraylist_length(g_context.dataList);
     for (size_t i = 0; i < len; i++)
@@ -2417,7 +2419,7 @@ coap_block_t *CAGetBlockOption(const CABlockDataID_t *blockID, uint16_t blockTyp
         CABlockData_t *currData = (CABlockData_t *) u_arraylist_get(g_context.dataList, i);
         if (CABlockidMatches(currData, blockID))
         {
-            ca_mutex_unlock(g_context.blockDataListMutex);
+            oc_mutex_unlock(g_context.blockDataListMutex);
             OIC_LOG(DEBUG, TAG, "OUT-GetBlockOption");
             if (COAP_OPTION_BLOCK2 == blockType)
             {
@@ -2429,7 +2431,7 @@ coap_block_t *CAGetBlockOption(const CABlockDataID_t *blockID, uint16_t blockTyp
             }
         }
     }
-    ca_mutex_unlock(g_context.blockDataListMutex);
+    oc_mutex_unlock(g_context.blockDataListMutex);
 
     OIC_LOG(DEBUG, TAG, "OUT-GetBlockOption");
     return NULL;
@@ -2442,7 +2444,7 @@ CAPayload_t CAGetPayloadFromBlockDataList(const CABlockDataID_t *blockID,
     VERIFY_NON_NULL_RET(blockID, TAG, "blockID", NULL);
     VERIFY_NON_NULL_RET(fullPayloadLen, TAG, "fullPayloadLen", NULL);
 
-    ca_mutex_lock(g_context.blockDataListMutex);
+    oc_mutex_lock(g_context.blockDataListMutex);
 
     size_t len = u_arraylist_length(g_context.dataList);
     for (size_t i = 0; i < len; i++)
@@ -2450,13 +2452,13 @@ CAPayload_t CAGetPayloadFromBlockDataList(const CABlockDataID_t *blockID,
         CABlockData_t *currData = (CABlockData_t *) u_arraylist_get(g_context.dataList, i);
         if (CABlockidMatches(currData, blockID))
         {
-            ca_mutex_unlock(g_context.blockDataListMutex);
+            oc_mutex_unlock(g_context.blockDataListMutex);
             *fullPayloadLen = currData->receivedPayloadLen;
             OIC_LOG(DEBUG, TAG, "OUT-GetFullPayload");
             return currData->payload;
         }
     }
-    ca_mutex_unlock(g_context.blockDataListMutex);
+    oc_mutex_unlock(g_context.blockDataListMutex);
 
     OIC_LOG(DEBUG, TAG, "OUT-GetFullPayload");
     return NULL;
@@ -2519,7 +2521,7 @@ CABlockData_t *CACreateNewBlockData(const CAData_t *sendData)
     }
     data->blockDataId = blockDataID;
 
-    ca_mutex_lock(g_context.blockDataListMutex);
+    oc_mutex_lock(g_context.blockDataListMutex);
 
     bool res = u_arraylist_add(g_context.dataList, (void *) data);
     if (!res)
@@ -2528,10 +2530,10 @@ CABlockData_t *CACreateNewBlockData(const CAData_t *sendData)
         CADestroyBlockID(data->blockDataId);
         CADestroyDataSet(data->sentData);
         OICFree(data);
-        ca_mutex_unlock(g_context.blockDataListMutex);
+        oc_mutex_unlock(g_context.blockDataListMutex);
         return NULL;
     }
-    ca_mutex_unlock(g_context.blockDataListMutex);
+    oc_mutex_unlock(g_context.blockDataListMutex);
 
     OIC_LOG(DEBUG, TAG, "OUT-CreateBlockData");
     return data;
@@ -2542,7 +2544,7 @@ CAResult_t CARemoveBlockDataFromList(const CABlockDataID_t *blockID)
     OIC_LOG(DEBUG, TAG, "CARemoveBlockData");
     VERIFY_NON_NULL(blockID, TAG, "blockID");
 
-    ca_mutex_lock(g_context.blockDataListMutex);
+    oc_mutex_lock(g_context.blockDataListMutex);
 
     size_t len = u_arraylist_length(g_context.dataList);
     for (size_t i = 0; i < len; i++)
@@ -2554,7 +2556,7 @@ CAResult_t CARemoveBlockDataFromList(const CABlockDataID_t *blockID)
             if (!removedData)
             {
                 OIC_LOG(ERROR, TAG, "data is NULL");
-                ca_mutex_unlock(g_context.blockDataListMutex);
+                oc_mutex_unlock(g_context.blockDataListMutex);
                 return CA_STATUS_FAILED;
             }
 
@@ -2563,11 +2565,11 @@ CAResult_t CARemoveBlockDataFromList(const CABlockDataID_t *blockID)
             CADestroyBlockID(currData->blockDataId);
             OICFree(currData->payload);
             OICFree(currData);
-            ca_mutex_unlock(g_context.blockDataListMutex);
+            oc_mutex_unlock(g_context.blockDataListMutex);
             return CA_STATUS_OK;
         }
     }
-    ca_mutex_unlock(g_context.blockDataListMutex);
+    oc_mutex_unlock(g_context.blockDataListMutex);
 
     return CA_STATUS_OK;
 }
@@ -2576,7 +2578,7 @@ CAResult_t CARemoveAllBlockDataFromList()
 {
     OIC_LOG(DEBUG, TAG, "CARemoveAllBlockDataFromList");
 
-    ca_mutex_lock(g_context.blockDataListMutex);
+    oc_mutex_lock(g_context.blockDataListMutex);
 
     size_t len = u_arraylist_length(g_context.dataList);
     for (size_t i = len; i > 0; i--)
@@ -2594,7 +2596,7 @@ CAResult_t CARemoveAllBlockDataFromList()
             OICFree(removedData);
         }
     }
-    ca_mutex_unlock(g_context.blockDataListMutex);
+    oc_mutex_unlock(g_context.blockDataListMutex);
 
     return CA_STATUS_OK;
 }
index 18f3509..a287608 100644 (file)
@@ -65,6 +65,7 @@ extern void CADTLSSetCrlCallback(CAGetDTLSCrlHandler crlCallback);
 #ifdef __WITH_TLS__
 extern void CAsetPkixInfoCallback(CAgetPkixInfoHandler infCallback);
 extern void CAsetTlsCredentialsCallback(CAGetDTLSPskCredentialsHandler credCallback);
+extern void CAsetCredentialTypesCallback(CAgetCredentialTypesHandler credCallback);
 #endif
 
 
@@ -222,6 +223,19 @@ CAResult_t CAregisterPkixInfoHandler(CAgetPkixInfoHandler getPkixInfoHandler)
     OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
     return CA_STATUS_OK;
 }
+
+CAResult_t CAregisterGetCredentialTypesHandler(CAgetCredentialTypesHandler getCredTypesHandler)
+{
+    OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
+
+    if (!g_isInitialized)
+    {
+        return CA_STATUS_NOT_INITIALIZED;
+    }
+    CAsetCredentialTypesCallback(getCredTypesHandler);
+    OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
+    return CA_STATUS_OK;
+}
 #endif
 
 #ifdef __WITH_X509__
index 8cc0858..8d86b1d 100644 (file)
@@ -28,7 +28,9 @@
 #include "caremotehandler.h"
 #include "caprotocolmessage.h"
 #include "logger.h"
-#include "config.h" /* for coap protocol */
+#ifndef WITH_UPSTREAM_LIBCOAP
+#include "coap/config.h"
+#endif
 #include "oic_malloc.h"
 #include "canetworkconfigurator.h"
 #include "caadapterutils.h"
@@ -130,13 +132,16 @@ static CAData_t* CAGenerateHandlerData(const CAEndpoint_t *endpoint,
         OIC_LOG(ERROR, TAG, "memory allocation failed");
         return NULL;
     }
-
+#ifdef SINGLE_THREAD
+    CAEndpoint_t* ep = endpoint;
+#else
     CAEndpoint_t* ep = CACloneEndpoint(endpoint);
     if (!ep)
     {
         OIC_LOG(ERROR, TAG, "endpoint clone failed");
         goto exit;
     }
+#endif
 
     OIC_LOG_V(DEBUG, TAG, "address : %s", ep->addr);
 
@@ -234,7 +239,9 @@ static CAData_t* CAGenerateHandlerData(const CAEndpoint_t *endpoint,
 
 exit:
     OICFree(cadata);
+#ifndef SINGLE_THREAD
     CAFreeEndpoint(ep);
+#endif
     return NULL;
 }
 
@@ -242,20 +249,25 @@ static void CATimeoutCallback(const CAEndpoint_t *endpoint, const void *pdu, uin
 {
     VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint");
     VERIFY_NON_NULL_VOID(pdu, TAG, "pdu");
-
+#ifdef SINGLE_THREAD
+    CAEndpoint_t* ep = endpoint;
+#else
     CAEndpoint_t* ep = CACloneEndpoint(endpoint);
     if (!ep)
     {
         OIC_LOG(ERROR, TAG, "clone failed");
         return;
     }
+#endif
 
     CAResponseInfo_t* resInfo = (CAResponseInfo_t*)OICCalloc(1, sizeof(CAResponseInfo_t));
 
     if (!resInfo)
     {
         OIC_LOG(ERROR, TAG, "calloc failed");
+#ifndef SINGLE_THREAD
         CAFreeEndpoint(ep);
+#endif
         return;
     }
 
@@ -263,13 +275,15 @@ static void CATimeoutCallback(const CAEndpoint_t *endpoint, const void *pdu, uin
     resInfo->info.type = CAGetMessageTypeFromPduBinaryData(pdu, size);
     resInfo->info.messageId = CAGetMessageIdFromPduBinaryData(pdu, size);
 
-    CAResult_t res = CAGetTokenFromPDU((const coap_hdr_t *) pdu, &(resInfo->info),
+    CAResult_t res = CAGetTokenFromPDU((const coap_hdr_transport_t *) pdu, &(resInfo->info),
                                        endpoint);
     if (CA_STATUS_OK != res)
     {
         OIC_LOG(ERROR, TAG, "fail to get Token from retransmission list");
         CADestroyResponseInfoInternal(resInfo);
+#ifndef SINGLE_THREAD
         CAFreeEndpoint(ep);
+#endif
         return;
     }
 
@@ -277,7 +291,9 @@ static void CATimeoutCallback(const CAEndpoint_t *endpoint, const void *pdu, uin
     if (NULL == cadata)
     {
         OIC_LOG(ERROR, TAG, "memory allocation failed !");
+#ifndef SINGLE_THREAD
         CAFreeEndpoint(ep);
+#endif
         CADestroyResponseInfoInternal(resInfo);
         return;
     }
@@ -320,11 +336,12 @@ static void CADestroyData(void *data, uint32_t size)
         OIC_LOG(ERROR, TAG, "cadata is NULL");
         return;
     }
-
+#ifndef SINGLE_THREAD
     if (NULL != cadata->remoteEndpoint)
     {
         CAFreeEndpoint(cadata->remoteEndpoint);
     }
+#endif
 
     if (NULL != cadata->requestInfo)
     {
@@ -404,7 +421,7 @@ static CAResult_t CAProcessMulticastData(const CAData_t *data)
     coap_pdu_t *pdu = NULL;
     CAInfo_t *info = NULL;
     coap_list_t *options = NULL;
-    coap_transport_type transport = coap_udp;
+    coap_transport_t transport = COAP_UDP;
     CAResult_t res = CA_SEND_FAILED;
 
     if (!data->requestInfo && !data->responseInfo)
@@ -453,9 +470,9 @@ static CAResult_t CAProcessMulticastData(const CAData_t *data)
     CALogPDUInfo(pdu, data->remoteEndpoint);
 
     OIC_LOG(DEBUG, TAG, "pdu to send :");
-    OIC_LOG_BUFFER(DEBUG, TAG,  (uint8_t*)pdu->hdr, pdu->length);
+    OIC_LOG_BUFFER(DEBUG, TAG,  (uint8_t*)pdu->transport_hdr, pdu->length);
 
-    res = CASendMulticastData(data->remoteEndpoint, pdu->hdr, pdu->length, data->dataType);
+    res = CASendMulticastData(data->remoteEndpoint, pdu->transport_hdr, pdu->length, data->dataType);
     if (CA_STATUS_OK != res)
     {
         OIC_LOG_V(ERROR, TAG, "send failed:%d", res);
@@ -467,7 +484,7 @@ static CAResult_t CAProcessMulticastData(const CAData_t *data)
     return res;
 
 exit:
-    CAErrorHandler(data->remoteEndpoint, pdu->hdr, pdu->length, res);
+    CAErrorHandler(data->remoteEndpoint, pdu->transport_hdr, pdu->length, res);
     coap_delete_list(options);
     coap_delete_pdu(pdu);
     return res;
@@ -485,7 +502,7 @@ static CAResult_t CAProcessSendData(const CAData_t *data)
     coap_pdu_t *pdu = NULL;
     CAInfo_t *info = NULL;
     coap_list_t *options = NULL;
-    coap_transport_type transport = coap_udp;
+    coap_transport_t transport = COAP_UDP;
 
     if (SEND_TYPE_UNICAST == type)
     {
@@ -542,7 +559,7 @@ static CAResult_t CAProcessSendData(const CAData_t *data)
                     if (CA_STATUS_OK != res)
                     {
                         OIC_LOG(INFO, TAG, "to write block option has failed");
-                        CAErrorHandler(data->remoteEndpoint, pdu->hdr, pdu->length, res);
+                        CAErrorHandler(data->remoteEndpoint, pdu->transport_hdr, pdu->length, res);
                         coap_delete_list(options);
                         coap_delete_pdu(pdu);
                         return res;
@@ -553,11 +570,11 @@ static CAResult_t CAProcessSendData(const CAData_t *data)
             CALogPDUInfo(pdu, data->remoteEndpoint);
 
             OIC_LOG_V(INFO, TAG, "CASendUnicastData type : %d", data->dataType);
-            res = CASendUnicastData(data->remoteEndpoint, pdu->hdr, pdu->length, data->dataType);
+            res = CASendUnicastData(data->remoteEndpoint, pdu->transport_hdr, pdu->length, data->dataType);
             if (CA_STATUS_OK != res)
             {
                 OIC_LOG_V(ERROR, TAG, "send failed:%d", res);
-                CAErrorHandler(data->remoteEndpoint, pdu->hdr, pdu->length, res);
+                CAErrorHandler(data->remoteEndpoint, pdu->transport_hdr, pdu->length, res);
                 coap_delete_list(options);
                 coap_delete_pdu(pdu);
                 return res;
@@ -578,7 +595,7 @@ static CAResult_t CAProcessSendData(const CAData_t *data)
                 res = CARetransmissionSentData(&g_retransmissionContext,
                                                data->remoteEndpoint,
                                                data->dataType,
-                                               pdu->hdr, pdu->length);
+                                               pdu->transport_hdr, pdu->length);
                 if ((CA_STATUS_OK != res) && (CA_NOT_SUPPORTED != res))
                 {
                     //when retransmission not supported this will return CA_NOT_SUPPORTED, ignore
@@ -760,7 +777,7 @@ static void CAReceivedPacketCallback(const CASecureEndpoint_t *sep,
         {
             // for retransmission
             void *retransmissionPdu = NULL;
-            CARetransmissionReceivedData(&g_retransmissionContext, cadata->remoteEndpoint, pdu->hdr,
+            CARetransmissionReceivedData(&g_retransmissionContext, cadata->remoteEndpoint, pdu->transport_hdr,
                                          pdu->length, &retransmissionPdu);
 
             // get token from saved data in retransmission list
@@ -769,7 +786,7 @@ static void CAReceivedPacketCallback(const CASecureEndpoint_t *sep,
                 if (cadata->responseInfo)
                 {
                     CAInfo_t *info = &cadata->responseInfo->info;
-                    CAResult_t res = CAGetTokenFromPDU((const coap_hdr_t *)retransmissionPdu,
+                    CAResult_t res = CAGetTokenFromPDU((const coap_hdr_transport_t *)retransmissionPdu,
                                                        info, &(sep->endpoint));
                     if (CA_STATUS_OK != res)
                     {
@@ -823,11 +840,11 @@ void CAHandleRequestResponseCallbacks()
     // #1 parse the data
     // #2 get endpoint
 
-    ca_mutex_lock(g_receiveThread.threadMutex);
+    oc_mutex_lock(g_receiveThread.threadMutex);
 
     u_queue_message_t *item = u_queue_get_element(g_receiveThread.dataQueue);
 
-    ca_mutex_unlock(g_receiveThread.threadMutex);
+    oc_mutex_unlock(g_receiveThread.threadMutex);
 
     if (NULL == item || NULL == item->msg)
     {
@@ -874,29 +891,33 @@ static CAData_t* CAPrepareSendData(const CAEndpoint_t *endpoint, const void *sen
 
     if (CA_REQUEST_DATA == dataType)
     {
+#ifdef SINGLE_THREAD
+        CARequestInfo_t *request = (CARequestInfo_t *)sendData;
+#else
         // clone request info
         CARequestInfo_t *request = CACloneRequestInfo((CARequestInfo_t *)sendData);
-
         if (!request)
         {
             OIC_LOG(ERROR, TAG, "CACloneRequestInfo failed");
             goto exit;
         }
-
+#endif
         cadata->type = request->isMulticast ? SEND_TYPE_MULTICAST : SEND_TYPE_UNICAST;
         cadata->requestInfo =  request;
     }
     else if (CA_RESPONSE_DATA == dataType || CA_RESPONSE_FOR_RES == dataType)
     {
+#ifdef SINGLE_THREAD
+        CAResponseInfo_t *response = (CAResponseInfo_t *)sendData;
+#else
         // clone response info
         CAResponseInfo_t *response = CACloneResponseInfo((CAResponseInfo_t *)sendData);
-
         if(!response)
         {
             OIC_LOG(ERROR, TAG, "CACloneResponseInfo failed");
             goto exit;
         }
-
+#endif
         cadata->type = response->isMulticast ? SEND_TYPE_MULTICAST : SEND_TYPE_UNICAST;
         cadata->responseInfo = response;
     }
@@ -906,19 +927,26 @@ static CAData_t* CAPrepareSendData(const CAEndpoint_t *endpoint, const void *sen
         goto exit;
     }
 
+#ifdef SINGLE_THREAD
+    CAEndpoint_t* ep = endpoint;
+#else
     CAEndpoint_t* ep = CACloneEndpoint(endpoint);
     if (!ep)
     {
         OIC_LOG(ERROR, TAG, "endpoint clone failed");
         goto exit;
     }
-
+#endif
     cadata->remoteEndpoint = ep;
     cadata->dataType = dataType;
     return cadata;
 
 exit:
+#ifndef SINGLE_THREAD
     CADestroyData(cadata, sizeof(CAData_t));
+#else
+    OICFree(cadata);
+#endif
     return NULL;
 }
 
@@ -954,11 +982,12 @@ CAResult_t CADetachSendMessage(const CAEndpoint_t *endpoint, const void *sendMsg
     if (CA_STATUS_OK != result)
     {
         OIC_LOG(ERROR, TAG, "CAProcessSendData failed");
-        CADestroyData(data, sizeof(CAData_t));
+        OICFree(data);
         return result;
     }
 
-    CADestroyData(data, sizeof(CAData_t));
+    OICFree(data);
+
 #else
 #ifdef WITH_BWT
     if (CAIsSupportedBlockwiseTransfer(endpoint->adapter))
@@ -1201,19 +1230,19 @@ void CALogPDUInfo(coap_pdu_t *pdu, const CAEndpoint_t *endpoint)
     if (CAIsSupportedCoAPOverTCP(endpoint->adapter))
     {
         OIC_LOG(DEBUG, TAG, "pdu header data :");
-        OIC_LOG_BUFFER(DEBUG, TAG,  (const uint8_t *) pdu->hdr, pdu->length);
+        OIC_LOG_BUFFER(DEBUG, TAG,  (const uint8_t *) pdu->transport_hdr, pdu->length);
     }
     else
 #endif
     {
-        OIC_LOG_V(DEBUG, TAG, "PDU Maker - type : %d", pdu->hdr->coap_hdr_udp_t.type);
+        OIC_LOG_V(DEBUG, TAG, "PDU Maker - type : %d", pdu->transport_hdr->udp.type);
 
-        OIC_LOG_V(DEBUG, TAG, "PDU Maker - code : %d", pdu->hdr->coap_hdr_udp_t.code);
+        OIC_LOG_V(DEBUG, TAG, "PDU Maker - code : %d", pdu->transport_hdr->udp.code);
 
         OIC_LOG(DEBUG, TAG, "PDU Maker - token :");
 
-        OIC_LOG_BUFFER(DEBUG, TAG, pdu->hdr->coap_hdr_udp_t.token,
-                       pdu->hdr->coap_hdr_udp_t.token_length);
+        OIC_LOG_BUFFER(DEBUG, TAG, pdu->transport_hdr->udp.token,
+                       pdu->transport_hdr->udp.token_length);
     }
 }
 
index 03eca3b..96cfbb7 100644 (file)
@@ -28,6 +28,7 @@
 // Refer http://www.gnu.org/software/libc/manual/html_node/BSD-Random.html
 #define _DEFAULT_SOURCE
 
+#include "iotivity_config.h"
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 
 static const char COAP_URI_HEADER[] = "coap://[::]/";
 
+#ifdef WITH_CHPROXY
+static char g_chproxyUri[CA_MAX_URI_LENGTH];
+
+CAResult_t CASetProxyUri(const char *uri)
+{
+    VERIFY_NON_NULL(uri, TAG, "uri");
+    OICStrcpy(g_chproxyUri, sizeof (g_chproxyUri), uri);
+    return CA_STATUS_OK;
+}
+#endif
+
 CAResult_t CAGetRequestInfoFromPDU(const coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
                                    CARequestInfo_t *outReqInfo)
 {
@@ -88,7 +100,7 @@ CAResult_t CAGetErrorInfoFromPDU(const coap_pdu_t *pdu, const CAEndpoint_t *endp
 }
 
 coap_pdu_t *CAGeneratePDU(uint32_t code, const CAInfo_t *info, const CAEndpoint_t *endpoint,
-                          coap_list_t **optlist, coap_transport_type *transport)
+                          coap_list_t **optlist, coap_transport_t *transport)
 {
     VERIFY_NON_NULL_RET(info, TAG, "info", NULL);
     VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint", NULL);
@@ -175,19 +187,15 @@ coap_pdu_t *CAParsePDU(const char *data, uint32_t length, uint32_t *outCode,
     VERIFY_NON_NULL_RET(data, TAG, "data", NULL);
     VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint", NULL);
 
-    coap_transport_type transport;
+    coap_transport_t transport = COAP_UDP;
 #ifdef WITH_TCP
     if (CAIsSupportedCoAPOverTCP(endpoint->adapter))
     {
         transport = coap_get_tcp_header_type_from_initbyte(((unsigned char *)data)[0] >> 4);
     }
-    else
 #endif
-    {
-        transport = coap_udp;
-    }
 
-    coap_pdu_t *outpdu = coap_new_pdu(transport, length);
+    coap_pdu_t *outpdu = coap_new_pdu2(transport, length);
     if (NULL == outpdu)
     {
         OIC_LOG(ERROR, TAG, "outpdu is null");
@@ -196,7 +204,7 @@ coap_pdu_t *CAParsePDU(const char *data, uint32_t length, uint32_t *outCode,
 
     OIC_LOG_V(DEBUG, TAG, "pdu parse-transport type : %d", transport);
 
-    int ret = coap_pdu_parse((unsigned char *) data, length, outpdu, transport);
+    int ret = coap_pdu_parse2((unsigned char *) data, length, outpdu, transport);
     OIC_LOG_V(DEBUG, TAG, "pdu parse ret: %d", ret);
     if (0 >= ret)
     {
@@ -212,16 +220,16 @@ coap_pdu_t *CAParsePDU(const char *data, uint32_t length, uint32_t *outCode,
     else
 #endif
     {
-        if (outpdu->hdr->coap_hdr_udp_t.version != COAP_DEFAULT_VERSION)
+        if (outpdu->transport_hdr->udp.version != COAP_DEFAULT_VERSION)
         {
             OIC_LOG_V(ERROR, TAG, "coap version is not available : %d",
-                      outpdu->hdr->coap_hdr_udp_t.version);
+                      outpdu->transport_hdr->udp.version);
             goto exit;
         }
-        if (outpdu->hdr->coap_hdr_udp_t.token_length > CA_MAX_TOKEN_LEN)
+        if (outpdu->transport_hdr->udp.token_length > CA_MAX_TOKEN_LEN)
         {
             OIC_LOG_V(ERROR, TAG, "token length has been exceed : %d",
-                      outpdu->hdr->coap_hdr_udp_t.token_length);
+                      outpdu->transport_hdr->udp.token_length);
             goto exit;
         }
     }
@@ -240,7 +248,7 @@ exit:
 
 coap_pdu_t *CAGeneratePDUImpl(code_t code, const CAInfo_t *info,
                               const CAEndpoint_t *endpoint, coap_list_t *options,
-                              coap_transport_type *transport)
+                              coap_transport_t *transport)
 {
     VERIFY_NON_NULL_RET(info, TAG, "info", NULL);
     VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint", NULL);
@@ -289,10 +297,10 @@ coap_pdu_t *CAGeneratePDUImpl(code_t code, const CAInfo_t *info,
     else
 #endif
     {
-        *transport = coap_udp;
+        *transport = COAP_UDP;
     }
 
-    coap_pdu_t *pdu = coap_new_pdu(*transport, length);
+    coap_pdu_t *pdu = coap_new_pdu2(*transport, length);
 
     if (NULL == pdu)
     {
@@ -325,10 +333,10 @@ coap_pdu_t *CAGeneratePDUImpl(code_t code, const CAInfo_t *info,
             /* use saved message id */
             message_id = info->messageId;
         }
-        pdu->hdr->coap_hdr_udp_t.id = message_id;
-        OIC_LOG_V(DEBUG, TAG, "messageId in pdu is %d, %d", message_id, pdu->hdr->coap_hdr_udp_t.id);
+        pdu->transport_hdr->udp.id = message_id;
+        OIC_LOG_V(DEBUG, TAG, "messageId in pdu is %d, %d", message_id, pdu->transport_hdr->udp.id);
 
-        pdu->hdr->coap_hdr_udp_t.type = info->type;
+        pdu->transport_hdr->udp.type = info->type;
     }
 
     coap_add_code(pdu, *transport, code);
@@ -339,7 +347,7 @@ coap_pdu_t *CAGeneratePDUImpl(code_t code, const CAInfo_t *info,
         OIC_LOG_V(DEBUG, TAG, "token info token length: %d, token :", tokenLength);
         OIC_LOG_BUFFER(DEBUG, TAG, (const uint8_t *)info->token, tokenLength);
 
-        int32_t ret = coap_add_token(pdu, tokenLength, (unsigned char *)info->token, *transport);
+        int32_t ret = coap_add_token2(pdu, tokenLength, (unsigned char *)info->token, *transport);
         if (0 == ret)
         {
             OIC_LOG(ERROR, TAG, "can't add token");
@@ -366,9 +374,9 @@ coap_pdu_t *CAGeneratePDUImpl(code_t code, const CAInfo_t *info,
                       COAP_OPTION_DATA(*(coap_option *) opt->data));
 
             OIC_LOG_V(DEBUG, TAG, "[%d] pdu length", pdu->length);
-            coap_add_option(pdu, COAP_OPTION_KEY(*(coap_option *) opt->data),
-                            COAP_OPTION_LENGTH(*(coap_option *) opt->data),
-                            COAP_OPTION_DATA(*(coap_option *) opt->data), *transport);
+            coap_add_option2(pdu, COAP_OPTION_KEY(*(coap_option *) opt->data),
+                             COAP_OPTION_LENGTH(*(coap_option *) opt->data),
+                             COAP_OPTION_DATA(*(coap_option *) opt->data), *transport);
         }
     }
 
@@ -672,7 +680,7 @@ uint32_t CAGetOptionCount(coap_opt_iterator_t opt_iter)
             && COAP_OPTION_ACCEPT != opt_iter.type
             && COAP_OPTION_URI_HOST != opt_iter.type && COAP_OPTION_URI_PORT != opt_iter.type
             && COAP_OPTION_ETAG != opt_iter.type && COAP_OPTION_MAXAGE != opt_iter.type
-            && COAP_OPTION_PROXY_URI != opt_iter.type && COAP_OPTION_PROXY_SCHEME != opt_iter.type)
+            && COAP_OPTION_PROXY_SCHEME != opt_iter.type)
         {
             count++;
         }
@@ -689,20 +697,20 @@ CAResult_t CAGetInfoFromPDU(const coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
     VERIFY_NON_NULL(outCode, TAG, "outCode");
     VERIFY_NON_NULL(outInfo, TAG, "outInfo");
 
-    coap_transport_type transport;
+    coap_transport_t transport;
 #ifdef WITH_TCP
     if (CAIsSupportedCoAPOverTCP(endpoint->adapter))
     {
-        transport = coap_get_tcp_header_type_from_initbyte(((unsigned char *)pdu->hdr)[0] >> 4);
+        transport = coap_get_tcp_header_type_from_initbyte(((unsigned char *)pdu->transport_hdr)[0] >> 4);
     }
     else
 #endif
     {
-        transport = coap_udp;
+        transport = COAP_UDP;
     }
 
     coap_opt_iterator_t opt_iter;
-    coap_option_iterator_init((coap_pdu_t *) pdu, &opt_iter, COAP_OPT_ALL, transport);
+    coap_option_iterator_init2((coap_pdu_t *) pdu, &opt_iter, COAP_OPT_ALL, transport);
 
     if (outCode)
     {
@@ -728,10 +736,10 @@ CAResult_t CAGetInfoFromPDU(const coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
 #endif
     {
         // set type
-        outInfo->type = pdu->hdr->coap_hdr_udp_t.type;
+        outInfo->type = pdu->transport_hdr->udp.type;
 
         // set message id
-        outInfo->messageId = pdu->hdr->coap_hdr_udp_t.id;
+        outInfo->messageId = pdu->transport_hdr->udp.id;
         outInfo->payloadFormat = CA_FORMAT_UNDEFINED;
         outInfo->acceptFormat = CA_FORMAT_UNDEFINED;
     }
@@ -752,6 +760,9 @@ CAResult_t CAGetInfoFromPDU(const coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
     uint32_t optionLength = 0;
     bool isfirstsetflag = false;
     bool isQueryBeingProcessed = false;
+#ifdef WITH_CHPROXY
+    bool isProxyRequest = false;
+#endif
 
     while ((option = coap_option_next(&opt_iter)))
     {
@@ -872,7 +883,6 @@ CAResult_t CAGetInfoFromPDU(const coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
                     COAP_OPTION_URI_HOST == opt_iter.type ||
                     COAP_OPTION_ETAG == opt_iter.type ||
                     COAP_OPTION_MAXAGE == opt_iter.type ||
-                    COAP_OPTION_PROXY_URI == opt_iter.type ||
                     COAP_OPTION_PROXY_SCHEME== opt_iter.type)
             {
                 OIC_LOG_V(INFO, TAG, "option[%d] has an unsupported format [%d]",
@@ -880,6 +890,12 @@ CAResult_t CAGetInfoFromPDU(const coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
             }
             else
             {
+#ifdef WITH_CHPROXY
+                if (COAP_OPTION_PROXY_URI == opt_iter.type)
+                {
+                    isProxyRequest = true;
+                }
+#endif
                 if (idx < count)
                 {
                     if (bufLength <= sizeof(outInfo->options[0].optionData))
@@ -897,7 +913,7 @@ CAResult_t CAGetInfoFromPDU(const coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
 
     unsigned char* token = NULL;
     unsigned int token_length = 0;
-    coap_get_token(pdu->hdr, transport, &token, &token_length);
+    coap_get_token2(pdu->transport_hdr, transport, &token, &token_length);
 
     // set token data
     if (token_length > 0)
@@ -945,7 +961,24 @@ CAResult_t CAGetInfoFromPDU(const coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
             return CA_MEMORY_ALLOC_FAILED;
         }
     }
-
+#ifdef WITH_CHPROXY
+    else if(isProxyRequest && g_chproxyUri[0] != '\0')
+    {
+       /*
+        *   A request for CoAP-HTTP Proxy will not have any uri element as per CoAP specs
+        *   and only COAP_OPTION_PROXY_URI will be present. Use preset proxy uri
+        *   for such requests.
+        */
+        outInfo->resourceUri = OICStrdup(g_chproxyUri);
+        if (!outInfo->resourceUri)
+        {
+            OIC_LOG(ERROR, TAG, "Out of memory");
+            OICFree(outInfo->options);
+            OICFree(outInfo->token);
+            return CA_MEMORY_ALLOC_FAILED;
+        }
+    }
+#endif
     return CA_STATUS_OK;
 
 exit:
@@ -954,14 +987,15 @@ exit:
     return CA_STATUS_FAILED;
 }
 
-CAResult_t CAGetTokenFromPDU(const coap_hdr_t *pdu_hdr, CAInfo_t *outInfo,
+CAResult_t CAGetTokenFromPDU(const coap_hdr_transport_t *pdu_hdr,
+                             CAInfo_t *outInfo,
                              const CAEndpoint_t *endpoint)
 {
     VERIFY_NON_NULL(pdu_hdr, TAG, "pdu_hdr");
     VERIFY_NON_NULL(outInfo, TAG, "outInfo");
     VERIFY_NON_NULL(endpoint, TAG, "endpoint");
 
-    coap_transport_type transport = coap_udp;
+    coap_transport_t transport = COAP_UDP;
 #ifdef WITH_TCP
     if (CAIsSupportedCoAPOverTCP(endpoint->adapter))
     {
@@ -971,7 +1005,7 @@ CAResult_t CAGetTokenFromPDU(const coap_hdr_t *pdu_hdr, CAInfo_t *outInfo,
 
     unsigned char* token = NULL;
     unsigned int token_length = 0;
-    coap_get_token(pdu_hdr, transport, &token, &token_length);
+    coap_get_token2(pdu_hdr, transport, &token, &token_length);
 
     // set token data
     if (token_length > 0)
@@ -1071,7 +1105,7 @@ CAMessageType_t CAGetMessageTypeFromPduBinaryData(const void *pdu, uint32_t size
 
     coap_hdr_t *hdr = (coap_hdr_t *) pdu;
 
-    return (CAMessageType_t) hdr->coap_hdr_udp_t.type;
+    return (CAMessageType_t) hdr->type;
 }
 
 uint16_t CAGetMessageIdFromPduBinaryData(const void *pdu, uint32_t size)
@@ -1087,7 +1121,7 @@ uint16_t CAGetMessageIdFromPduBinaryData(const void *pdu, uint32_t size)
 
     coap_hdr_t *hdr = (coap_hdr_t *) pdu;
 
-    return hdr->coap_hdr_udp_t.id;
+    return hdr->id;
 }
 
 CAResponseResult_t CAGetCodeFromPduBinaryData(const void *pdu, uint32_t size)
@@ -1103,7 +1137,7 @@ CAResponseResult_t CAGetCodeFromPduBinaryData(const void *pdu, uint32_t size)
 
     coap_hdr_t *hdr = (coap_hdr_t *) pdu;
 
-    return (CAResponseResult_t) CA_RESPONSE_CODE(hdr->coap_hdr_udp_t.code);
+    return (CAResponseResult_t) CA_RESPONSE_CODE(hdr->code);
 }
 
 CAPayloadFormat_t CAConvertFormat(uint8_t format)
index 3e10065..1b4089d 100644 (file)
@@ -18,6 +18,7 @@
  *
  ******************************************************************/
 
+#include "iotivity_config.h"
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
@@ -49,7 +50,7 @@ static void CAQueueingThreadBaseRoutine(void *threadValue)
     while (!thread->isStop)
     {
         // mutex lock
-        ca_mutex_lock(thread->threadMutex);
+        oc_mutex_lock(thread->threadMutex);
 
         // if queue is empty, thread will wait
         if (!thread->isStop && u_queue_get_size(thread->dataQueue) <= 0)
@@ -57,7 +58,7 @@ static void CAQueueingThreadBaseRoutine(void *threadValue)
             OIC_LOG(DEBUG, TAG, "wait..");
 
             // wait
-            ca_cond_wait(thread->threadCond, thread->threadMutex);
+            oc_cond_wait(thread->threadCond, thread->threadMutex);
 
             OIC_LOG(DEBUG, TAG, "wake up..");
         }
@@ -66,14 +67,14 @@ static void CAQueueingThreadBaseRoutine(void *threadValue)
         if (thread->isStop)
         {
             // mutex unlock
-            ca_mutex_unlock(thread->threadMutex);
+            oc_mutex_unlock(thread->threadMutex);
             continue;
         }
 
         // get data
         u_queue_message_t *message = u_queue_get_element(thread->dataQueue);
         // mutex unlock
-        ca_mutex_unlock(thread->threadMutex);
+        oc_mutex_unlock(thread->threadMutex);
         if (NULL == message)
         {
             continue;
@@ -95,9 +96,9 @@ static void CAQueueingThreadBaseRoutine(void *threadValue)
         OICFree(message);
     }
 
-    ca_mutex_lock(thread->threadMutex);
-    ca_cond_signal(thread->threadCond);
-    ca_mutex_unlock(thread->threadMutex);
+    oc_mutex_lock(thread->threadMutex);
+    oc_cond_signal(thread->threadCond);
+    oc_mutex_unlock(thread->threadMutex);
 
     OIC_LOG(DEBUG, TAG, "message handler main thread end..");
 }
@@ -122,8 +123,8 @@ CAResult_t CAQueueingThreadInitialize(CAQueueingThread_t *thread, ca_thread_pool
     // set send thread data
     thread->threadPool = handle;
     thread->dataQueue = u_queue_create();
-    thread->threadMutex = ca_mutex_new();
-    thread->threadCond = ca_cond_new();
+    thread->threadMutex = oc_mutex_new();
+    thread->threadCond = oc_cond_new();
     thread->isStop = true;
     thread->threadTask = task;
     thread->destroy = destroy;
@@ -142,12 +143,12 @@ ERROR_MEM_FAILURE:
     }
     if (thread->threadMutex)
     {
-        ca_mutex_free(thread->threadMutex);
+        oc_mutex_free(thread->threadMutex);
         thread->threadMutex = NULL;
     }
     if (thread->threadCond)
     {
-        ca_cond_free(thread->threadCond);
+        oc_cond_free(thread->threadCond);
         thread->threadCond = NULL;
     }
     return CA_MEMORY_ALLOC_FAILED;
@@ -174,10 +175,10 @@ CAResult_t CAQueueingThreadStart(CAQueueingThread_t *thread)
     }
 
     // mutex lock
-    ca_mutex_lock(thread->threadMutex);
+    oc_mutex_lock(thread->threadMutex);
     thread->isStop = false;
     // mutex unlock
-    ca_mutex_unlock(thread->threadMutex);
+    oc_mutex_unlock(thread->threadMutex);
 
     CAResult_t res = ca_thread_pool_add_task(thread->threadPool, CAQueueingThreadBaseRoutine,
                                             thread);
@@ -217,16 +218,16 @@ CAResult_t CAQueueingThreadAddData(CAQueueingThread_t *thread, void *data, uint3
     message->size = size;
 
     // mutex lock
-    ca_mutex_lock(thread->threadMutex);
+    oc_mutex_lock(thread->threadMutex);
 
     // add thread data into list
     u_queue_add_element(thread->dataQueue, message);
 
     // notity the thread
-    ca_cond_signal(thread->threadCond);
+    oc_cond_signal(thread->threadCond);
 
     // mutex unlock
-    ca_mutex_unlock(thread->threadMutex);
+    oc_mutex_unlock(thread->threadMutex);
 
     return CA_STATUS_OK;
 }
@@ -241,9 +242,9 @@ CAResult_t CAQueueingThreadDestroy(CAQueueingThread_t *thread)
 
     OIC_LOG(DEBUG, TAG, "thread destroy..");
 
-    ca_mutex_free(thread->threadMutex);
+    oc_mutex_free(thread->threadMutex);
     thread->threadMutex = NULL;
-    ca_cond_free(thread->threadCond);
+    oc_cond_free(thread->threadCond);
 
     // remove all remained list data.
     while (u_queue_get_size(thread->dataQueue) > 0)
@@ -285,18 +286,18 @@ CAResult_t CAQueueingThreadStop(CAQueueingThread_t *thread)
     if (!thread->isStop)
     {
         // mutex lock
-        ca_mutex_lock(thread->threadMutex);
+        oc_mutex_lock(thread->threadMutex);
 
         // set stop flag
         thread->isStop = true;
 
         // notify the thread
-        ca_cond_signal(thread->threadCond);
+        oc_cond_signal(thread->threadCond);
 
-        ca_cond_wait(thread->threadCond, thread->threadMutex);
+        oc_cond_wait(thread->threadCond, thread->threadMutex);
 
         // mutex unlock
-        ca_mutex_unlock(thread->threadMutex);
+        oc_mutex_unlock(thread->threadMutex);
     }
 
     return CA_STATUS_OK;
index a3cb02f..0d58a0d 100644 (file)
@@ -41,6 +41,7 @@
 #define _POSIX_C_SOURCE 200809L
 #endif
 
+#include "iotivity_config.h"
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
@@ -55,7 +56,7 @@
 #ifdef HAVE_SYS_TIME_H
 #include <sys/time.h>
 #endif
-#if HAVE_SYS_TIMEB_H
+#ifdef HAVE_SYS_TIMEB_H
 #include <sys/timeb.h>
 #endif
 #ifdef HAVE_TIME_H
@@ -177,7 +178,7 @@ static void CACheckRetransmissionList(CARetransmission_t *context)
     }
 
     // mutex lock
-    ca_mutex_lock(context->threadMutex);
+    oc_mutex_lock(context->threadMutex);
 
     uint32_t i = 0;
     uint32_t len = u_arraylist_length(context->dataList);
@@ -217,7 +218,7 @@ static void CACheckRetransmissionList(CARetransmission_t *context)
             {
                 OIC_LOG(ERROR, TAG, "Removed data is NULL");
                 // mutex unlock
-                ca_mutex_unlock(context->threadMutex);
+                oc_mutex_unlock(context->threadMutex);
                 return;
             }
             OIC_LOG_V(DEBUG, TAG, "max trying count, remove RTCON data,"
@@ -242,7 +243,7 @@ static void CACheckRetransmissionList(CARetransmission_t *context)
     }
 
     // mutex unlock
-    ca_mutex_unlock(context->threadMutex);
+    oc_mutex_unlock(context->threadMutex);
 }
 
 void CARetransmissionBaseRoutine(void *threadValue)
@@ -270,7 +271,7 @@ void CARetransmissionBaseRoutine(void *threadValue)
     while (!context->isStop)
     {
         // mutex lock
-        ca_mutex_lock(context->threadMutex);
+        oc_mutex_lock(context->threadMutex);
 
         if (!context->isStop && u_arraylist_length(context->dataList) <= 0)
         {
@@ -278,7 +279,7 @@ void CARetransmissionBaseRoutine(void *threadValue)
             OIC_LOG(DEBUG, TAG, "wait..there is no retransmission data.");
 
             // wait
-            ca_cond_wait(context->threadCond, context->threadMutex);
+            oc_cond_wait(context->threadCond, context->threadMutex);
 
             OIC_LOG(DEBUG, TAG, "wake up..");
         }
@@ -290,7 +291,7 @@ void CARetransmissionBaseRoutine(void *threadValue)
 
             // wait
             uint64_t absTime = RETRANSMISSION_CHECK_PERIOD_SEC * (uint64_t) USECS_PER_SEC;
-            ca_cond_wait_for(context->threadCond, context->threadMutex, absTime );
+            oc_cond_wait_for(context->threadCond, context->threadMutex, absTime );
         }
         else
         {
@@ -298,7 +299,7 @@ void CARetransmissionBaseRoutine(void *threadValue)
         }
 
         // mutex unlock
-        ca_mutex_unlock(context->threadMutex);
+        oc_mutex_unlock(context->threadMutex);
 
         // check stop flag
         if (context->isStop)
@@ -309,9 +310,9 @@ void CARetransmissionBaseRoutine(void *threadValue)
         CACheckRetransmissionList(context);
     }
 
-    ca_mutex_lock(context->threadMutex);
-    ca_cond_signal(context->threadCond);
-    ca_mutex_unlock(context->threadMutex);
+    oc_mutex_lock(context->threadMutex);
+    oc_cond_signal(context->threadCond);
+    oc_mutex_unlock(context->threadMutex);
 
 #endif
     OIC_LOG(DEBUG, TAG, "retransmission main thread end");
@@ -350,8 +351,8 @@ CAResult_t CARetransmissionInitialize(CARetransmission_t *context,
 
     // set send thread data
     context->threadPool = handle;
-    context->threadMutex = ca_mutex_new();
-    context->threadCond = ca_cond_new();
+    context->threadMutex = oc_mutex_new();
+    context->threadCond = oc_cond_new();
     context->dataSendMethod = retransmissionSendMethod;
     context->timeoutCallback = timeoutCallback;
     context->config = cfg;
@@ -434,7 +435,7 @@ CAResult_t CARetransmissionSentData(CARetransmission_t *context,
     retData->dataType = dataType;
 #ifndef SINGLE_THREAD
     // mutex lock
-    ca_mutex_lock(context->threadMutex);
+    oc_mutex_lock(context->threadMutex);
 
     uint32_t i = 0;
     uint32_t len = u_arraylist_length(context->dataList);
@@ -456,7 +457,7 @@ CAResult_t CARetransmissionSentData(CARetransmission_t *context,
             OIC_LOG(ERROR, TAG, "Duplicate message ID");
 
             // mutex unlock
-            ca_mutex_unlock(context->threadMutex);
+            oc_mutex_unlock(context->threadMutex);
 
             OICFree(retData);
             OICFree(pduData);
@@ -468,10 +469,10 @@ CAResult_t CARetransmissionSentData(CARetransmission_t *context,
     u_arraylist_add(context->dataList, (void *) retData);
 
     // notify the thread
-    ca_cond_signal(context->threadCond);
+    oc_cond_signal(context->threadCond);
 
     // mutex unlock
-    ca_mutex_unlock(context->threadMutex);
+    oc_mutex_unlock(context->threadMutex);
 
 #else
     u_arraylist_add(context->dataList, (void *) retData);
@@ -515,7 +516,7 @@ CAResult_t CARetransmissionReceivedData(CARetransmission_t *context,
     }
 
     // mutex lock
-    ca_mutex_lock(context->threadMutex);
+    oc_mutex_lock(context->threadMutex);
     uint32_t len = u_arraylist_length(context->dataList);
 
     // find index
@@ -545,7 +546,7 @@ CAResult_t CARetransmissionReceivedData(CARetransmission_t *context,
                     OIC_LOG(ERROR, TAG, "retData->pdu is null");
                     OICFree(retData);
                     // mutex unlock
-                    ca_mutex_unlock(context->threadMutex);
+                    oc_mutex_unlock(context->threadMutex);
 
                     return CA_STATUS_FAILED;
                 }
@@ -558,7 +559,7 @@ CAResult_t CARetransmissionReceivedData(CARetransmission_t *context,
                     OIC_LOG(ERROR, TAG, "memory error");
 
                     // mutex unlock
-                    ca_mutex_unlock(context->threadMutex);
+                    oc_mutex_unlock(context->threadMutex);
 
                     return CA_MEMORY_ALLOC_FAILED;
                 }
@@ -572,7 +573,7 @@ CAResult_t CARetransmissionReceivedData(CARetransmission_t *context,
                 OIC_LOG(ERROR, TAG, "Removed data is NULL");
 
                 // mutex unlock
-                ca_mutex_unlock(context->threadMutex);
+                oc_mutex_unlock(context->threadMutex);
 
                 return CA_STATUS_FAILED;
             }
@@ -588,7 +589,7 @@ CAResult_t CARetransmissionReceivedData(CARetransmission_t *context,
     }
 
     // mutex unlock
-    ca_mutex_unlock(context->threadMutex);
+    oc_mutex_unlock(context->threadMutex);
 
     OIC_LOG(DEBUG, TAG, "OUT");
     return CA_STATUS_OK;
@@ -605,18 +606,18 @@ CAResult_t CARetransmissionStop(CARetransmission_t *context)
     OIC_LOG(DEBUG, TAG, "retransmission stop request!!");
 
     // mutex lock
-    ca_mutex_lock(context->threadMutex);
+    oc_mutex_lock(context->threadMutex);
 
     // set stop flag
     context->isStop = true;
 
     // notify the thread
-    ca_cond_signal(context->threadCond);
+    oc_cond_signal(context->threadCond);
 
-    ca_cond_wait(context->threadCond, context->threadMutex);
+    oc_cond_wait(context->threadCond, context->threadMutex);
 
     // mutex unlock
-    ca_mutex_unlock(context->threadMutex);
+    oc_mutex_unlock(context->threadMutex);
 
     return CA_STATUS_OK;
 }
@@ -631,9 +632,9 @@ CAResult_t CARetransmissionDestroy(CARetransmission_t *context)
 
     OIC_LOG(DEBUG, TAG, "retransmission context destroy..");
 
-    ca_mutex_free(context->threadMutex);
+    oc_mutex_free(context->threadMutex);
     context->threadMutex = NULL;
-    ca_cond_free(context->threadCond);
+    oc_cond_free(context->threadCond);
     u_arraylist_free(&context->dataList);
 
     return CA_STATUS_OK;
index 24c8224..ec426d9 100644 (file)
@@ -255,6 +255,13 @@ u_arraylist_t *CAIPGetInterfaceInformation(int desiredIndex)
         {
             goto exit;
         }
+
+        // Add IPv6 interface
+        result = CAAddInterfaceItem(iflist, ifindex, name, AF_INET6, addr, flags);
+        if (CA_STATUS_OK != result)
+        {
+            goto exit;
+        }
     }
     return iflist;
 
index 04f16c8..8b39412 100644 (file)
@@ -30,7 +30,7 @@
 #ifdef __WITH_DTLS__
 #include "caadapternetdtls.h"
 #endif
-#include "camutex.h"
+#include "octhread.h"
 #include "uarraylist.h"
 #include "caremotehandler.h"
 #include "logger.h"
index 313d2f6..474e694 100644 (file)
@@ -25,6 +25,7 @@
 #define _GNU_SOURCE // for in6_pktinfo
 #endif
 
+#include "iotivity_config.h"
 #include <sys/types.h>
 #if !defined(_WIN32)
 #include <sys/socket.h>
 #include <linux/rtnetlink.h>
 #endif
 
-#include "pdu.h"
+#include <coap/pdu.h>
 #include "caipinterface.h"
 #include "caadapterutils.h"
 #ifdef __WITH_DTLS__
 #include "caadapternetdtls.h"
 #endif
-#include "camutex.h"
+#include "octhread.h"
 #include "oic_malloc.h"
 #include "oic_string.h"
-#include "platform_features.h"
 
 #define USE_IP_MREQN
 #if defined(_WIN32)
@@ -1008,7 +1008,7 @@ static void applyMulticastToInterface4(uint32_t ifindex)
                              .imr_address.s_addr = htonl(INADDR_ANY),
                              .imr_ifindex = ifindex };
 #else
-    struct ip_mreq mreq  = { .imr_multiaddr = IPv4MulticastAddress,
+    struct ip_mreq mreq  = { .imr_multiaddr.s_addr = IPv4MulticastAddress.s_addr,
                              .imr_interface.s_addr = htonl(ifindex) };
 #endif
 
@@ -1040,8 +1040,12 @@ static void applyMulticastToInterface4(uint32_t ifindex)
 
 static void applyMulticast6(int fd, struct in6_addr *addr, uint32_t ifindex)
 {
-    struct ipv6_mreq mreq = {.ipv6mr_multiaddr = *addr,
+    struct ipv6_mreq mreq = {.ipv6mr_multiaddr = {0},
                              .ipv6mr_interface = ifindex };
+
+    // VS2013 has problems with struct copies inside struct initializers, so copy separately.
+    mreq.ipv6mr_multiaddr = *addr;
+
     int ret = setsockopt(fd, IPPROTO_IPV6, IPV6_JOIN_GROUP, OPTVAL_T(&mreq), sizeof (mreq));
     if (OC_SOCKET_ERROR == ret)
     {
@@ -1338,7 +1342,7 @@ static void sendMulticastData4(const u_arraylist_t *iflist,
                              .imr_address.s_addr = htonl(INADDR_ANY),
                              .imr_ifindex = 0};
 #else
-    struct ip_mreq mreq  = { .imr_multiaddr = IPv4MulticastAddress,
+    struct ip_mreq mreq  = { .imr_multiaddr.s_addr = IPv4MulticastAddress.s_addr,
                              .imr_interface = {0}};
 #endif
 
index 7d09727..a839ab9 100644 (file)
@@ -39,7 +39,7 @@
 #include <linux/rtnetlink.h>
 #endif
 
-#include "camutex.h"
+#include "octhread.h"
 #include "caadapterutils.h"
 #include "logger.h"
 #include "oic_malloc.h"
@@ -50,7 +50,7 @@
 /**
  * Mutex for synchronizing access to cached interface and IP address information.
  */
-static ca_mutex g_networkMonitorContextMutex = NULL;
+static oc_mutex g_networkMonitorContextMutex = NULL;
 
 /**
  * Used to storing network interface.
@@ -68,10 +68,10 @@ static CAResult_t CAIPInitializeNetworkMonitorList()
 {
     if (!g_networkMonitorContextMutex)
     {
-        g_networkMonitorContextMutex = ca_mutex_new();
+        g_networkMonitorContextMutex = oc_mutex_new();
         if (!g_networkMonitorContextMutex)
         {
-            OIC_LOG(ERROR, TAG, "ca_mutex_new has failed");
+            OIC_LOG(ERROR, TAG, "oc_mutex_new has failed");
             return CA_STATUS_FAILED;
         }
     }
@@ -99,7 +99,7 @@ static void CAIPDestroyNetworkMonitorList()
 
     if (g_networkMonitorContextMutex)
     {
-        ca_mutex_free(g_networkMonitorContextMutex);
+        oc_mutex_free(g_networkMonitorContextMutex);
         g_networkMonitorContextMutex = NULL;
     }
 }
@@ -112,7 +112,7 @@ static bool CACmpNetworkList(uint32_t ifiindex)
         return false;
     }
 
-    ca_mutex_lock(g_networkMonitorContextMutex);
+    oc_mutex_lock(g_networkMonitorContextMutex);
 
     uint32_t list_length = u_arraylist_length(g_netInterfaceList);
     for (uint32_t list_index = 0; list_index < list_length; list_index++)
@@ -120,11 +120,11 @@ static bool CACmpNetworkList(uint32_t ifiindex)
         CAInterface_t *currItem = (CAInterface_t *) u_arraylist_get(g_netInterfaceList, list_index);
         if (currItem->index == ifiindex)
         {
-            ca_mutex_unlock(g_networkMonitorContextMutex);
+            oc_mutex_unlock(g_networkMonitorContextMutex);
             return true;
         }
     }
-    ca_mutex_unlock(g_networkMonitorContextMutex);
+    oc_mutex_unlock(g_networkMonitorContextMutex);
     return false;
 }
 
@@ -133,15 +133,15 @@ static CAResult_t CAAddNetworkMonitorList(CAInterface_t *ifitem)
     VERIFY_NON_NULL(g_netInterfaceList, TAG, "g_netInterfaceList is NULL");
     VERIFY_NON_NULL(ifitem, TAG, "ifitem is NULL");
 
-    ca_mutex_lock(g_networkMonitorContextMutex);
+    oc_mutex_lock(g_networkMonitorContextMutex);
     bool result = u_arraylist_add(g_netInterfaceList, (void *) ifitem);
     if (!result)
     {
         OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
-        ca_mutex_unlock(g_networkMonitorContextMutex);
+        oc_mutex_unlock(g_networkMonitorContextMutex);
         return CA_STATUS_FAILED;
     }
-    ca_mutex_unlock(g_networkMonitorContextMutex);
+    oc_mutex_unlock(g_networkMonitorContextMutex);
     return CA_STATUS_OK;
 }
 
@@ -149,7 +149,7 @@ static void CARemoveNetworkMonitorList(int ifiindex)
 {
     VERIFY_NON_NULL_VOID(g_netInterfaceList, TAG, "g_netInterfaceList is NULL");
 
-    ca_mutex_lock(g_networkMonitorContextMutex);
+    oc_mutex_lock(g_networkMonitorContextMutex);
 
     uint32_t list_length = u_arraylist_length(g_netInterfaceList);
     for (uint32_t list_index = 0; list_index < list_length; list_index++)
@@ -161,13 +161,13 @@ static void CARemoveNetworkMonitorList(int ifiindex)
             if (u_arraylist_remove(g_netInterfaceList, list_index))
             {
                 OICFree(removedifitem);
-                ca_mutex_unlock(g_networkMonitorContextMutex);
+                oc_mutex_unlock(g_networkMonitorContextMutex);
                 return;
             }
             continue;
         }
     }
-    ca_mutex_unlock(g_networkMonitorContextMutex);
+    oc_mutex_unlock(g_networkMonitorContextMutex);
     return;
 }
 
index fa66949..3635f15 100644 (file)
@@ -269,6 +269,13 @@ u_arraylist_t *CAIPGetInterfaceInformation(int desiredIndex)
         {
             goto exit;
         }
+
+        // Add IPv6 interface
+        result = CAAddInterfaceItem(iflist, ifindex, name, AF_INET6, addr, flags);
+        if (CA_STATUS_OK != result)
+        {
+            goto exit;
+        }
     }
     return iflist;
 
index 0b06a1d..3fc370e 100644 (file)
@@ -20,7 +20,7 @@
 #include "canfcinterface.h"\r
 \r
 #include "caadapterutils.h"\r
-#include "camutex.h"\r
+#include "octhread.h"\r
 #include "oic_malloc.h"\r
 #include "oic_string.h"\r
 \r
index 4f8e57e..084fbf3 100644 (file)
@@ -19,7 +19,7 @@
 #include "canfcinterface.h"
 #include "caqueueingthread.h"
 #include "caadapterutils.h"
-#include "camutex.h"
+#include "octhread.h"
 #include "uarraylist.h"
 #include "caremotehandler.h"
 #include "logger.h"
index 86741fe..11f56cb 100644 (file)
@@ -26,7 +26,7 @@
 #include <stdint.h>
 
 #include "caadapterutils.h"
-#include "camutex.h"
+#include "octhread.h"
 #include "uarraylist.h"
 #include "logger.h"
 #include "oic_malloc.h"
@@ -77,7 +77,7 @@ typedef struct
     CAJidBoundCallback jidBoundCallback;
 } CARAXmppData_t;
 
-static ca_mutex g_raadapterMutex = NULL;
+static oc_mutex g_raadapterMutex = NULL;
 
 static CARAXmppData_t g_xmppData = {.xmpp = NULL, .port = 5222, .hostName = {0},
     .password = {0}, .jid = {0}, .connectionStatus = CA_INTERFACE_DOWN,
@@ -231,16 +231,16 @@ static char *CARAGetSIDFromPDU(coap_pdu_t *pdu)
 
     VERIFY_NON_NULL_RET(pdu, RA_ADAPTER_TAG, "Invalid parameter!", NULL);
 
-    if (pdu->hdr->coap_hdr_udp_t.token_length * 2 > MAX_IBB_SESSION_ID_LENGTH)
+    if (pdu->hdr->token_length * 2 > MAX_IBB_SESSION_ID_LENGTH)
     {
         OIC_LOG(ERROR, RA_ADAPTER_TAG, "Token length more than expected!");
         return NULL;
     }
 
     char hex[3] = {0};
-    for (int i = 0; i < pdu->hdr->coap_hdr_udp_t.token_length; i++)
+    for (int i = 0; i < pdu->hdr->token_length; i++)
     {
-        snprintf(hex, 3, "%02x", pdu->hdr->coap_hdr_udp_t.token[i]);
+        snprintf(hex, 3, "%02x", pdu->hdr->token[i]);
         OICStrcat(s_sid, sizeof(s_sid), hex);
     }
 
@@ -451,14 +451,14 @@ CAResult_t CAStartRA()
         return CA_STATUS_FAILED;
     }
 
-    g_raadapterMutex = ca_mutex_new ();
+    g_raadapterMutex = oc_mutex_new ();
     if (!g_raadapterMutex)
     {
         OIC_LOG (ERROR, RA_ADAPTER_TAG, PCF("Memory allocation for mutex failed."));
         return CA_MEMORY_ALLOC_FAILED;
     }
 
-    ca_mutex_lock (g_raadapterMutex);
+    oc_mutex_lock (g_raadapterMutex);
 
     xmpphelper_connect(g_xmppData.xmpp, g_xmppData.hostName, g_xmppData.port,
                     g_xmppData.jid, g_xmppData.password);
@@ -471,7 +471,7 @@ CAResult_t CAStartRA()
 
     xmpphelper_run(g_xmppData.xmpp);
 
-    ca_mutex_unlock (g_raadapterMutex);
+    oc_mutex_unlock (g_raadapterMutex);
 
     OIC_LOG(DEBUG, RA_ADAPTER_TAG, "RA adapter started succesfully");
     return CA_STATUS_OK;
@@ -485,7 +485,7 @@ CAResult_t CAStopRA()
     xmpp_ibb_unregister(xmpphelper_get_conn(g_xmppData.xmpp));
     if (!g_raadapterMutex)
     {
-        ca_mutex_free (g_raadapterMutex);
+        oc_mutex_free (g_raadapterMutex);
         g_raadapterMutex = NULL;
     }
     OIC_LOG(DEBUG, RA_ADAPTER_TAG, PCF("Stopped RA adapter successfully"));
@@ -516,11 +516,11 @@ int32_t CASendRAUnicastData(const CAEndpoint_t *remoteEndpoint, const void *data
     int obsopt = CARAGetReqObsOption(pdu, remoteEndpoint);
     coap_delete_pdu(pdu);
 
-    ca_mutex_lock (g_raadapterMutex);
+    oc_mutex_lock (g_raadapterMutex);
     if (CA_INTERFACE_UP != g_xmppData.connectionStatus)
     {
         OIC_LOG(ERROR, RA_ADAPTER_TAG, "Unable to send XMPP message, RA not connected");
-        ca_mutex_unlock (g_raadapterMutex);
+        oc_mutex_unlock (g_raadapterMutex);
         return -1;
     }
 
@@ -531,7 +531,7 @@ int32_t CASendRAUnicastData(const CAEndpoint_t *remoteEndpoint, const void *data
         if (sess == NULL)
         {
             OIC_LOG(ERROR, RA_ADAPTER_TAG, "IBB session establish failed!");
-            ca_mutex_unlock (g_raadapterMutex);
+            oc_mutex_unlock (g_raadapterMutex);
             return -1;
         }
     }
@@ -544,7 +544,7 @@ int32_t CASendRAUnicastData(const CAEndpoint_t *remoteEndpoint, const void *data
     }
     xmppdata_t xdata = {.data = (char *) data, .size = dataLength};
     int rc = xmpp_ibb_send_data(sess, &xdata);
-    ca_mutex_unlock (g_raadapterMutex);
+    oc_mutex_unlock (g_raadapterMutex);
     if (rc < 0)
     {
         OIC_LOG(ERROR, RA_ADAPTER_TAG, "IBB send data failed!");
@@ -628,7 +628,7 @@ typedef struct
     char jabberID[CA_RAJABBERID_SIZE];
 } CARAXmppData_t;
 
-static ca_mutex g_raadapterMutex = NULL;
+static oc_mutex g_raadapterMutex = NULL;
 
 static CARAXmppData_t g_xmppData = {};
 
@@ -674,7 +674,7 @@ void CARAXmppConnectedCB(void * const param, xmpp_error_code_t result,
     {
         printf("\n\n\t\t===>your jid: %s\n\n", bound_jid);
 
-        ca_mutex_lock (g_raadapterMutex);
+        oc_mutex_lock (g_raadapterMutex);
         OICStrcpy (g_xmppData.jabberID, CA_RAJABBERID_SIZE, bound_jid);
 
         g_xmppData.connection_status = CA_INTERFACE_UP;
@@ -692,7 +692,7 @@ void CARAXmppConnectedCB(void * const param, xmpp_error_code_t result,
         OIC_LOG_V(ERROR, RA_ADAPTER_TAG, "XMPP connected callback status: %d", result);
     }
 
-    ca_mutex_unlock (g_raadapterMutex);
+    oc_mutex_unlock (g_raadapterMutex);
     // Notify network change to CA
     CARANotifyNetworkChange(bound_jid, connection_status);
 
@@ -704,13 +704,13 @@ void CARAXmppDisonnectedCB(void * const param, xmpp_error_code_t result,
 {
     OIC_LOG(DEBUG, RA_ADAPTER_TAG, "CARAXmppDisonnectedCB IN");
     char jabberID[CA_RAJABBERID_SIZE];
-    ca_mutex_lock (g_raadapterMutex);
+    oc_mutex_lock (g_raadapterMutex);
 
     g_xmppData.connection_status = CA_INTERFACE_DOWN;
     xmpp_message_context_destroy(g_xmppData.message_context);
     OICStrcpy (jabberID, CA_RAJABBERID_SIZE, g_xmppData.jabberID);
 
-    ca_mutex_unlock (g_raadapterMutex);
+    oc_mutex_unlock (g_raadapterMutex);
 
     // Notify network change to CA
     CARANotifyNetworkChange(jabberID, CA_INTERFACE_DOWN);
@@ -824,14 +824,14 @@ CAResult_t CAStartRA()
 
     OIC_LOG(DEBUG, RA_ADAPTER_TAG, PCF("Starting RA adapter"));
 
-    g_raadapterMutex = ca_mutex_new ();
+    g_raadapterMutex = oc_mutex_new ();
     if (!g_raadapterMutex)
     {
         OIC_LOG (ERROR, RA_ADAPTER_TAG, PCF("Memory allocation for mutex failed."));
         return CA_MEMORY_ALLOC_FAILED;
     }
 
-    ca_mutex_lock (g_raadapterMutex);
+    oc_mutex_lock (g_raadapterMutex);
 
     xmpp_context_init(&g_xmppData.context);
     g_xmppData.handle = xmpp_startup(&g_xmppData.context);
@@ -848,7 +848,7 @@ CAResult_t CAStartRA()
     xmpp_identity_destroy(&g_xmppData.g_identity);
     xmpp_host_destroy(&g_xmppData.g_host);
 
-    ca_mutex_unlock (g_raadapterMutex);
+    oc_mutex_unlock (g_raadapterMutex);
 
     if (XMPP_ERR_OK != ret)
     {
@@ -875,7 +875,7 @@ CAResult_t CAStopRA()
 
     xmpp_shutdown_xmpp(g_xmppData.handle);
     xmpp_context_destroy(&g_xmppData.context);
-    ca_mutex_free (g_raadapterMutex);
+    oc_mutex_free (g_raadapterMutex);
     g_raadapterMutex = NULL;
 
     OIC_LOG(DEBUG, RA_ADAPTER_TAG, PCF("Stopped RA adapter successfully"));
@@ -899,12 +899,12 @@ int32_t CASendRAUnicastData(const CAEndpoint_t *remoteEndpoint, const void *data
     }
 
     OIC_LOG_V(ERROR, RA_ADAPTER_TAG, "Sending unicast data to %s", remoteEndpoint->addr);
-    ca_mutex_lock (g_raadapterMutex);
+    oc_mutex_lock (g_raadapterMutex);
 
     if (CA_INTERFACE_UP != g_xmppData.connection_status)
     {
         OIC_LOG(ERROR, RA_ADAPTER_TAG, "Unable to send XMPP message, RA not connected");
-        ca_mutex_unlock (g_raadapterMutex);
+        oc_mutex_unlock (g_raadapterMutex);
         return -1;
     }
 
@@ -914,10 +914,10 @@ int32_t CASendRAUnicastData(const CAEndpoint_t *remoteEndpoint, const void *data
     if (XMPP_ERR_OK != res)
     {
         OIC_LOG_V(ERROR, RA_ADAPTER_TAG, "Unable to send XMPP message, status: %d", res);
-        ca_mutex_unlock (g_raadapterMutex);
+        oc_mutex_unlock (g_raadapterMutex);
         return -1;
     }
-    ca_mutex_unlock (g_raadapterMutex);
+    oc_mutex_unlock (g_raadapterMutex);
 
     OIC_LOG_V(INFO, RA_ADAPTER_TAG, "Successfully dispatched bytes[%d] to addr[%s]",
             dataLength, remoteEndpoint->addr);
@@ -930,16 +930,16 @@ CAResult_t CAGetRAInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
     VERIFY_NON_NULL(info, RA_ADAPTER_TAG, "info is NULL");
     VERIFY_NON_NULL(size, RA_ADAPTER_TAG, "size is NULL");
 
-    ca_mutex_lock (g_raadapterMutex);
+    oc_mutex_lock (g_raadapterMutex);
 
     if (CA_INTERFACE_UP != g_xmppData.connection_status)
     {
         OIC_LOG(ERROR, RA_ADAPTER_TAG, "Failed to get interface info, RA not Connected");
-        ca_mutex_unlock (g_raadapterMutex);
+        oc_mutex_unlock (g_raadapterMutex);
         return CA_ADAPTER_NOT_ENABLED;
     }
 
-    ca_mutex_unlock (g_raadapterMutex);
+    oc_mutex_unlock (g_raadapterMutex);
 
     CAEndpoint_t *localEndpoint = CACreateEndpointObject(CA_DEFAULT_FLAGS,
                                  CA_ADAPTER_REMOTE_ACCESS,
index b290eb3..58293fd 100644 (file)
@@ -29,9 +29,9 @@
 
 #include "catcpadapterutils_eth.h"
 #include "catcpinterface.h"
-#include "pdu.h"
+#include <coap/pdu.h>
 #include "caadapterutils.h"
-#include "camutex.h"
+#include "octhread.h"
 #include "oic_malloc.h"
 #include "oic_string.h"
 
@@ -212,7 +212,7 @@ void CATCPReadDataInternal()
 
             if (!isHeaderChecked && totalReceivedLen)
             {
-                coap_transport_type transport;
+                coap_transport_t transport;
                 size_t headerLen;
                 CAGetTCPHeaderDetails(recvBuffer, &transport, &headerLen);
                 if (totalReceivedLen >= headerLen)
@@ -326,4 +326,4 @@ void CATCPSendData(CAEndpoint_t *endpoint, const void *data, uint32_t datalen,
             sendData(endpoint, data, datalen);
         }
     }
-}
\ No newline at end of file
+}
index cec1f42..afe653f 100644 (file)
@@ -33,7 +33,7 @@
 #include "catcpinterface.h"
 #include "caqueueingthread.h"
 #include "caadapterutils.h"
-#include "camutex.h"
+#include "octhread.h"
 #include "uarraylist.h"
 #include "caremotehandler.h"
 #include "logger.h"
@@ -549,7 +549,7 @@ size_t CAGetTotalLengthFromPacketHeader(const unsigned char *recvBuffer, size_t
         return 0;
     }
 
-    coap_transport_type transport = coap_get_tcp_header_type_from_initbyte(
+    coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(
             ((unsigned char *)recvBuffer)[0] >> 4);
     size_t optPaylaodLen = coap_get_length_from_header((unsigned char *)recvBuffer,
                                                         transport);
@@ -563,7 +563,7 @@ size_t CAGetTotalLengthFromPacketHeader(const unsigned char *recvBuffer, size_t
     return headerLen + optPaylaodLen;
 }
 
-void CAGetTCPHeaderDetails(unsigned char* recvBuffer, coap_transport_type *transport,
+void CAGetTCPHeaderDetails(unsigned char* recvBuffer, coap_transport_t *transport,
                            size_t *headerlen)
 {
     if (NULL == recvBuffer)
index d532c10..3337ef0 100644 (file)
@@ -38,9 +38,9 @@
 #endif
 
 #include "catcpinterface.h"
-#include "pdu.h"
+#include <coap/pdu.h>
 #include "caadapterutils.h"
-#include "camutex.h"
+#include "octhread.h"
 #include "oic_malloc.h"
 
 #ifdef __WITH_TLS__
 /**
  * Mutex to synchronize device object list.
  */
-static ca_mutex g_mutexObjectList = NULL;
+static oc_mutex g_mutexObjectList = NULL;
 
 /**
  * Conditional mutex to synchronize.
  */
-static ca_cond g_condObjectList = NULL;
+static oc_cond g_condObjectList = NULL;
 
 /**
  * Maintains the callback to be notified when data received from remote device.
@@ -154,7 +154,7 @@ static void CATCPDestroyMutex()
 {
     if (g_mutexObjectList)
     {
-        ca_mutex_free(g_mutexObjectList);
+        oc_mutex_free(g_mutexObjectList);
         g_mutexObjectList = NULL;
     }
 }
@@ -163,7 +163,7 @@ static CAResult_t CATCPCreateMutex()
 {
     if (!g_mutexObjectList)
     {
-        g_mutexObjectList = ca_mutex_new();
+        g_mutexObjectList = oc_mutex_new();
         if (!g_mutexObjectList)
         {
             OIC_LOG(ERROR, TAG, "Failed to created mutex!");
@@ -178,7 +178,7 @@ static void CATCPDestroyCond()
 {
     if (g_condObjectList)
     {
-        ca_cond_free(g_condObjectList);
+        oc_cond_free(g_condObjectList);
         g_condObjectList = NULL;
     }
 }
@@ -187,7 +187,7 @@ static CAResult_t CATCPCreateCond()
 {
     if (!g_condObjectList)
     {
-        g_condObjectList = ca_cond_new();
+        g_condObjectList = oc_cond_new();
         if (!g_condObjectList)
         {
             OIC_LOG(ERROR, TAG, "Failed to created cond!");
@@ -207,9 +207,9 @@ static void CAReceiveHandler(void *data)
         CAFindReadyMessage();
     }
 
-    ca_mutex_lock(g_mutexObjectList);
-    ca_cond_signal(g_condObjectList);
-    ca_mutex_unlock(g_mutexObjectList);
+    oc_mutex_lock(g_mutexObjectList);
+    oc_cond_signal(g_condObjectList);
+    oc_mutex_unlock(g_mutexObjectList);
 
     OIC_LOG(DEBUG, TAG, "OUT - CAReceiveHandler");
 }
@@ -341,35 +341,36 @@ static void CAAcceptConnection(CATransportFlags_t flag, CASocket_t *sock)
 
         svritem->fd = sockfd;
         svritem->sep.endpoint.flags = flag;
+        svritem->sep.endpoint.adapter = CA_ADAPTER_TCP;
         CAConvertAddrToName((struct sockaddr_storage *)&clientaddr, clientlen,
                             svritem->sep.endpoint.addr, &svritem->sep.endpoint.port);
 
-        ca_mutex_lock(g_mutexObjectList);
+        oc_mutex_lock(g_mutexObjectList);
         bool result = u_arraylist_add(caglobals.tcp.svrlist, svritem);
         if (!result)
         {
             OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
             close(sockfd);
             OICFree(svritem);
-            ca_mutex_unlock(g_mutexObjectList);
+            oc_mutex_unlock(g_mutexObjectList);
             return;
         }
-        ca_mutex_unlock(g_mutexObjectList);
+        oc_mutex_unlock(g_mutexObjectList);
 
         CHECKFD(sockfd);
     }
 }
 
 #ifdef __WITH_TLS__
-static bool CAIsTlsMessage(const CATCPSessionInfo_t * recvinfo)
+static bool CAIsTlsMessage(const unsigned char* data, size_t length)
 {
-    if (recvinfo->data == NULL || recvinfo->len == 0)
+    if (NULL == data || 0 == length)
     {
         OIC_LOG_V(ERROR, TAG, "%s: null input param", __func__);
         return false;
     }
 
-    unsigned char first_byte = recvinfo->data[0];
+    unsigned char first_byte = data[0];
 
     //TLS Plaintext has four types: change_cipher_spec = [14], alert = [15],
     //handshake = [16], application_data = [17] in HEX
@@ -450,7 +451,7 @@ static CAResult_t CAReadHeader(CATCPSessionInfo_t *svritem)
 
     //if enough data received - parse header
 #ifdef __WITH_TLS__
-    if (CAIsTlsMessage(svritem))
+    if (CAIsTlsMessage(svritem->data, svritem->len))
     {
         svritem->protocol = TLS;
 
@@ -466,7 +467,7 @@ static CAResult_t CAReadHeader(CATCPSessionInfo_t *svritem)
         svritem->protocol = COAP;
 
         //seems CoAP data received. read full coap header.
-        coap_transport_type transport = coap_get_tcp_header_type_from_initbyte(svritem->data[0] >> 4);
+        coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(svritem->data[0] >> 4);
 
         size_t headerLen = coap_get_tcp_header_length_for_transport(transport);
 
@@ -725,7 +726,7 @@ static int CACreateAcceptSocket(int family, CASocket_t *sock)
 
     if (family == AF_INET6)
     {
-        // the socket is restricted to sending and receiving IPv6 packets only.
+        // the socket is restricted to sending and receiving IPv6 packets only.
         int on = 1;
         if (-1 == setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof (on)))
         {
@@ -849,12 +850,12 @@ CAResult_t CATCPStartServer(const ca_thread_pool_t threadPool)
         return res;
     }
 
-    ca_mutex_lock(g_mutexObjectList);
+    oc_mutex_lock(g_mutexObjectList);
     if (!caglobals.tcp.svrlist)
     {
         caglobals.tcp.svrlist = u_arraylist_create();
     }
-    ca_mutex_unlock(g_mutexObjectList);
+    oc_mutex_unlock(g_mutexObjectList);
 
     if (caglobals.server)
     {
@@ -892,7 +893,7 @@ CAResult_t CATCPStartServer(const ca_thread_pool_t threadPool)
 void CATCPStopServer()
 {
     // mutex lock
-    ca_mutex_lock(g_mutexObjectList);
+    oc_mutex_lock(g_mutexObjectList);
 
     // set terminate flag
     caglobals.tcp.terminate = true;
@@ -910,12 +911,12 @@ void CATCPStopServer()
 
     if (caglobals.tcp.started)
     {
-        ca_cond_wait(g_condObjectList, g_mutexObjectList);
+        oc_cond_wait(g_condObjectList, g_mutexObjectList);
     }
     caglobals.tcp.started = false;
 
     // mutex unlock
-    ca_mutex_unlock(g_mutexObjectList);
+    oc_mutex_unlock(g_mutexObjectList);
 
     if (-1 != caglobals.tcp.ipv4.fd)
     {
@@ -948,17 +949,17 @@ static size_t CACheckPayloadLength(const void *data, size_t dlen)
 {
     VERIFY_NON_NULL_RET(data, TAG, "data", -1);
 
-    coap_transport_type transport = coap_get_tcp_header_type_from_initbyte(
+    coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(
             ((unsigned char *)data)[0] >> 4);
 
-    coap_pdu_t *pdu = coap_new_pdu(transport, dlen);
+    coap_pdu_t *pdu = coap_new_pdu2(transport, dlen);
     if (!pdu)
     {
         OIC_LOG(ERROR, TAG, "outpdu is null");
         return 0;
     }
 
-    int ret = coap_pdu_parse((unsigned char *) data, dlen, pdu, transport);
+    int ret = coap_pdu_parse2((unsigned char *) data, dlen, pdu, transport);
     if (0 >= ret)
     {
         OIC_LOG(ERROR, TAG, "pdu parse failed");
@@ -1003,7 +1004,7 @@ static void sendData(const CAEndpoint_t *endpoint, const void *data,
 
     // #2. check payload length
 #ifdef __WITH_TLS__
-    if (false == CAIsTlsMessage(svritem))
+    if (false == CAIsTlsMessage(data, dlen))
 #endif
     {
         size_t payloadLen = CACheckPayloadLength(data, dlen);
@@ -1112,7 +1113,7 @@ CATCPSessionInfo_t *CAConnectTCPSession(const CAEndpoint_t *endpoint)
 
     // #3. add TCP connection info to list
     svritem->fd = fd;
-    ca_mutex_lock(g_mutexObjectList);
+    oc_mutex_lock(g_mutexObjectList);
     if (caglobals.tcp.svrlist)
     {
         bool res = u_arraylist_add(caglobals.tcp.svrlist, svritem);
@@ -1121,11 +1122,11 @@ CATCPSessionInfo_t *CAConnectTCPSession(const CAEndpoint_t *endpoint)
             OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
             close(svritem->fd);
             OICFree(svritem);
-            ca_mutex_unlock(g_mutexObjectList);
+            oc_mutex_unlock(g_mutexObjectList);
             return NULL;
         }
     }
-    ca_mutex_unlock(g_mutexObjectList);
+    oc_mutex_unlock(g_mutexObjectList);
 
     CHECKFD(fd);
 
@@ -1142,7 +1143,7 @@ CAResult_t CADisconnectTCPSession(CATCPSessionInfo_t *svritem, size_t index)
 {
     VERIFY_NON_NULL(svritem, TAG, "svritem is NULL");
 
-    ca_mutex_lock(g_mutexObjectList);
+    oc_mutex_lock(g_mutexObjectList);
 
     // close the socket and remove TCP connection info in list
     if (svritem->fd >= 0)
@@ -1160,14 +1161,14 @@ CAResult_t CADisconnectTCPSession(CATCPSessionInfo_t *svritem, size_t index)
     }
 
     OICFree(svritem);
-    ca_mutex_unlock(g_mutexObjectList);
+    oc_mutex_unlock(g_mutexObjectList);
 
     return CA_STATUS_OK;
 }
 
 void CATCPDisconnectAll()
 {
-    ca_mutex_lock(g_mutexObjectList);
+    oc_mutex_lock(g_mutexObjectList);
     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
 
     CATCPSessionInfo_t *svritem = NULL;
@@ -1184,7 +1185,7 @@ void CATCPDisconnectAll()
         }
     }
     u_arraylist_destroy(caglobals.tcp.svrlist);
-    ca_mutex_unlock(g_mutexObjectList);
+    oc_mutex_unlock(g_mutexObjectList);
 }
 
 CATCPSessionInfo_t *CAGetTCPSessionInfoFromEndpoint(const CAEndpoint_t *endpoint, size_t *index)
@@ -1218,7 +1219,7 @@ CATCPSessionInfo_t *CAGetTCPSessionInfoFromEndpoint(const CAEndpoint_t *endpoint
 
 CATCPSessionInfo_t *CAGetSessionInfoFromFD(int fd, size_t *index)
 {
-    ca_mutex_lock(g_mutexObjectList);
+    oc_mutex_lock(g_mutexObjectList);
 
     // check from the last item.
     CATCPSessionInfo_t *svritem = NULL;
@@ -1230,12 +1231,12 @@ CATCPSessionInfo_t *CAGetSessionInfoFromFD(int fd, size_t *index)
         if (svritem && svritem->fd == fd)
         {
             *index = i;
-            ca_mutex_unlock(g_mutexObjectList);
+            oc_mutex_unlock(g_mutexObjectList);
             return svritem;
         }
     }
 
-    ca_mutex_unlock(g_mutexObjectList);
+    oc_mutex_unlock(g_mutexObjectList);
 
     return NULL;
 }
@@ -1244,7 +1245,7 @@ size_t CAGetTotalLengthFromHeader(const unsigned char *recvBuffer)
 {
     OIC_LOG(DEBUG, TAG, "IN - CAGetTotalLengthFromHeader");
 
-    coap_transport_type transport = coap_get_tcp_header_type_from_initbyte(
+    coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(
             ((unsigned char *)recvBuffer)[0] >> 4);
     size_t optPaylaodLen = coap_get_length_from_header((unsigned char *)recvBuffer,
                                                         transport);
index 0dc19e0..62dfaf4 100644 (file)
@@ -59,7 +59,6 @@ if catest_env.get('LOGGING'):
        catest_env.AppendUnique(CPPDEFINES = ['TB_LOG'])
 
 if target_os in ['msys_nt', 'windows']:
-       catest_env.AppendUnique(LINKFLAGS = ['/subsystem:CONSOLE'])
        catest_env.AppendUnique(LIBS = ['ws2_32',
                                         'advapi32',
                                         'iphlpapi'])
@@ -76,7 +75,7 @@ if (('IP' in target_transport) or ('ALL' in target_transport)):
                                                         'caprotocolmessagetest.cpp',
                                                         'cablocktransfertest.cpp',
                                                         'ca_api_unittest.cpp',
-                                                        'camutex_tests.cpp',
+                                                        'octhread_tests.cpp',
                                                         'uarraylist_test.cpp',
                                                         'ulinklist_test.cpp',
                                                         'uqueue_test.cpp'
@@ -86,7 +85,7 @@ else:
                catests = catest_env.Program('catests', ['catests.cpp',
                                                         'caprotocolmessagetest.cpp',
                                                         'ca_api_unittest.cpp',
-                                                        'camutex_tests.cpp',
+                                                        'octhread_tests.cpp',
                                                         'uarraylist_test.cpp',
                                                         'ulinklist_test.cpp',
                                                         'uqueue_test.cpp'
index 5efc456..040c7e0 100644 (file)
@@ -47,7 +47,7 @@ TEST_F(CABlockTransferTests, CACreateNewDataSetTest)
 
     coap_pdu_t *pdu = NULL;
     coap_list_t *options = NULL;
-    coap_transport_type transport = coap_udp;
+    coap_transport_t transport = COAP_UDP;
 
     CAToken_t tempToken = NULL;
     CAGenerateToken(&tempToken, CA_MAX_TOKEN_LEN);
@@ -100,7 +100,7 @@ TEST_F(CABlockTransferTests, CARemoveBlockDataFromListWithSeed)
 
     coap_pdu_t *pdu = NULL;
     coap_list_t *options = NULL;
-    coap_transport_type transport = coap_udp;
+    coap_transport_t transport = COAP_UDP;
 
     CAToken_t tempToken = NULL;
     CAGenerateToken(&tempToken, CA_MAX_TOKEN_LEN);
@@ -151,7 +151,7 @@ TEST_F(CABlockTransferTests, CAGetBlockDataFromBlockDataListTest)
 
     coap_pdu_t *pdu = NULL;
     coap_list_t *options = NULL;
-    coap_transport_type transport = coap_udp;
+    coap_transport_t transport = COAP_UDP;
 
     CAToken_t tempToken = NULL;
     CAGenerateToken(&tempToken, CA_MAX_TOKEN_LEN);
@@ -194,7 +194,7 @@ TEST_F(CABlockTransferTests, CAGetPayloadFromBlockDataListTest)
 
     coap_pdu_t *pdu = NULL;
     coap_list_t *options = NULL;
-    coap_transport_type transport = coap_udp;
+    coap_transport_t transport = COAP_UDP;
 
     CAToken_t tempToken = NULL;
     CAGenerateToken(&tempToken, CA_MAX_TOKEN_LEN);
@@ -242,7 +242,7 @@ TEST_F(CABlockTransferTests, CAAddBlockOptionTest)
 
     coap_pdu_t *pdu = NULL;
     coap_list_t *options = NULL;
-    coap_transport_type transport = coap_udp;
+    coap_transport_t transport = COAP_UDP;
 
     CAToken_t tempToken = NULL;
     CAGenerateToken(&tempToken, CA_MAX_TOKEN_LEN);
@@ -282,7 +282,7 @@ TEST_F(CABlockTransferTests, CAAddBlockOption1InRequest)
 
     coap_pdu_t *pdu = NULL;
     coap_list_t *options = NULL;
-    coap_transport_type transport = coap_udp;
+    coap_transport_t transport = COAP_UDP;
 
     CAToken_t tempToken = NULL;
     CAGenerateToken(&tempToken, CA_MAX_TOKEN_LEN);
@@ -337,7 +337,7 @@ TEST_F(CABlockTransferTests, CAAddBlockOption1InResponse)
 
     coap_pdu_t *pdu = NULL;
     coap_list_t *options = NULL;
-    coap_transport_type transport = coap_udp;
+    coap_transport_t transport = COAP_UDP;
 
     CAToken_t tempToken = NULL;
     CAGenerateToken(&tempToken, CA_MAX_TOKEN_LEN);
@@ -393,7 +393,7 @@ TEST_F(CABlockTransferTests, CAAddBlockOption2InResponse)
 
     coap_pdu_t *pdu = NULL;
     coap_list_t *options = NULL;
-    coap_transport_type transport = coap_udp;
+    coap_transport_t transport = COAP_UDP;
 
     CAToken_t tempToken = NULL;
     CAGenerateToken(&tempToken, CA_MAX_TOKEN_LEN);
@@ -449,7 +449,7 @@ TEST_F(CABlockTransferTests, CAAddBlockOption2InRequest)
 
     coap_pdu_t *pdu = NULL;
     coap_list_t *options = NULL;
-    coap_transport_type transport = coap_udp;
+    coap_transport_t transport = COAP_UDP;
 
     CAToken_t tempToken = NULL;
     CAGenerateToken(&tempToken, CA_MAX_TOKEN_LEN);
@@ -503,7 +503,7 @@ TEST_F(CABlockTransferTests, CAGetBlockSizeOptionFromPduTest)
 
     coap_pdu_t *pdu = NULL;
     coap_list_t *options = NULL;
-    coap_transport_type transport = coap_udp;
+    coap_transport_t transport = COAP_UDP;
 
     CAToken_t tempToken = NULL;
     CAGenerateToken(&tempToken, CA_MAX_TOKEN_LEN);
@@ -535,7 +535,7 @@ TEST_F(CABlockTransferTests, CASetNextBlockOption1WithRequest)
 
     coap_pdu_t *pdu = NULL;
     coap_list_t *options = NULL;
-    coap_transport_type transport = coap_udp;
+    coap_transport_t transport = COAP_UDP;
 
     CAToken_t tempToken = NULL;
     CAGenerateToken(&tempToken, CA_MAX_TOKEN_LEN);
@@ -573,7 +573,7 @@ TEST_F(CABlockTransferTests, CASetNextBlockOption1WithResponse)
 
     coap_pdu_t *pdu = NULL;
     coap_list_t *options = NULL;
-    coap_transport_type transport = coap_udp;
+    coap_transport_t transport = COAP_UDP;
 
     CAToken_t tempToken = NULL;
     CAGenerateToken(&tempToken, CA_MAX_TOKEN_LEN);
@@ -612,7 +612,7 @@ TEST_F(CABlockTransferTests, CASetNextBlockOption2WithRequest)
 
     coap_pdu_t *pdu = NULL;
     coap_list_t *options = NULL;
-    coap_transport_type transport = coap_udp;
+    coap_transport_t transport = COAP_UDP;
 
     CAToken_t tempToken = NULL;
     CAGenerateToken(&tempToken, CA_MAX_TOKEN_LEN);
@@ -650,7 +650,7 @@ TEST_F(CABlockTransferTests, CASetNextBlockOption2WithResponse)
 
     coap_pdu_t *pdu = NULL;
     coap_list_t *options = NULL;
-    coap_transport_type transport = coap_udp;
+    coap_transport_t transport = COAP_UDP;
 
     CAToken_t tempToken = NULL;
     CAGenerateToken(&tempToken, CA_MAX_TOKEN_LEN);
index 718c3d3..3e6b283 100644 (file)
@@ -77,7 +77,7 @@ void verifyParsedOptions(CoAPOptionCase const *cases,
 
 TEST(CAProtocolMessage, CAParseURIBase)
 {
-    char sampleURI[] = "coap://[::]/oic/res?rt=core.sensor;if=core.mi.ll";
+    char sampleURI[] = "coap://[::]/oic/res?rt=core.sensor&if=core.mi.ll";
     CoAPOptionCase cases[] = {
         {COAP_OPTION_URI_PATH, 3, "oic"},
         {COAP_OPTION_URI_PATH, 3, "res"},
@@ -99,8 +99,8 @@ TEST(CAProtocolMessage, CAParseURIBase)
 TEST(CAProtocolMessage, CAParseURIManyPath)
 {
     char sampleURI[] = "coap://[::]"
-        "/medium/a/b/c/d/e/f/g/h/i/j/"
-        "?rt=core.sensor;if=core.mi.ll";
+        "/medium/a/b/c/d/e/f/g/h/i/j"
+        "?rt=core.sensor&if=core.mi.ll";
 
     CoAPOptionCase cases[] = {
         {COAP_OPTION_URI_PATH, 6, "medium"},
@@ -131,8 +131,8 @@ TEST(CAProtocolMessage, CAParseURIManyPath)
 // Try for multiple URI parameters that still total less than 128
 TEST(CAProtocolMessage, CAParseURIManyParams)
 {
-    char sampleURI[] = "coap://[::]/oic/res/"
-        "?rt=core.sensor;a=0;b=1;c=2;d=3;e=4;f=5;g=6;h=7;i=8;j=9";
+    char sampleURI[] = "coap://[::]/oic/res"
+        "?rt=core.sensor&a=0&b=1&c=2&d=3&e=4&f=5&g=6&h=7&i=8&j=9";
 
     CoAPOptionCase cases[] = {
         {COAP_OPTION_URI_PATH, 3, "oic"},
@@ -166,7 +166,7 @@ TEST(CAProtocolMessage, CAParseURILongPath)
     char sampleURI[] = "coap://[::]/oic"
         "123456789012345678901234567890123456789012345678901234567890"
         "12345678901234567890123456789012345678901234567890"
-        "/res?rt=core.sensor;if=core.mi.ll";
+        "/res?rt=core.sensor&if=core.mi.ll";
 
     CoAPOptionCase cases[] = {
         {COAP_OPTION_URI_PATH, 113, "oic"
@@ -197,7 +197,7 @@ TEST(CAProtocolMessage, CAGetTokenFromPDU)
 
     coap_pdu_t *pdu = NULL;
     coap_list_t *options = NULL;
-    coap_transport_type transport = coap_udp;
+    coap_transport_t transport = COAP_UDP;
 
     CAInfo_t inData;
     memset(&inData, 0, sizeof(CAInfo_t));
@@ -211,5 +211,5 @@ TEST(CAProtocolMessage, CAGetTokenFromPDU)
     memset(&outData, 0, sizeof(CAInfo_t));
     outData.type = CA_MSG_NONCONFIRM;
 
-    EXPECT_EQ(CA_STATUS_OK, CAGetTokenFromPDU(pdu->hdr, &outData, &tempRep));
+    EXPECT_EQ(CA_STATUS_OK, CAGetTokenFromPDU(pdu->transport_hdr, &outData, &tempRep));
 }
index c701a2e..69eaa14 100644 (file)
@@ -18,6 +18,7 @@
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
+#include "iotivity_config.h"
 #include "gtest/gtest.h"
 
 #ifdef HAVE_PTHREAD_H
 #define _POSIX_C_SOURCE 200809L
 #endif // _POSIX_C_SOURCE
 
+#include "iotivity_config.h"
 #include "gtest/gtest.h"
 
-#include <camutex.h>
+#include "octhread.h"
 #include <cathreadpool.h>
 
 #ifdef HAVE_TIME_H
@@ -47,7 +48,6 @@
 #ifdef HAVE_UNISTD_H
 #include <unistd.h>
 #endif
-#include "platform_features.h"
 #ifdef HAVE_WINDOWS_H
 #include <windows.h>
 #endif
@@ -102,18 +102,18 @@ uint64_t getAbsTime()
 
 TEST(MutexTests, TC_01_CREATE)
 {
-    ca_mutex mymutex = ca_mutex_new();
+    oc_mutex mymutex = oc_mutex_new();
 
     EXPECT_TRUE(mymutex != NULL);
     if (mymutex != NULL)
     {
-        ca_mutex_free(mymutex);
+        oc_mutex_free(mymutex);
     }
 }
 
 typedef struct _tagFunc1
 {
-    ca_mutex mutex;
+    oc_mutex mutex;
     volatile bool thread_up;
     volatile bool finished;
 } _func1_struct;
@@ -127,7 +127,7 @@ void mutexFunc(void *context)
     // setting the flag must be done before lock attempt, as the test
     // thread starts off with the mutex locked
     pData->thread_up = true;
-    ca_mutex_lock(pData->mutex);
+    oc_mutex_lock(pData->mutex);
 
     DBG_printf("Thread: got lock\n");
     usleep(MINIMAL_LOOP_SLEEP * USECS_PER_MSEC);
@@ -135,7 +135,7 @@ void mutexFunc(void *context)
 
     pData->finished = true; // assignment guarded by lock
 
-    ca_mutex_unlock(pData->mutex);
+    oc_mutex_unlock(pData->mutex);
 }
 
 TEST(MutexTests, TC_03_THREAD_LOCKING)
@@ -146,13 +146,13 @@ TEST(MutexTests, TC_03_THREAD_LOCKING)
 
     _func1_struct pData = {0, false, false};
 
-    pData.mutex = ca_mutex_new();
+    pData.mutex = oc_mutex_new();
 
     EXPECT_TRUE(pData.mutex != NULL);
     if (pData.mutex != NULL)
     {
         DBG_printf("test: Holding mutex in test\n");
-        ca_mutex_lock(pData.mutex);
+        oc_mutex_lock(pData.mutex);
 
         DBG_printf("test: starting thread\n");
         //start thread
@@ -172,7 +172,7 @@ TEST(MutexTests, TC_03_THREAD_LOCKING)
 
         DBG_printf("test: unlocking\n");
 
-        ca_mutex_unlock(pData.mutex);
+        oc_mutex_unlock(pData.mutex);
 
         DBG_printf("test: waiting for thread to release\n");
         while (!pData.finished)
@@ -180,12 +180,12 @@ TEST(MutexTests, TC_03_THREAD_LOCKING)
             usleep(MINIMAL_LOOP_SLEEP * USECS_PER_MSEC);
         }
 
-        ca_mutex_lock(pData.mutex);
+        oc_mutex_lock(pData.mutex);
 
         // Cleanup Everything
 
-        ca_mutex_unlock(pData.mutex);
-        ca_mutex_free(pData.mutex);
+        oc_mutex_unlock(pData.mutex);
+        oc_mutex_free(pData.mutex);
     }
 
     ca_thread_pool_free(mythreadpool);
@@ -193,23 +193,23 @@ TEST(MutexTests, TC_03_THREAD_LOCKING)
 
 TEST(ConditionTests, TC_01_CREATE)
 {
-    ca_cond mycond = ca_cond_new();
+    oc_cond mycond = oc_cond_new();
 
     EXPECT_TRUE(mycond != NULL);
     if (mycond != NULL)
     {
-        ca_cond_free(mycond);
+        oc_cond_free(mycond);
     }
 }
 
 // Normally we would use one pair of mutex/cond-var communicating to the
 // worker threads and one pair back to the main thread. However since
-// testing the ca_cond itself is the point, only one pair is used here.
+// testing the oc_cond itself is the point, only one pair is used here.
 typedef struct _tagFunc2
 {
     int id;
-    ca_mutex mutex;
-    ca_cond condition;
+    oc_mutex mutex;
+    oc_cond condition;
     volatile bool thread_up;
     volatile bool finished;
 } _func2_struct;
@@ -220,15 +220,15 @@ void condFunc(void *context)
 
     DBG_printf("Thread_%d: waiting on condition\n", pData->id);
 
-    ca_mutex_lock(pData->mutex);
+    oc_mutex_lock(pData->mutex);
 
     pData->thread_up = true;
 
-    ca_cond_wait(pData->condition, pData->mutex);
+    oc_cond_wait(pData->condition, pData->mutex);
 
     pData->finished = true; // assignment guarded by lock
 
-    ca_mutex_unlock(pData->mutex);
+    oc_mutex_unlock(pData->mutex);
 
     DBG_printf("Thread_%d: completed.\n", pData->id);
 }
@@ -245,8 +245,8 @@ TEST(ConditionTests, TC_02_SIGNAL)
 
     EXPECT_EQ(CA_STATUS_OK, ca_thread_pool_init(3, &mythreadpool));
 
-    ca_mutex sharedMutex = ca_mutex_new();
-    ca_cond sharedCond = ca_cond_new();
+    oc_mutex sharedMutex = oc_mutex_new();
+    oc_cond sharedCond = oc_cond_new();
 
     _func2_struct pData1 =
     { 1, sharedMutex, sharedCond, false, false };
@@ -275,11 +275,11 @@ TEST(ConditionTests, TC_02_SIGNAL)
         // has already started waiting on the condition and the other is at
         // least close.
 
-        ca_mutex_lock(sharedMutex);
+        oc_mutex_lock(sharedMutex);
         // once the lock is acquired it means both threads were waiting.
         DBG_printf("test    : signaling first thread\n");
-        ca_cond_signal(sharedCond);
-        ca_mutex_unlock(sharedMutex);
+        oc_cond_signal(sharedCond);
+        oc_mutex_unlock(sharedMutex);
 
         // At this point either of the child threads might lock the mutex in
         // their cond_wait call, or this test thread might lock it again if
@@ -303,15 +303,15 @@ TEST(ConditionTests, TC_02_SIGNAL)
         usleep(MINIMAL_EXTRA_SLEEP);
 
         // only one should be finished
-        ca_mutex_lock(sharedMutex);
+        oc_mutex_lock(sharedMutex);
         EXPECT_NE(pData1.finished, pData2.finished);
-        ca_mutex_unlock(sharedMutex);
+        oc_mutex_unlock(sharedMutex);
 
         DBG_printf("test    : signaling another thread\n");
 
-        ca_mutex_lock(sharedMutex);
-        ca_cond_signal(sharedCond);
-        ca_mutex_unlock(sharedMutex);
+        oc_mutex_lock(sharedMutex);
+        oc_cond_signal(sharedCond);
+        oc_mutex_unlock(sharedMutex);
 
         waitCount = 0;
         while ((!pData1.finished || !pData2.finished)
@@ -327,10 +327,10 @@ TEST(ConditionTests, TC_02_SIGNAL)
 
         // Cleanup Everything
 
-        ca_mutex_free(pData1.mutex);
+        oc_mutex_free(pData1.mutex);
     }
 
-    ca_cond_free(pData1.condition);
+    oc_cond_free(pData1.condition);
 
     ca_thread_pool_free(mythreadpool);
 }
@@ -342,8 +342,8 @@ TEST(ConditionTests, TC_03_BROADCAST)
 
     EXPECT_EQ(CA_STATUS_OK, ca_thread_pool_init(3, &mythreadpool));
 
-    ca_mutex sharedMutex = ca_mutex_new();
-    ca_cond sharedCond = ca_cond_new();
+    oc_mutex sharedMutex = oc_mutex_new();
+    oc_cond sharedCond = oc_cond_new();
 
     _func2_struct pData1 =
     { 1, sharedMutex, sharedCond, false, false };
@@ -374,10 +374,10 @@ TEST(ConditionTests, TC_03_BROADCAST)
 
         DBG_printf("test    : signaling all threads\n");
 
-        ca_mutex_lock(sharedMutex);
+        oc_mutex_lock(sharedMutex);
         // once the lock is acquired it means both threads were waiting.
-        ca_cond_broadcast(sharedCond);
-        ca_mutex_unlock(sharedMutex);
+        oc_cond_broadcast(sharedCond);
+        oc_mutex_unlock(sharedMutex);
 
         int waitCount = 0;
         while ((!pData1.finished || !pData2.finished)
@@ -393,10 +393,10 @@ TEST(ConditionTests, TC_03_BROADCAST)
 
         // Cleanup Everything
 
-        ca_mutex_free(sharedMutex);
+        oc_mutex_free(sharedMutex);
     }
 
-    ca_cond_free(sharedCond);
+    oc_cond_free(sharedCond);
 
     ca_thread_pool_free(mythreadpool);
 }
@@ -423,14 +423,14 @@ void timedFunc(void *context)
 
     DBG_printf("Thread_%d: waiting for timeout \n", pData->id);
 
-    ca_mutex_lock(pData->mutex);
+    oc_mutex_lock(pData->mutex);
 
     uint64_t abs = USECS_PER_SEC / 2; // 1/2 seconds
 
     // test UTIMEDOUT
-    CAWaitResult_t ret = ca_cond_wait_for(pData->condition,
+    OCWaitResult_t ret = oc_cond_wait_for(pData->condition,
                                           pData->mutex, abs);
-    EXPECT_EQ(CA_WAIT_TIMEDOUT, ret);
+    EXPECT_EQ(OC_WAIT_TIMEDOUT, ret);
 
     pData->thread_up = true;
 
@@ -439,12 +439,12 @@ void timedFunc(void *context)
     abs = 5 * USECS_PER_SEC; // 5 seconds
 
     // test signal
-    ret = ca_cond_wait_for(pData->condition, pData->mutex, abs);
-    EXPECT_EQ(CA_WAIT_SUCCESS, ret);
+    ret = oc_cond_wait_for(pData->condition, pData->mutex, abs);
+    EXPECT_EQ(OC_WAIT_SUCCESS, ret);
 
     pData->finished = true; // assignment guarded by lock
 
-    ca_mutex_unlock(pData->mutex);
+    oc_mutex_unlock(pData->mutex);
 
     DBG_printf("Thread_%d: stopping\n", pData->id);
 }
@@ -456,8 +456,8 @@ TEST(ConditionTests, TC_05_WAIT)
 
     EXPECT_EQ(CA_STATUS_OK, ca_thread_pool_init(3, &mythreadpool));
 
-    ca_mutex sharedMutex = ca_mutex_new();
-    ca_cond sharedCond = ca_cond_new();
+    oc_mutex sharedMutex = oc_mutex_new();
+    oc_cond sharedCond = oc_cond_new();
 
     _func2_struct pData1 =
     { 1, sharedMutex, sharedCond, false, false };
@@ -482,9 +482,9 @@ TEST(ConditionTests, TC_05_WAIT)
 
         DBG_printf("test    : signaling first thread\n");
 
-        ca_mutex_lock(sharedMutex);
-        ca_cond_signal(sharedCond);
-        ca_mutex_unlock(sharedMutex);
+        oc_mutex_lock(sharedMutex);
+        oc_cond_signal(sharedCond);
+        oc_mutex_unlock(sharedMutex);
 
         int waitCount = 0;
         while (!pData1.finished
@@ -498,10 +498,10 @@ TEST(ConditionTests, TC_05_WAIT)
 
         // Cleanup Everything
 
-        ca_mutex_free(sharedMutex);
+        oc_mutex_free(sharedMutex);
     }
 
-    ca_cond_free(sharedCond);
+    oc_cond_free(sharedCond);
 
     ca_thread_pool_free(mythreadpool);
 }
@@ -510,43 +510,43 @@ TEST(ConditionTests, TC_05_WAIT)
 TEST(ConditionTests, DISABLED_TC_06_INVALIDWAIT)
 {
 
-    ca_mutex sharedMutex = ca_mutex_new();
-    ca_cond sharedCond = ca_cond_new();
+    oc_mutex sharedMutex = oc_mutex_new();
+    oc_cond sharedCond = oc_cond_new();
 
-    ca_mutex_lock(sharedMutex);
+    oc_mutex_lock(sharedMutex);
 
-    int ret = ca_cond_wait_for(NULL, sharedMutex, 5000);
-    EXPECT_EQ(CA_WAIT_INVAL,ret);
+    int ret = oc_cond_wait_for(NULL, sharedMutex, 5000);
+    EXPECT_EQ(OC_WAIT_INVAL,ret);
 
-    ret = ca_cond_wait_for(sharedCond, NULL, 5000);
-    EXPECT_EQ(CA_WAIT_INVAL,ret);
+    ret = oc_cond_wait_for(sharedCond, NULL, 5000);
+    EXPECT_EQ(OC_WAIT_INVAL,ret);
 
-    ret = ca_cond_wait_for(NULL, NULL, 5000);
-    EXPECT_EQ(CA_WAIT_INVAL,ret);
+    ret = oc_cond_wait_for(NULL, NULL, 5000);
+    EXPECT_EQ(OC_WAIT_INVAL,ret);
 
-    ca_mutex_unlock(sharedMutex);
+    oc_mutex_unlock(sharedMutex);
 
     // Cleanup Everything
 
-    ca_mutex_free(sharedMutex);
+    oc_mutex_free(sharedMutex);
 
-    ca_cond_free(sharedCond);
+    oc_cond_free(sharedCond);
 }
 
 TEST(ConditionTests, TC_07_WAITDURATION)
 {
     const double TARGET_WAIT = 1.125;
 
-    ca_mutex sharedMutex = ca_mutex_new();
-    ca_cond sharedCond = ca_cond_new();
+    oc_mutex sharedMutex = oc_mutex_new();
+    oc_cond sharedCond = oc_cond_new();
 
-    ca_mutex_lock(sharedMutex);
+    oc_mutex_lock(sharedMutex);
 
     uint64_t beg = getAbsTime();
 
-    CAWaitResult_t ret = ca_cond_wait_for(sharedCond, sharedMutex,
+    OCWaitResult_t ret = oc_cond_wait_for(sharedCond, sharedMutex,
                                           TARGET_WAIT * USECS_PER_SEC);
-    EXPECT_EQ(CA_WAIT_TIMEDOUT,ret);
+    EXPECT_EQ(OC_WAIT_TIMEDOUT,ret);
 
     uint64_t end = getAbsTime();
 
@@ -561,11 +561,11 @@ TEST(ConditionTests, TC_07_WAITDURATION)
     EXPECT_NEAR(TARGET_WAIT, secondsDiff, 0.05);
 #endif
 
-    ca_mutex_unlock(sharedMutex);
+    oc_mutex_unlock(sharedMutex);
 
     // Cleanup Everything
 
-    ca_mutex_free(sharedMutex);
+    oc_mutex_free(sharedMutex);
 
-    ca_cond_free(sharedCond);
+    oc_cond_free(sharedCond);
 }
index 03cd4e7..161022e 100644 (file)
@@ -26,7 +26,7 @@
 #include "caleautoconnector.h"
 #include "cacommonutil.h"
 #include "logger.h"
-#include "camutex.h"
+#include "octhread.h"
 
 #define TAG "OIC_CA_LE_AUTO_CONN"
 
@@ -34,50 +34,50 @@ static const size_t MAX_RETRY_COUNT = 5;
 static const size_t TIMEOUT = 1000000;
 static const size_t WAITING_TIME = 500000;
 
-static ca_mutex g_connectRetryMutex = NULL;
-static ca_cond g_connectRetryCond = NULL;
+static oc_mutex g_connectRetryMutex = NULL;
+static oc_cond g_connectRetryCond = NULL;
 
-static ca_mutex g_recoveryMutex = NULL;
-static ca_cond g_recoveryCond = NULL;
+static oc_mutex g_recoveryMutex = NULL;
+static oc_cond g_recoveryCond = NULL;
 
 CAResult_t CAManagerInitLEAutoConnection()
 {
     if (NULL == g_connectRetryMutex)
     {
-        g_connectRetryMutex = ca_mutex_new();
+        g_connectRetryMutex = oc_mutex_new();
         if (NULL == g_connectRetryMutex)
         {
-            OIC_LOG(ERROR, TAG, "ca_mutex_new has failed");
+            OIC_LOG(ERROR, TAG, "oc_mutex_new has failed");
             return CA_STATUS_FAILED;
         }
     }
 
     if (NULL == g_connectRetryCond)
     {
-        g_connectRetryCond = ca_cond_new();
+        g_connectRetryCond = oc_cond_new();
         if (NULL == g_connectRetryCond)
         {
-            OIC_LOG(ERROR, TAG, "ca_cond_new has failed");
+            OIC_LOG(ERROR, TAG, "oc_cond_new has failed");
             return CA_STATUS_FAILED;
         }
     }
 
     if (NULL == g_recoveryMutex)
     {
-        g_recoveryMutex = ca_mutex_new();
+        g_recoveryMutex = oc_mutex_new();
         if (NULL == g_recoveryMutex)
         {
-            OIC_LOG(ERROR, TAG, "ca_mutex_new has failed");
+            OIC_LOG(ERROR, TAG, "oc_mutex_new has failed");
             return CA_STATUS_FAILED;
         }
     }
 
     if (NULL == g_recoveryCond)
     {
-        g_recoveryCond = ca_cond_new();
+        g_recoveryCond = oc_cond_new();
         if (NULL == g_recoveryCond)
         {
-            OIC_LOG(ERROR, TAG, "ca_cond_new has failed");
+            OIC_LOG(ERROR, TAG, "oc_cond_new has failed");
             return CA_STATUS_FAILED;
         }
     }
@@ -89,27 +89,27 @@ void CAManagerTerminateLEAutoConnection()
 {
     if (g_connectRetryCond)
     {
-        ca_cond_signal(g_connectRetryCond);
-        ca_cond_free(g_connectRetryCond);
+        oc_cond_signal(g_connectRetryCond);
+        oc_cond_free(g_connectRetryCond);
         g_connectRetryCond = NULL;
     }
 
     if (g_connectRetryMutex)
     {
-        ca_mutex_free(g_connectRetryMutex);
+        oc_mutex_free(g_connectRetryMutex);
         g_connectRetryMutex = NULL;
     }
 
     if (g_recoveryCond)
     {
-        ca_cond_signal(g_recoveryCond);
-        ca_cond_free(g_recoveryCond);
+        oc_cond_signal(g_recoveryCond);
+        oc_cond_free(g_recoveryCond);
         g_recoveryCond = NULL;
     }
 
     if (g_recoveryMutex)
     {
-        ca_mutex_free(g_recoveryMutex);
+        oc_mutex_free(g_recoveryMutex);
         g_recoveryMutex = NULL;
     }
 }
@@ -120,20 +120,20 @@ CAResult_t CAManagerStartAutoConnection(JNIEnv *env, jstring remote_le_address)
     VERIFY_NON_NULL(remote_le_address, TAG, "remote_le_address is null");
 
     OIC_LOG(DEBUG, TAG, "IN - CAManagerStartAutoConnection");
-    ca_mutex_lock(g_connectRetryMutex);
+    oc_mutex_lock(g_connectRetryMutex);
 
     bool isAutoConnecting = false;
     if (CA_STATUS_OK != CAManagerGetAutoConnectingFlag(env, remote_le_address, &isAutoConnecting))
     {
         OIC_LOG(DEBUG, TAG, "CAManagerIsAutoConnecting has failed");
-        ca_mutex_unlock(g_connectRetryMutex);
+        oc_mutex_unlock(g_connectRetryMutex);
         return CA_STATUS_FAILED;
     }
 
     if (isAutoConnecting)
     {
         OIC_LOG(INFO, TAG, "connection has been already in progress or completed");
-        ca_mutex_unlock(g_connectRetryMutex);
+        oc_mutex_unlock(g_connectRetryMutex);
         return CA_STATUS_FAILED;
     }
 
@@ -147,9 +147,9 @@ CAResult_t CAManagerStartAutoConnection(JNIEnv *env, jstring remote_le_address)
         {
             OIC_LOG_V(INFO, TAG, "retry will be started at least %d times after delay 1sec",
                       MAX_RETRY_COUNT - retry_cnt - 1);
-            if (ca_cond_wait_for(g_connectRetryCond, g_connectRetryMutex, TIMEOUT) == 0)
+            if (oc_cond_wait_for(g_connectRetryCond, g_connectRetryMutex, TIMEOUT) == 0)
             {
-                ca_mutex_unlock(g_connectRetryMutex);
+                oc_mutex_unlock(g_connectRetryMutex);
                 OIC_LOG(INFO, TAG, "request to connect gatt was canceled");
                 return CA_STATUS_OK;
             }
@@ -161,7 +161,7 @@ CAResult_t CAManagerStartAutoConnection(JNIEnv *env, jstring remote_le_address)
             break;
         }
     }
-    ca_mutex_unlock(g_connectRetryMutex);
+    oc_mutex_unlock(g_connectRetryMutex);
     OIC_LOG(DEBUG, TAG, "OUT - CAManagerStartAutoConnection");
     return res;
 }
@@ -206,14 +206,14 @@ CAResult_t CAManagerProcessRecovery(JNIEnv *env, uint16_t adapter_state)
     VERIFY_NON_NULL(env, TAG, "env");
     OIC_LOG(DEBUG, TAG, "IN - CAManagerProcessRecovery");
 
-    ca_mutex_lock(g_recoveryMutex);
+    oc_mutex_lock(g_recoveryMutex);
     CAResult_t res = CA_STATUS_OK;
 
     switch(adapter_state)
     {
         case STATE_OFF:
             // adapter will be enabled automatically after WAITING_TIME.
-            if (ca_cond_wait_for(g_recoveryCond, g_recoveryMutex, WAITING_TIME) == 0)
+            if (oc_cond_wait_for(g_recoveryCond, g_recoveryMutex, WAITING_TIME) == 0)
             {
                 OIC_LOG(INFO, TAG, "BT recovery was canceled");
             }
@@ -240,7 +240,7 @@ CAResult_t CAManagerProcessRecovery(JNIEnv *env, uint16_t adapter_state)
             break;
     }
 
-    ca_mutex_unlock(g_recoveryMutex);
+    oc_mutex_unlock(g_recoveryMutex);
     OIC_LOG(DEBUG, TAG, "OUT - CAManagerProcessRecovery");
 
     return res;
index 7a431e8..cbdde51 100644 (file)
 #include "cacommonutil.h"
 #include "camanagerleutil.h"
 #include "uarraylist.h"
-#include "camutex.h"
+#include "octhread.h"
 #include "camanagerdevice.h"
 #include "oic_malloc.h"
 
 #define TAG "OIC_CA_MANAGER_DEVICE"
 
 static u_arraylist_t *g_deviceACDataList = NULL;
-static ca_mutex g_deviceACDataListMutex = NULL;
+static oc_mutex g_deviceACDataListMutex = NULL;
 static bool g_isBTRecovery = false;
 
 jstring CAManagerGetLEAddressFromACData(JNIEnv *env, size_t idx)
@@ -66,13 +66,13 @@ void CAManagerCreateACDataList()
 {
     OIC_LOG(DEBUG, TAG, "CAManagerCreateACDataList");
 
-    ca_mutex_lock(g_deviceACDataListMutex);
+    oc_mutex_lock(g_deviceACDataListMutex);
     if (NULL == g_deviceACDataList)
     {
         OIC_LOG(DEBUG, TAG, "Create AC Data list");
         g_deviceACDataList = u_arraylist_create();
     }
-    ca_mutex_unlock(g_deviceACDataListMutex);
+    oc_mutex_unlock(g_deviceACDataListMutex);
 }
 
 void CAManagerDestroyACDataList()
@@ -90,10 +90,10 @@ CAResult_t CAManagerInitMutexVaraibles()
 {
     if (NULL == g_deviceACDataListMutex)
     {
-        g_deviceACDataListMutex = ca_mutex_new();
+        g_deviceACDataListMutex = oc_mutex_new();
         if (NULL == g_deviceACDataListMutex)
         {
-            OIC_LOG(ERROR, TAG, "ca_mutex_new has failed");
+            OIC_LOG(ERROR, TAG, "oc_mutex_new has failed");
             return CA_STATUS_FAILED;
         }
     }
@@ -104,7 +104,7 @@ void CAManagerTerminateMutexVariables()
 {
     if (g_deviceACDataListMutex)
     {
-        ca_mutex_free(g_deviceACDataListMutex);
+        oc_mutex_free(g_deviceACDataListMutex);
         g_deviceACDataListMutex = NULL;
     }
 }
@@ -134,13 +134,13 @@ bool CAManagerIsInACDataList(JNIEnv *env, jstring jaddress)
     VERIFY_NON_NULL_RET(env, TAG, "env", NULL);
     VERIFY_NON_NULL_RET(jaddress, TAG, "jaddress", false);
 
-    ca_mutex_lock(g_deviceACDataListMutex);
+    oc_mutex_lock(g_deviceACDataListMutex);
 
     const char* address = (*env)->GetStringUTFChars(env, jaddress, NULL);
     if (!address)
     {
         OIC_LOG(ERROR, TAG, "address is null");
-        ca_mutex_unlock(g_deviceACDataListMutex);
+        oc_mutex_unlock(g_deviceACDataListMutex);
         return false;
     }
 
@@ -153,7 +153,7 @@ bool CAManagerIsInACDataList(JNIEnv *env, jstring jaddress)
         {
             OIC_LOG(ERROR, TAG, "curData is null");
             (*env)->ReleaseStringUTFChars(env, jaddress, address);
-            ca_mutex_unlock(g_deviceACDataListMutex);
+            oc_mutex_unlock(g_deviceACDataListMutex);
             return false;
         }
 
@@ -162,7 +162,7 @@ bool CAManagerIsInACDataList(JNIEnv *env, jstring jaddress)
         {
             OIC_LOG(ERROR, TAG, "address is null");
             (*env)->ReleaseStringUTFChars(env, jaddress, address);
-            ca_mutex_unlock(g_deviceACDataListMutex);
+            oc_mutex_unlock(g_deviceACDataListMutex);
             return false;
         }
 
@@ -170,7 +170,7 @@ bool CAManagerIsInACDataList(JNIEnv *env, jstring jaddress)
         {
             (*env)->ReleaseStringUTFChars(env, curData->address, setAddress);
             (*env)->ReleaseStringUTFChars(env, jaddress, address);
-            ca_mutex_unlock(g_deviceACDataListMutex);
+            oc_mutex_unlock(g_deviceACDataListMutex);
             return true;
         }
         (*env)->ReleaseStringUTFChars(env, curData->address, setAddress);
@@ -178,7 +178,7 @@ bool CAManagerIsInACDataList(JNIEnv *env, jstring jaddress)
 
     OIC_LOG_V(DEBUG, TAG, "[%s] doesn't exist in list", address);
     (*env)->ReleaseStringUTFChars(env, jaddress, address);
-    ca_mutex_unlock(g_deviceACDataListMutex);
+    oc_mutex_unlock(g_deviceACDataListMutex);
 
     return false;
 }
@@ -198,9 +198,9 @@ void CAManagerAddACData(JNIEnv *env, jstring jaddress)
 
         CAManagerACData_t *data = CAManagerCreateACData(gaddress);
 
-        ca_mutex_lock(g_deviceACDataListMutex);
+        oc_mutex_lock(g_deviceACDataListMutex);
         u_arraylist_add(g_deviceACDataList, data);
-        ca_mutex_unlock(g_deviceACDataListMutex);
+        oc_mutex_unlock(g_deviceACDataListMutex);
     }
     else
     {
@@ -216,13 +216,13 @@ CAResult_t CAManagerRemoveACData(JNIEnv *env, jstring jaddress)
     VERIFY_NON_NULL(env, TAG, "env");
     VERIFY_NON_NULL(jaddress, TAG, "jaddress");
 
-    ca_mutex_lock(g_deviceACDataListMutex);
+    oc_mutex_lock(g_deviceACDataListMutex);
 
     const char* address = (*env)->GetStringUTFChars(env, jaddress, NULL);
     if (!address)
     {
         OIC_LOG(ERROR, TAG, "address is null");
-        ca_mutex_unlock(g_deviceACDataListMutex);
+        oc_mutex_unlock(g_deviceACDataListMutex);
         return CA_STATUS_FAILED;
     }
 
@@ -237,7 +237,7 @@ CAResult_t CAManagerRemoveACData(JNIEnv *env, jstring jaddress)
         {
             OIC_LOG(ERROR, TAG, "curData is null");
             (*env)->ReleaseStringUTFChars(env, jaddress, address);
-            ca_mutex_unlock(g_deviceACDataListMutex);
+            oc_mutex_unlock(g_deviceACDataListMutex);
             return CA_STATUS_FAILED;
         }
 
@@ -246,7 +246,7 @@ CAResult_t CAManagerRemoveACData(JNIEnv *env, jstring jaddress)
         {
             OIC_LOG(ERROR, TAG, "address is null");
             (*env)->ReleaseStringUTFChars(env, jaddress, address);
-            ca_mutex_unlock(g_deviceACDataListMutex);
+            oc_mutex_unlock(g_deviceACDataListMutex);
             return CA_STATUS_FAILED;
         }
 
@@ -257,7 +257,7 @@ CAResult_t CAManagerRemoveACData(JNIEnv *env, jstring jaddress)
                 OIC_LOG(ERROR, TAG, "removal has failed.");
                 (*env)->ReleaseStringUTFChars(env, jaddress, address);
                 (*env)->ReleaseStringUTFChars(env, curData->address, setAddress);
-                ca_mutex_unlock(g_deviceACDataListMutex);
+                oc_mutex_unlock(g_deviceACDataListMutex);
                 return CA_STATUS_FAILED;
             }
 
@@ -270,7 +270,7 @@ CAResult_t CAManagerRemoveACData(JNIEnv *env, jstring jaddress)
 
             OICFree(curData);
             (*env)->ReleaseStringUTFChars(env, jaddress, address);
-            ca_mutex_unlock(g_deviceACDataListMutex);
+            oc_mutex_unlock(g_deviceACDataListMutex);
             OIC_LOG(DEBUG, TAG, "remove done");
             return CA_STATUS_OK;
         }
@@ -279,7 +279,7 @@ CAResult_t CAManagerRemoveACData(JNIEnv *env, jstring jaddress)
 
     OIC_LOG_V(DEBUG, TAG, "[%s] doesn't exist in list", address);
     (*env)->ReleaseStringUTFChars(env, jaddress, address);
-    ca_mutex_unlock(g_deviceACDataListMutex);
+    oc_mutex_unlock(g_deviceACDataListMutex);
 
     return CA_STATUS_OK;
 }
@@ -289,7 +289,7 @@ CAResult_t CAManagerRemoveAllACData(JNIEnv *env)
     OIC_LOG(DEBUG, TAG, "IN - CAManagerRemoveAllACData");
     VERIFY_NON_NULL(env, TAG, "env");
 
-    ca_mutex_lock(g_deviceACDataListMutex);
+    oc_mutex_lock(g_deviceACDataListMutex);
 
     size_t length = u_arraylist_length(g_deviceACDataList);
     for (size_t idx = 0; idx < length; idx++)
@@ -299,14 +299,14 @@ CAResult_t CAManagerRemoveAllACData(JNIEnv *env)
         if (!curData)
         {
             OIC_LOG(ERROR, TAG, "curData is null");
-            ca_mutex_unlock(g_deviceACDataListMutex);
+            oc_mutex_unlock(g_deviceACDataListMutex);
             return CA_STATUS_FAILED;
         }
 
         if (NULL == u_arraylist_remove(g_deviceACDataList, idx))
         {
             OIC_LOG(ERROR, TAG, "removal has failed.");
-            ca_mutex_unlock(g_deviceACDataListMutex);
+            oc_mutex_unlock(g_deviceACDataListMutex);
             return CA_STATUS_FAILED;
         }
 
@@ -317,7 +317,7 @@ CAResult_t CAManagerRemoveAllACData(JNIEnv *env)
 
         OICFree(curData);
     }
-    ca_mutex_unlock(g_deviceACDataListMutex);
+    oc_mutex_unlock(g_deviceACDataListMutex);
     OIC_LOG(DEBUG, TAG, "OUT - CAManagerRemoveAllACData");
     return CA_STATUS_OK;
 }
@@ -328,13 +328,13 @@ CAResult_t CAManagerGetAutoConnectingFlag(JNIEnv *env, jstring jaddress, bool *f
     VERIFY_NON_NULL(env, TAG, "env");
     VERIFY_NON_NULL(jaddress, TAG, "jaddress");
 
-    ca_mutex_lock(g_deviceACDataListMutex);
+    oc_mutex_lock(g_deviceACDataListMutex);
 
     const char* address = (*env)->GetStringUTFChars(env, jaddress, NULL);
     if (!address)
     {
         OIC_LOG(ERROR, TAG, "address is null");
-        ca_mutex_unlock(g_deviceACDataListMutex);
+        oc_mutex_unlock(g_deviceACDataListMutex);
         return CA_STATUS_FAILED;
     }
 
@@ -347,7 +347,7 @@ CAResult_t CAManagerGetAutoConnectingFlag(JNIEnv *env, jstring jaddress, bool *f
         {
             OIC_LOG(ERROR, TAG, "curData is null");
             (*env)->ReleaseStringUTFChars(env, jaddress, address);
-            ca_mutex_unlock(g_deviceACDataListMutex);
+            oc_mutex_unlock(g_deviceACDataListMutex);
             return CA_STATUS_FAILED;
         }
 
@@ -356,7 +356,7 @@ CAResult_t CAManagerGetAutoConnectingFlag(JNIEnv *env, jstring jaddress, bool *f
         {
             OIC_LOG(ERROR, TAG, "setAddress is null");
             (*env)->ReleaseStringUTFChars(env, jaddress, address);
-            ca_mutex_unlock(g_deviceACDataListMutex);
+            oc_mutex_unlock(g_deviceACDataListMutex);
             return CA_STATUS_FAILED;
         }
 
@@ -367,7 +367,7 @@ CAResult_t CAManagerGetAutoConnectingFlag(JNIEnv *env, jstring jaddress, bool *f
             *flag = curData->isAutoConnecting;
             (*env)->ReleaseStringUTFChars(env, curData->address, setAddress);
             (*env)->ReleaseStringUTFChars(env, jaddress, address);
-            ca_mutex_unlock(g_deviceACDataListMutex);
+            oc_mutex_unlock(g_deviceACDataListMutex);
             return CA_STATUS_OK;
         }
         (*env)->ReleaseStringUTFChars(env, curData->address, setAddress);
@@ -375,7 +375,7 @@ CAResult_t CAManagerGetAutoConnectingFlag(JNIEnv *env, jstring jaddress, bool *f
 
     OIC_LOG_V(DEBUG, TAG, "[%s] doesn't exist in list", address);
     (*env)->ReleaseStringUTFChars(env, jaddress, address);
-    ca_mutex_unlock(g_deviceACDataListMutex);
+    oc_mutex_unlock(g_deviceACDataListMutex);
 
     return CA_STATUS_FAILED;
 }
@@ -386,13 +386,13 @@ bool CAManagerSetAutoConnectingFlag(JNIEnv *env, jstring jaddress, bool flag)
     VERIFY_NON_NULL_RET(env, TAG, "env", false);
     VERIFY_NON_NULL_RET(jaddress, TAG, "jaddress", false);
 
-    ca_mutex_lock(g_deviceACDataListMutex);
+    oc_mutex_lock(g_deviceACDataListMutex);
 
     const char* address = (*env)->GetStringUTFChars(env, jaddress, NULL);
     if (!address)
     {
         OIC_LOG(ERROR, TAG, "address is null");
-        ca_mutex_unlock(g_deviceACDataListMutex);
+        oc_mutex_unlock(g_deviceACDataListMutex);
         return false;
     }
 
@@ -405,7 +405,7 @@ bool CAManagerSetAutoConnectingFlag(JNIEnv *env, jstring jaddress, bool flag)
         {
             OIC_LOG(ERROR, TAG, "curData is null");
             (*env)->ReleaseStringUTFChars(env, jaddress, address);
-            ca_mutex_unlock(g_deviceACDataListMutex);
+            oc_mutex_unlock(g_deviceACDataListMutex);
             return false;
         }
 
@@ -414,7 +414,7 @@ bool CAManagerSetAutoConnectingFlag(JNIEnv *env, jstring jaddress, bool flag)
         {
             OIC_LOG(ERROR, TAG, "address is null");
             (*env)->ReleaseStringUTFChars(env, jaddress, address);
-            ca_mutex_unlock(g_deviceACDataListMutex);
+            oc_mutex_unlock(g_deviceACDataListMutex);
             return false;
         }
 
@@ -425,7 +425,7 @@ bool CAManagerSetAutoConnectingFlag(JNIEnv *env, jstring jaddress, bool flag)
             curData->isAutoConnecting = flag;
             (*env)->ReleaseStringUTFChars(env, curData->address, setAddress);
             (*env)->ReleaseStringUTFChars(env, jaddress, address);
-            ca_mutex_unlock(g_deviceACDataListMutex);
+            oc_mutex_unlock(g_deviceACDataListMutex);
             return true;
         }
         (*env)->ReleaseStringUTFChars(env, curData->address, setAddress);
@@ -433,7 +433,7 @@ bool CAManagerSetAutoConnectingFlag(JNIEnv *env, jstring jaddress, bool flag)
 
     OIC_LOG_V(DEBUG, TAG, "[%s] doesn't exist in list", address);
     (*env)->ReleaseStringUTFChars(env, jaddress, address);
-    ca_mutex_unlock(g_deviceACDataListMutex);
+    oc_mutex_unlock(g_deviceACDataListMutex);
 
     return false;
 }
index 0b42ead..4304d23 100644 (file)
@@ -21,7 +21,7 @@
 #ifndef LOGGER_H_
 #define LOGGER_H_
 
-#define IOTIVITY_VERSION "1.1.1"
+#define IOTIVITY_VERSION "1.2.0"
 
 #include <stdint.h>
 #include <stdio.h>
@@ -42,6 +42,11 @@ extern "C"
 {
 #endif
 
+/**
+* Helper for unused warning.
+*/
+#define UNUSED(x) (void)(x)
+
 // Use the PCF macro to wrap strings stored in FLASH on the Arduino
 // Example:  OIC_LOG(INFO, TAG, PCF("Entering function"));
 #ifdef ARDUINO
index cc7f303..edeb167 100644 (file)
@@ -30,6 +30,8 @@
 #define _POSIX_C_SOURCE 200809L
 #endif
 
+#include "iotivity_config.h"
+
 // Pull in _POSIX_TIMERS feature test macro to check for
 // clock_gettime() support.
 #ifdef HAVE_UNISTD_H
@@ -52,7 +54,6 @@
 #include "logger.h"
 #include "string.h"
 #include "logger_types.h"
-#include "platform_features.h"
 
 #ifndef __TIZEN__
 static oc_log_ctx_t *logCtx = 0;
index 47b95d9..1c81e28 100644 (file)
@@ -28,14 +28,6 @@ cJSON_GetArrayItem
 calcDimTotal
 ConvertStrToUuid
 convertTriggerEnumToString
-CreateJustWorksOwnerTransferPayload
-CreateJustWorksSelectOxmPayload
-CreatePinBasedSelectOxmPayload
-CreatePinBasedOwnerTransferPayload
-CreateSecureSessionJustWorksCallback
-CreateSecureSessionRandomPinCallback
-InputPinCodeCallback
-LoadSecretJustWorksCallback
 
 OCBindResource
 OCBindResourceHandler
@@ -45,24 +37,16 @@ OCBindResourceTypeToResource
 OCCancel
 OCCreateOCStringLL
 OCCreateResource
-OCDeleteACLList
-OCDeleteDiscoveredDevices
-OCDeletePdAclList
 OCDeleteResource
-OCDeleteUuidList
 OCDiscoverDirectPairingDevices
-OCDiscoverUnownedDevices
-OCDiscoverOwnedDevices
+OCDiscoveryPayloadCreate
+OCDiscoveryPayloadDestroy
+OCDiscoveryPayloadGetResourceCount
 OCDoDirectPairing
-OCDoOwnershipTransfer
 OCDoResource
 OCDoResponse
 OCFreeOCStringLL
-OCGetACLResource
-OCGetCredResource
-OCGetDevInfoFromNetwork
 OCGetDirectPairedDevices
-OCGetLinkedStatus
 OCGetNumberOfResources
 OCGetNumberOfResourceInterfaces
 OCGetNumberOfResourceTypes
@@ -77,22 +61,17 @@ OCGetResourceUri
 OCGetServerInstanceIDString
 OCInit
 OCInit1
-OCInitPM
 OCNotifyAllObservers
 OCNotifyListOfObservers
 OCPayloadDestroy
+OCPlatformPayloadCreate
+OCPresencePayloadCreate
 OCProcess
-OCProvisionACL
-OCProvisionCredentials
-OCProvisionDirectPairing
-OCProvisionPairwiseDevices
 OCRDDelete
 OCRDDeleteWithDeviceId
 OCRDPublish
 OCRDPublishWithDeviceId
 OCRegisterPersistentStorageHandler
-OCRemoveDevice
-OCRemoveDeviceWithUuid
 OCRepPayloadAddInterface
 OCRepPayloadAddResourceType
 OCRepPayloadAppend
@@ -100,6 +79,7 @@ OCRepPayloadClone
 OCRepPayloadCreate
 OCRepPayloadDestroy
 OCRepPayloadGetByteStringArray
+OCRepPayloadSetByteStringArrayAsOwner
 OCRepPayloadGetPropBool
 OCRepPayloadGetPropByteString
 OCRepPayloadGetPropInt
@@ -117,18 +97,12 @@ OCRepPayloadSetPropObjectAsOwner
 OCRepPayloadSetPropString
 OCRepPayloadSetStringArrayAsOwner
 OCRepPayloadSetUri
-OCResetDevice
 OCResourcePayloadAddStringLL
 OCSecurityPayloadCreate
 OCSetDefaultDeviceEntityHandler
 OCSetDeviceInfo
-OCSetOwnerTransferCallbackData
 OCSetPlatformInfo
 OCStartPresence
 OCStop
 OCStopPresence
 OCUnBindResource
-OCUnlinkDevices
-
-SetGeneratePinCB
-SetInputPinCB
diff --git a/resource/csdk/octbstack_product_secured.def b/resource/csdk/octbstack_product_secured.def
new file mode 100644 (file)
index 0000000..2960f4f
--- /dev/null
@@ -0,0 +1,36 @@
+; Windows octbstack.dll exports that are required for both products and tests,
+; but only when building with SECURED=1.
+
+CreateJustWorksOwnerTransferPayload
+CreateJustWorksSelectOxmPayload
+CreatePinBasedSelectOxmPayload
+CreatePinBasedOwnerTransferPayload
+CreateSecureSessionJustWorksCallback
+CreateSecureSessionRandomPinCallback
+InputPinCodeCallback
+LoadSecretJustWorksCallback
+
+OCDeleteACLList
+OCDeleteDiscoveredDevices
+OCDeletePdAclList
+OCDeleteUuidList
+OCDiscoverOwnedDevices
+OCDiscoverUnownedDevices
+OCDoOwnershipTransfer
+OCGetACLResource
+OCGetCredResource
+OCGetDevInfoFromNetwork
+OCGetLinkedStatus
+OCInitPM
+OCProvisionACL
+OCProvisionCredentials
+OCProvisionDirectPairing
+OCProvisionPairwiseDevices
+OCRemoveDevice
+OCRemoveDeviceWithUuid
+OCResetDevice
+OCSetOwnerTransferCallbackData
+OCUnlinkDevices
+
+SetGeneratePinCB
+SetInputPinCB
index 2292fda..eb465e1 100644 (file)
@@ -46,7 +46,7 @@
 /**
  * Unique gateway ID generated before hosting a gateway resource.
  */
-uint32_t g_GatewayID = 0;
+static uint32_t g_GatewayID = 0;
 
 /**
  * Used for assigning unique ID.to endpoint's connected to this gateway
index 4952d83..f878587 100644 (file)
@@ -29,16 +29,24 @@ SConscript('#resource/third_party_libs.scons', 'lib_env')
 
 libocsrm_env = lib_env.Clone()
 
-target_os = env.get('TARGET_OS')
+target_os = libocsrm_env.get('TARGET_OS')
 # As in the source code, it includes arduino Time library (C++)
 # It requires compile the .c with g++
 if target_os == 'arduino':
-       libocsrm_env.Replace(CC = env.get('CXX'))
-       libocsrm_env.Replace(CFLAGS = env.get('CXXFLAGS'))
+       libocsrm_env.Replace(CC = libocsrm_env.get('CXX'))
+       libocsrm_env.Replace(CFLAGS = libocsrm_env.get('CXXFLAGS'))
 
 ######################################################################
 # Build flags
 ######################################################################
+with_upstream_libcoap = libocsrm_env.get('WITH_UPSTREAM_LIBCOAP')
+if with_upstream_libcoap == '1':
+       # For bring up purposes only, we manually copy the forked version to where the unforked version is downloaded.
+       libocsrm_env.AppendUnique(CPPPATH = ['#extlibs/libcoap/libcoap/include'])
+else:
+       # For bring up purposes only, the forked version will live here.
+       libocsrm_env.AppendUnique(CPPPATH = ['../connectivity/lib/libcoap-4.1.1/include'])
+
 libocsrm_env.PrependUnique(CPPPATH = [
                '../../../extlibs/cjson/',
                '../../../extlibs/tinydtls/',
@@ -47,7 +55,6 @@ libocsrm_env.PrependUnique(CPPPATH = [
                '../stack/include',
                '../stack/include/internal',
                '../../oc_logger/include',
-               '../connectivity/lib/libcoap-4.1.1',
                '../connectivity/external/inc',
                '../connectivity/common/inc',
                '../connectivity/inc/pkix',
@@ -59,10 +66,10 @@ libocsrm_env.PrependUnique(CPPPATH = [
                ])
 
 if target_os not in ['arduino', 'windows']:
-       libocsrm_env.AppendUnique(CPPDEFINES  = ['WITH_POSIX'])
+       libocsrm_env.AppendUnique(CPPDEFINES  = ['WITH_POSIX', '_GNU_SOURCE'])
        libocsrm_env.AppendUnique(CFLAGS = ['-std=c99', '-Wall'])
 
-libocsrm_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
+libocsrm_env.AppendUnique(LIBPATH = [libocsrm_env.get('BUILD_DIR')])
 libocsrm_env.AppendUnique(LIBS = ['coap'])
 
 if target_os == 'arduino':
@@ -72,11 +79,11 @@ elif target_os not in ['windows', 'msys_nt']:
        libocsrm_env.AppendUnique(LIBS = ['m'])
 
 if target_os in ['windows', 'msys_nt']:
-       libocsrm_env.AppendUnique(LIBPATH = [os.path.join(env.get('BUILD_DIR'), 'resource', 'oc_logger')])
+       libocsrm_env.AppendUnique(LIBPATH = [os.path.join(libocsrm_env.get('BUILD_DIR'), 'resource', 'oc_logger')])
 
 if target_os in ['darwin', 'ios']:
        libocsrm_env.AppendUnique(CPPDEFINES = ['_DARWIN_C_SOURCE'])
-       libocsrm_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
+       libocsrm_env.AppendUnique(LIBPATH = [libocsrm_env.get('BUILD_DIR')])
        libocsrm_env.AppendUnique(LIBS = ['coap'])
 
 if env.get('LOGGING'):
@@ -111,15 +118,14 @@ libocsrm_src = [
        OCSRM_SRC + 'directpairing.c'
        ]
 
-if env.get('SECURED') == '1':
-       libocsrm_src  = libocsrm_src + [OCSRM_SRC + 'oxmpincommon.c', OCSRM_SRC + 'pbkdf2.c']
+if libocsrm_env.get('SECURED') == '1':
+       libocsrm_src = libocsrm_src + [OCSRM_SRC + 'oxmpincommon.c', OCSRM_SRC + 'pbkdf2.c']
 
 if target_os in ['windows', 'msys_nt']:
        libocsrm_src  = libocsrm_src + [OCSRM_SRC + 'strptime.c']
 
 if (env.get('DTLS_WITH_X509') == '1' or env.get('WITH_TCP') == True) and env.get('SECURED') == '1':
-       crl_src = [OCSRM_SRC + 'crlresource.c']
-       libocsrm_src  = libocsrm_src + crl_src
+       libocsrm_src  = libocsrm_src + [OCSRM_SRC + 'crlresource.c', OCSRM_SRC + 'pkix_interface.c']
 
 libocsrm_conf = Configure(libocsrm_env)
 if libocsrm_conf.CheckFunc('strptime'):
@@ -130,8 +136,8 @@ libocsrm = libocsrm_env.StaticLibrary('ocsrm', libocsrm_src)
 
 libocsrm_env.InstallTarget(libocsrm, 'ocsrm')
 
-if target_os in ['linux', 'android', 'tizen', 'msys_nt', 'windows'] and env.get('SECURED') == '1':
+if target_os in ['linux', 'android', 'tizen', 'msys_nt', 'windows'] and libocsrm_env.get('SECURED') == '1':
        SConscript('provisioning/SConscript')
 
-if target_os in ['linux'] and env.get('SECURED') == '1':
+if target_os in ['linux'] and libocsrm_env.get('SECURED') == '1':
        SConscript('tool/SConscript')
index 7daf51f..3596377 100644 (file)
@@ -101,6 +101,14 @@ OicSecAce_t* DuplicateACE(const OicSecAce_t* ace);
 OCStackResult InstallNewACL(const uint8_t* payload, const size_t size);
 
 /**
+ * This function installs a new ACL.
+ *
+ * @param acl  new acl to install.
+ *
+ * @return ::OC_STACK_OK for Success, otherwise some error value
+ */
+OCStackResult InstallNewACL2(const OicSecAcl_t* acl);
+/**
  * This function updates default ACE which is required for ownership transfer.
  * This function should be invoked after OTM is complete to prevent anonymous user access.
  *
@@ -126,6 +134,16 @@ OCStackResult SetAclRownerId(const OicUuid_t* newROwner);
  */
 OCStackResult GetAclRownerId(OicUuid_t *rowneruuid);
 
+/**
+ * This function converts CBOR data into ACL.
+ *
+ * @param cborPayload is the pointer to cbor payload to parse.
+ * @param size of the cbor payload.
+ *
+ * @return ::acl instance of @ref OicSecAcl_t structure or NULL if error occurs
+ */
+OicSecAcl_t* CBORPayloadToAcl2(const uint8_t *cborPayload, const size_t size);
+
 #ifdef __cplusplus
 }
 #endif
index d3161ad..beab0c4 100644 (file)
@@ -190,12 +190,30 @@ OCStackResult GetCredRownerId(OicUuid_t *rowneruuid);
 
 #ifdef __WITH_TLS__
 /**
- * @def CA_SUBJECT_ID
- * @brief subject uuid for credential with CA certificates
+ * Used by mbedTLS to retrieve trusted CA certificates
+ *
+ * @param[out] crt certificates to be filled.
  */
-#define CA_SUBJECT_ID ("00000000-0000-0000-0000-000000000000")
-void GetPkixInfo(PkiInfo_t * inf);
-#endif
+void GetDerCaCert(ByteArray * crt);
+/**
+ * Used by mbedTLS to retrieve own certificate chain
+ *
+ * @param[out] crt certificate chain to be filled.
+ */
+void GetDerOwnCert(ByteArray * crt);
+/**
+ * Used by mbedTLS to retrieve owm private key
+ *
+ * @param[out] key key to be filled.
+ */
+void GetDerKey(ByteArray * key);
+/**
+ * Used by CA to retrieve credential types
+ *
+ * @param[out] key key to be filled.
+ */
+void InitCipherSuiteList(bool *list);
+#endif // __WITH_TLS__
 #ifdef __cplusplus
 }
 #endif
index 3e98f8c..a2f135c 100644 (file)
@@ -21,8 +21,7 @@
 #ifndef IOTVT_SRM_CRLR_H
 #define IOTVT_SRM_CRLR_H
 
-#include "octypes.h"
-#include "securevirtualresourcetypes.h"
+#include "ocpayload.h"
 
 #ifdef __cplusplus
 extern "C" {
@@ -35,7 +34,7 @@ extern "C" {
  *
  * @return ::OC_STACK_OK for Success, otherwise some error value.
  */
-OCStackResult UpdateCRLResource(const OicSecCrl_t *crl);
+OCStackResult UpdateCRLResource(OicSecCrl_t *crl);
 
 /**
  * This function get encoded with base64 CRL from SRM.
@@ -60,12 +59,14 @@ void  GetDerCrl(ByteArray* crlArray);
  * will be allocated by the function and content of *crl will be ignored.
  * @param payload is the converted cbor value.
  * @param size is a pointer to length of the CRL buffer. Should be not NULL.
+ * @param lastUpdate optional field contains CRL last update time
  *
  * @note Caller responsible for crl buffer memory (use OICFree to free it).
  *
  * @return ::OC_STACK_OK if success, otherwise some error value.
  */
-OCStackResult CrlToCBORPayload(const OicSecCrl_t *crl, uint8_t **payload, size_t *size);
+OCStackResult CrlToCBORPayload(const OicSecCrl_t *crl, uint8_t **payload, size_t *size,
+                               char *lastUpdate);
 
 /**
  * This function converts CBOR to CRL
@@ -102,6 +103,23 @@ OCStackResult DeInitCRLResource();
  */
 OicSecCrl_t *GetCRLResource();
 
+/**
+ * This function frees resources inside given OicSecCrl_t object
+ *
+ * @param crl  crl object
+ */
+void DeleteCrl(OicSecCrl_t *crl);
+
+/**
+ * This function gets time when CRL was last updated in database
+ * Function allocates memory for lastUpdate and
+ * Caller is responsible to free that memory
+ *
+ * @param lastUpdate    pointer to last update string.
+ * @return ::OC_STACK_OK for Success, otherwise some error value.
+ */
+OCStackResult getLastUpdateFromDB(char **lastUpdate);
+
 #ifdef __cplusplus
 }
 #endif
old mode 100755 (executable)
new mode 100644 (file)
index f63a2b1..fb8843f
@@ -87,6 +87,14 @@ OCStackResult DoxmToCBORPayload(const OicSecDoxm_t * doxm, uint8_t **cborPayload
 OCStackResult GetDoxmDeviceID(OicUuid_t *deviceID);
 
 /**
+ * This method changes the SRM device ID for this device.
+ * This api will update device Id iff device is in unowned state.
+ * @return ::OC_STACK_OK for Success, otherwise some error value.
+ */
+OCStackResult SetDoxmDeviceID(const OicUuid_t *deviceID);
+
+
+/**
  * Gets the OicUuid_t value for the owner of this device.
  *
  * @param devownerid a pointer to be assigned to the devownerid property
index f7f0773..ba7bcf6 100644 (file)
@@ -153,6 +153,7 @@ extern const char * OIC_JSON_SEC_V_NAME;
 extern const char * OIC_JSON_EMPTY_STRING;
 
 extern const char * TRUST_CA;
+extern const char * PRIMARY_CERT;
 
 extern OicUuid_t WILDCARD_SUBJECT_ID;
 extern OicUuid_t WILDCARD_SUBJECT_B64_ID;
diff --git a/resource/csdk/security/include/pkix_interface.h b/resource/csdk/security/include/pkix_interface.h
new file mode 100644 (file)
index 0000000..e4e5835
--- /dev/null
@@ -0,0 +1,40 @@
+/******************************************************************
+ *
+ * Copyright 2016 Samsung Electronics 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.
+ *
+ ******************************************************************/
+
+#ifndef PKIX_INTERFACE_H
+#define PKIX_INTERFACE_H
+
+#include "cainterface.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+/**
+ * This method is used by mbedTLS/SRM to retrieve PKIX related info
+ *
+ * @param[out] inf structure with certificate, private key and crl to be filled.
+ *
+ */
+void GetPkixInfo(PkiInfo_t * inf);
+#ifdef __cplusplus
+}
+#endif
+
+#endif //PKIX_INTERFACE_H
index bc0efb4..2101381 100644 (file)
 #ifndef OC_SECURITY_RESOURCE_TYPES_H
 #define OC_SECURITY_RESOURCE_TYPES_H
 
+#include "iotivity_config.h"
+
 #include <stdint.h> // for uint8_t typedef
 #include <stdbool.h>
 #if defined(__WITH_X509__) || defined(__WITH_TLS__)
 #include "byte_array.h"
 #endif /* __WITH_X509__  or __WITH_TLS__*/
 
-#include "platform_features.h"
-
 #ifdef __cplusplus
 extern "C" {
 #endif
@@ -495,7 +495,7 @@ struct OicSecCrl
 {
     uint16_t CrlId;
     ByteArray ThisUpdate;
-    ByteArray CrlData;
+    OicSecKey_t CrlData;
 };
 #endif /* __WITH_X509__ or __WITH_TLS__ */
 
index 4e6c02a..bcf5ea8 100644 (file)
@@ -28,7 +28,7 @@
 extern "C"
 {
 #endif
-#include "uri.h"
+#include <coap/uri.h>
 #ifdef __cplusplus
 }
 #endif
index 96d59f3..593a6c4 100644 (file)
@@ -27,6 +27,14 @@ root_dir = './../../../../'
 ######################################################################
 # Build flags
 ######################################################################
+with_upstream_libcoap = provisioning_env.get('WITH_UPSTREAM_LIBCOAP')
+if with_upstream_libcoap == '1':
+       # For bring up purposes only, we manually copy the forked version to where the unforked version is downloaded.
+       provisioning_env.AppendUnique(CPPPATH = ['#extlibs/libcoap/libcoap/include'])
+else:
+       # For bring up purposes only, the forked version will live here.
+       provisioning_env.AppendUnique(CPPPATH = ['../../connectivity/lib/libcoap-4.1.1/include'])
+
 provisioning_env.AppendUnique(CPPPATH = [
                '../../stack/include',
                '../../stack/include/internal',
@@ -36,6 +44,7 @@ provisioning_env.AppendUnique(CPPPATH = [
                '../../../c_common/oic_malloc/include',
                'include',
                'include/internal',
+               'include/cloud',
                'include/oxm',
                '../../resource/csdk/security/include',
                '../../../../extlibs/cjson/',
@@ -44,7 +53,6 @@ provisioning_env.AppendUnique(CPPPATH = [
                '../../connectivity/inc/pkix',
                '../../connectivity/external/inc',
                '../../connectivity/common/inc',
-               '../../connectivity/lib/libcoap-4.1.1',
                '../../connectivity/api',
                '../include',
                '../include/internal',
@@ -54,9 +62,6 @@ provisioning_env.AppendUnique(CPPPATH = [
                'ck_manager/include'
                ])
 
-if target_os not in ['tizen']:
-       provisioning_env.AppendUnique(CPPPATH = ['../../../../extlibs/sqlite3'])
-
 provisioning_env.AppendUnique(CPPDEFINES= ['__WITH_DTLS__'])
 
 if 'g++' in provisioning_env.get('CXX'):
@@ -67,6 +72,9 @@ provisioning_env.PrependUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'connecti
 
 provisioning_env.AppendUnique(LIBS = ['tinydtls'])
 
+if provisioning_env.get('WITH_TCP') == True:
+       provisioning_env.AppendUnique(LIBS = ['mbedtls', 'mbedx509','mbedcrypto'])
+
 if provisioning_env.get('DTLS_WITH_X509') == '1':
        provisioning_env.AppendUnique(LIBS = ['CKManager', 'asn1'])
 if provisioning_env.get('WITH_TCP') == True:
@@ -78,9 +86,6 @@ if target_os not in ['msys_nt', 'windows', 'android']:
 if target_os in ['windows', 'msys_nt']:
        provisioning_env.AppendUnique(LIBS = ['ws2_32', 'advapi32', 'iphlpapi', 'timer'])
 
-if target_os in ['tizen']:
-       provisioning_env.ParseConfig('pkg-config --cflags --libs sqlite3')
-
 if target_os in ['android']:
        provisioning_env.AppendUnique(CXXFLAGS = ['-frtti', '-fexceptions'])
        provisioning_env.AppendUnique(LIBS = ['gnustl_static'])
@@ -104,7 +109,19 @@ provisioning_src = [
        'src/oxmrandompin.c',
        'src/provisioningdatabasemanager.c' ]
 
-if target_os != 'tizen':
+if provisioning_env.get('WITH_TCP') == True:
+       provisioning_src = provisioning_src + [
+       'src/cloud/utils.c',
+       'src/cloud/crl.c',
+       'src/cloud/aclgroup.c',
+       'src/cloud/aclinvite.c',
+       'src/cloud/aclid.c',
+       'src/cloud/csr.c']
+
+if target_os in ['tizen']:
+       provisioning_env.ParseConfig('pkg-config --cflags --libs sqlite3')
+else:
+       provisioning_env.AppendUnique(CPPPATH = ['../../../../extlibs/sqlite3'])
        provisioning_src = provisioning_src + [root_dir+'/extlibs/sqlite3/sqlite3.c' ]
 
 if target_os in ['windows', 'msys_nt']:
index c5b1f80..d45be77 100644 (file)
@@ -64,12 +64,6 @@ typedef struct /*CA private key, CA certificate, other CA-related info*/
     long        numberOfRevoked;
 } CKMInfo_t;
 
-typedef struct /*CA private key, CA certificate, certificate revocation/white list*/
-{
-    uint32_t    CRLsize;
-    uint8_t     *certificateRevocationList;//should be allocated dynamically
-} CRLInfo_t;
-
 //General functions
 
 /**
index 2512f98..71e938f 100644 (file)
@@ -27,6 +27,14 @@ provisioning_env = env.Clone()
 ######################################################################
 # Build flags
 ######################################################################
+with_upstream_libcoap = provisioning_env.get('WITH_UPSTREAM_LIBCOAP')
+if with_upstream_libcoap == '1':
+       # For bring up purposes only, we manually copy the forked version to where the unforked version is downloaded.
+       provisioning_env.AppendUnique(CPPPATH = ['#extlibs/libcoap/libcoap/include'])
+else:
+       # For bring up purposes only, the forked version will live here.
+       provisioning_env.AppendUnique(CPPPATH = ['../../../../connectivity/lib/libcoap-4.1.1/include'])
+
 provisioning_env.AppendUnique(CPPPATH = [
                '../../../../stack/include',
                '../../../../../c_common/ocrandom/include',
@@ -45,7 +53,6 @@ provisioning_env.AppendUnique(CPPPATH = [
                '../../../../connectivity/inc',
                '../../../../connectivity/inc/pkix/',
                '../../../../connectivity/common/inc',
-               '../../../../connectivity/lib/libcoap-4.1.1',
                '../../../../connectivity/api',
                '../../../../../c_common/oic_malloc/include',
                '../include',
diff --git a/resource/csdk/security/provisioning/include/cloud/occloudprovisioning.h b/resource/csdk/security/provisioning/include/cloud/occloudprovisioning.h
new file mode 100644 (file)
index 0000000..9b3f9b1
--- /dev/null
@@ -0,0 +1,406 @@
+/* *****************************************************************
+ *
+ * Copyright 2016 Samsung Electronics 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.
+ *
+ * *****************************************************************/
+#ifndef OC_CLOUD_PROVISIONING_H
+#define OC_CLOUD_PROVISIONING_H
+
+#include "octypes.h"
+#include "securevirtualresourcetypes.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif // __cplusplus
+
+typedef void (*OCCloudResponseCB )(void* ctx, OCStackResult result, void* data);
+
+typedef struct cloudAce cloudAce_t;
+
+struct cloudAce {
+    char *aceId;
+    OicUuid_t subjectuuid;
+    uint16_t stype;
+    uint16_t permission;
+    OicSecRsrc_t *resources;
+    OicSecValidity_t *validities;
+    cloudAce_t *next;
+};
+
+typedef struct {
+    char **array;
+    size_t length;
+}stringArray_t;
+
+typedef struct {
+    stringArray_t gidlist;
+    stringArray_t midlist;
+}stringArrayPair_t;
+
+typedef struct {
+    stringArrayPair_t invite;
+    stringArrayPair_t invited;
+}inviteResponse_t;
+
+/**
+ * Certificate-Issue request function
+ *
+ * @param[in] ctx               user-defined context
+ * @param[in] endPoint          cloud host and port
+ * @param[in] callback          result callback
+ * @return  OCStackResult application result
+ */
+OCStackResult OCCloudCertificateIssueRequest(void* ctx,
+                                             const OCDevAddr *endPoint,
+                                             OCCloudResponseCB callback);
+
+/**
+ * CRL GET request function
+ *
+ * @param[in] ctx               user-defined context
+ * @param[in] endPoint          cloud host and port
+ * @param[in] callback          result callback
+ * @return  OCStackResult application result
+ */
+OCStackResult OCCloudGetCRL(void* ctx,
+                            const OCDevAddr *endPoint,
+                            OCCloudResponseCB callback);
+
+/**
+ * CRL POST request function (with Serial Numbers list to revoke)
+ *
+ * @param[in] ctx               user-defined context
+ * @param[in] thisUpdate        mandatory parameter thisUpdate
+ * @param[in] nextUpdate        mandatory parameter nextUpdate
+ * @param[in] crl               optional parameter crl
+ * @param[in] serialNumbers     optional parameter serial numbers
+ * @param[in] endPoint          cloud host and port
+ * @param[in] callback          result callback
+ * @return  OCStackResult application result
+ */
+OCStackResult OCCloudPostCRL(void* ctx,
+                             const char *thisUpdate,
+                             const char *nextUpdate,
+                             const OCByteString *crl,
+                             const stringArray_t *serialNumbers,
+                             const OCDevAddr *endPoint,
+                             OCCloudResponseCB callback);
+
+/**
+ * ACL id retrieve by device id
+ *
+ * @param[in] ctx               user-defined context
+ * @param[in] deviceId          mandatory parameter device id
+ * @param[in] endPoint          cloud host and port
+ * @param[in] callback          result callback
+ * @return  OCStackResult application result
+ */
+OCStackResult OCCloudAclIdGetByDevice(void* ctx,
+                                      const char *deviceId,
+                                      const OCDevAddr *endPoint,
+                                      OCCloudResponseCB callback);
+
+/**
+ * ACL id create
+ *
+ * @param[in] ctx               user-defined context
+ * @param[in] ownerId           mandatory parameter owner id
+ * @param[in] deviceId          mandatory parameter device id
+ * @param[in] endPoint          cloud host and port
+ * @param[in] callback          result callback
+ * @return  OCStackResult application result
+ */
+OCStackResult OCCloudAclIdCreate(void* ctx,
+                                 const char *ownerId,
+                                 const char *deviceId,
+                                 const OCDevAddr *endPoint,
+                                 OCCloudResponseCB callback);
+
+/**
+ * ACL id delete
+ *
+ * @param[in] ctx               user-defined context
+ * @param[in] aclId             mandatory parameter acl id
+ * @param[in] endPoint          cloud host and port
+ * @param[in] callback          result callback
+ * @return  OCStackResult application result
+ */
+OCStackResult OCCloudAclIdDelete(void* ctx,
+                                 const char *aclId,
+                                 const OCDevAddr *endPoint,
+                                 OCCloudResponseCB callback);
+
+/**
+ * ACL individual get info
+ *
+ * @param[in] ctx               user-defined context
+ * @param[in] aclId             mandatory parameter acl id
+ * @param[in] endPoint          cloud host and port
+ * @param[in] callback          result callback
+ * @return  OCStackResult application result
+ */
+OCStackResult OCCloudAclIndividualGetInfo(void* ctx,
+                                          const char *aclId,
+                                          const OCDevAddr *endPoint,
+                                          OCCloudResponseCB callback);
+
+/**
+ * ACL individual update ACE
+ *
+ * @param[in] ctx               user-defined context
+ * @param[in] aclId             mandatory parameter acl id
+ * @param[in] aces              mandatory parameter aces
+ * @param[in] endPoint          cloud host and port
+ * @param[in] callback          result callback
+ * @return  OCStackResult application result
+ */
+OCStackResult OCCloudAclIndividualUpdateAce(void* ctx,
+                                            const char *aclId,
+                                            const cloudAce_t *aces,
+                                            const OCDevAddr *endPoint,
+                                            OCCloudResponseCB callback);
+
+/**
+ * ACL individual delete
+ *
+ * @param[in] ctx               user-defined context
+ * @param[in] aclId             mandatory parameter acl id
+ * @param[in] endPoint          cloud host and port
+ * @param[in] callback          result callback
+ * @return  OCStackResult application result
+ */
+OCStackResult OCCloudAclIndividualDelete(void* ctx,
+                                         const char *aclId,
+                                         const OCDevAddr *endPoint,
+                                         OCCloudResponseCB callback);
+
+/**
+ * ACL post group request function
+ *
+ * @param[in] ctx               user-defined context
+ * @param[in] groupType         mandatory parameter group type
+ * @param[in] groupMasterId     optional parameter group master id
+ * @param[in] endPoint          cloud host and port
+ * @param[in] callback          result callback
+ * @return  OCStackResult application result
+ */
+OCStackResult OCCloudAclCreateGroup(void* ctx,
+                                    const char *groupType,
+                                    const char *groupMasterId,
+                                    const OCDevAddr *endPoint,
+                                    OCCloudResponseCB callback);
+
+/**
+ * ACL get group request function
+ *
+ * @param[in] ctx               user-defined context
+ * @param[in] memberId          mandatory parameter member id
+ * @param[in] endPoint          cloud host and port
+ * @param[in] callback          result callback
+ * @return  OCStackResult application result
+ */
+OCStackResult OCCloudAclFindMyGroup(void* ctx,
+                                    const char *memberId,
+                                    const OCDevAddr *endPoint,
+                                    OCCloudResponseCB callback);
+
+/**
+ * ACL delete group request function
+ *
+ * @param[in] ctx               user-defined context
+ * @param[in] groupId           mandatory parameter group id
+ * @param[in] groupMasterId     optional parameter group master id
+ * @param[in] endPoint          cloud host and port
+ * @param[in] callback          result callback
+ * @return  OCStackResult application result
+ */
+OCStackResult OCCloudAclDeleteGroup(void* ctx,
+                                    const char *groupId,
+                                    const char *groupMasterId,
+                                    const OCDevAddr *endPoint,
+                                    OCCloudResponseCB callback);
+
+/**
+ * ACL join to invited group request function
+ *
+ * @param[in] ctx               user-defined context
+ * @param[in] groupId           mandatory parameter group id
+ * @param[in] endPoint          cloud host and port
+ * @param[in] callback          result callback
+ * @return  OCStackResult application result
+ */
+OCStackResult OCCloudAclJoinToInvitedGroup(void* ctx,
+                                           const char *groupId,
+                                           const OCDevAddr *endPoint,
+                                           OCCloudResponseCB callback);
+
+/**
+ * ACL observe group request function
+ *
+ * @param[in] ctx               user-defined context
+ * @param[in] groupId           mandatory parameter group id
+ * @param[in] endPoint          cloud host and port
+ * @param[in] callback          result callback
+ * @return  OCStackResult application result
+ */
+OCStackResult OCCloudAclObserveGroup(void* ctx,
+                                     const char *groupId,
+                                     const OCDevAddr *endPoint,
+                                     OCCloudResponseCB callback);
+
+/**
+ * ACL share device into group request function
+ *
+ * @param[in] ctx               user-defined context
+ * @param[in] groupId           mandatory parameter group id
+ * @param[in] memberIds         mandatory parameter members list
+ * @param[in] deviceIds         mandatory parameter devices list
+ * @param[in] endPoint          cloud host and port
+ * @param[in] callback          result callback
+ * @return  OCStackResult application result
+ */
+OCStackResult OCCloudAclShareDeviceIntoGroup(void* ctx,
+                                             const char *groupId,
+                                             const stringArray_t *memberIds,
+                                             const stringArray_t *deviceIds,
+                                             const OCDevAddr *endPoint,
+                                             OCCloudResponseCB callback);
+
+/**
+ * ACL delete device from group request function
+ *
+ * @param[in] ctx               user-defined context
+ * @param[in] groupId           mandatory parameter group id
+ * @param[in] memberIds         mandatory parameter members list
+ * @param[in] deviceIds         mandatory parameter devices list
+ * @param[in] endPoint          cloud host and port
+ * @param[in] callback          result callback
+ * @return  OCStackResult application result
+ */
+OCStackResult OCCloudAclDeleteDeviceFromGroup(void* ctx,
+                                              const char *groupId,
+                                              const stringArray_t *memberIds,
+                                              const stringArray_t *deviceIds,
+                                              const OCDevAddr *endPoint,
+                                              OCCloudResponseCB callback);
+
+/**
+ * ACL get group info request function
+ *
+ * @param[in] ctx               user-defined context
+ * @param[in] groupId           mandatory parameter group id
+ * @param[in] memberId          optional parameter member id
+ * @param[in] endPoint          cloud host and port
+ * @param[in] callback          result callback
+ * @return  OCStackResult application result
+ */
+OCStackResult OCCloudAclGroupGetInfo(void* ctx,
+                                     const char *groupId,
+                                     const char *memberId,
+                                     const OCDevAddr *endPoint,
+                                     OCCloudResponseCB callback);
+
+/**
+ * ACL invite user to group request function
+ *
+ * @param[in] ctx               user-defined context
+ * @param[in] userId            optional parameter user id
+ * @param[in] groupIds          mandatory parameter groups list
+ * @param[in] memberIds         mandatory parameter members list
+ * @param[in] endPoint          cloud host and port
+ * @param[in] callback          result callback
+ * @return  OCStackResult application result
+ */
+OCStackResult OCCloudAclInviteUser(void* ctx,
+                                   const char *userId,
+                                   const stringArray_t *groupIds,
+                                   const stringArray_t *memberIds,
+                                   const OCDevAddr *endPoint,
+                                   OCCloudResponseCB callback);
+
+/**
+ * ACL get invitation request function
+ *
+ * @param[in] ctx               user-defined context
+ * @param[in] userId            optional parameter user id
+ * @param[in] endPoint          cloud host and port
+ * @param[in] callback          result callback
+ * @return  OCStackResult application result
+ */
+OCStackResult OCCloudAclGetInvitation(void* ctx,
+                                      const char *userId,
+                                      const OCDevAddr *endPoint,
+                                      OCCloudResponseCB callback);
+
+/**
+ * ACL delete invitation request function (by receiver)
+ *
+ * @param[in] ctx               user-defined context
+ * @param[in] userId            optional parameter user id
+ * @param[in] groupId           mandatory parameter group id
+ * @param[in] endPoint          cloud host and port
+ * @param[in] callback          result callback
+ * @return  OCStackResult application result
+ */
+OCStackResult OCCloudAclDeleteInvitation(void* ctx,
+                                         const char *userId,
+                                         const char *groupId,
+                                         const OCDevAddr *endPoint,
+                                         OCCloudResponseCB callback);
+
+/**
+ * ACL cancel invitation request function (by sender)
+ *
+ * @param[in] ctx               user-defined context
+ * @param[in] userId            optional parameter user id
+ * @param[in] groupId           mandatory parameter group id
+ * @param[in] memberId          mandatory parameter member id
+ * @param[in] endPoint          cloud host and port
+ * @param[in] callback          result callback
+ * @return  OCStackResult application result
+ */
+OCStackResult OCCloudAclCancelInvitation(void* ctx,
+                                         const char *userId,
+                                         const char *groupId,
+                                         const char *memberId,
+                                         const OCDevAddr *endPoint,
+                                         OCCloudResponseCB callback);
+
+/**
+ * ACL check that given request can be applied to resource
+ *
+ * @param[in] ctx               user-defined context
+ * @param[in] subjectId         mandatory parameter subject id
+ * @param[in] deviceId          mandatory parameter device id
+ * @param[in] method            mandatory parameter method
+ * @param[in] uri               mandatory parameter uri
+ * @param[in] endPoint          cloud host and port
+ * @param[in] callback          result callback
+ * @return  OCStackResult application result
+ */
+OCStackResult OCCloudAclPolicyCheck(void* ctx,
+                                    const char *subjectId,
+                                    const char *deviceId,
+                                    const char *method,
+                                    const char *uri,
+                                    const OCDevAddr *endPoint,
+                                    OCCloudResponseCB callback);
+
+#ifdef __cplusplus
+}
+#endif // __cplusplus
+#endif //OC_CLOUD_PROVISIONING_H
diff --git a/resource/csdk/security/provisioning/include/cloud/utils.h b/resource/csdk/security/provisioning/include/cloud/utils.h
new file mode 100644 (file)
index 0000000..f6b1c04
--- /dev/null
@@ -0,0 +1,64 @@
+/* *****************************************************************
+ *
+ * Copyright 2016 Samsung Electronics 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.
+ *
+ * *****************************************************************/
+#ifndef CLOUD_UTILS_H
+#define CLOUD_UTILS_H
+
+#include "occloudprovisioning.h"
+
+extern char *DEFAULT_QUERY;
+extern char *DEFAULT_PREFIX;
+
+typedef OCStackResult (*UserFunctionCB)(void *params, void **data, OCClientResponse *clientResponse);
+
+/**
+ * This function sets required CoAP prefix depending on
+ * secure or non-secure connection
+ *
+ * @param[in] secure   secure flag
+ */
+void setCoapPrefix(bool secure);
+
+/**
+ * This hepler function fills OCCallbackData
+ *
+ * @param[in] cbData       cloud host and port
+ * @param[in] ctx          external context
+ * @param[in] cb           external callback
+ * @param[in] fn           internal function
+ * @param[in] params       params to internal function
+ */
+void fillCallbackData(OCCallbackData *cbData, void *ctx, OCCloudResponseCB cb,
+                                              UserFunctionCB fn, void *params);
+
+/**
+ * Get the device id from db
+ *
+ * @return  device id
+ */
+char *getDeviceId();
+
+/**
+ * Clear previously filled array of strings
+ *
+ * @param[out] list           array of strings structure to clear
+ */
+void clearStringArray(stringArray_t *list);
+
+#endif // CLOUD_UTILS_H
index 001339b..97b90f0 100644 (file)
@@ -104,6 +104,16 @@ OCStackResult SRPProvisionTrustCertChain(void *ctx, OicSecCredType_t type, uint1
 OCStackResult SRPSaveTrustCertChain(uint8_t *trustCertChain, size_t chainSize,
                                         OicEncodingType_t encodingType,uint16_t *credId);
 
+/**
+ * function to save own certificate chain into Cred of SVR.
+ *
+ * @param[in] cert own certificate chain to be saved in Cred of SVR.
+ * @param[in] key own secret key to be saved in Cred of SVR.
+ * @param[out] credId CredId of saved trust certificate chain in Cred of SVR.
+ * @return  OC_STACK_OK in case of success and other value otherwise.
+ */
+OCStackResult SRPSaveOwnCertChain(OicSecCert_t * cert, OicSecKey_t * key, uint16_t *credId);
+
 #endif // __WITH_X509__ || __WITH_TLS__
 /**
  * API to send Direct-Pairing Configuration to a device.
index d3947b1..5d8c8a7 100755 (executable)
@@ -38,7 +38,9 @@ extern "C"
 #define COAP_QUERY "coap://%s:%d%s"
 
 #define COAP_TCP_PREFIX "coap+tcp://"
+#define COAP_TCP_QUERY "coap+tcp://%s:%d%s"
 #define COAPS_TCP_PREFIX "coaps+tcp://"
+#define COAPS_TCP_QUERY "coaps+tcp://%s:%d%s"
 
 /**
  * Discover owned/unowned devices in the specified endpoint.
diff --git a/resource/csdk/security/provisioning/sample/README-cloud.txt b/resource/csdk/security/provisioning/sample/README-cloud.txt
new file mode 100644 (file)
index 0000000..05720c9
--- /dev/null
@@ -0,0 +1,32 @@
+# Cloud Connection
+
+# Start cloud application
+# Run ./cloudClient command in console. By default if uses cloud.dat database
+# if you want to use custom database, run ./cloudClient <filename>
+
+# After cloudClient start, you will see the big Menu
+# First of all, you need to fill proper connection settings
+# Enter number 4 (Change default host) - and enter your ip address
+# By default, cloudClient using non-secure connection. If you want to use secure connection
+# Enter number 5 (Change default port) - and enter 5684 (default CoAPs port)
+# Enter number 10 (Change Protocol type (CoAP/CoAPs)) - and enter 1 - secure connection
+# You can check all settings, they are printed in title of the Menu
+
+# After basic setting were done, it is required to execute Sign Up request
+# Enter number 1 (Sign Up request) and follow the comments (go to link, get authentication token and paste it to console)
+# Then, before each user request, it is required to execute Sign In request
+# Enter number 2 (Sign In request) and check the result.
+# If it says "UUID is missing, execute Sign Up first", then previous Sign Up failed.
+# Otherwice, it is OK and you can proceed to user requests
+
+# After successful Sign Up and Sign In, you can execute user Requests
+# There are 3 main group of requests - Certificate Request, CRL and ACL requests
+# After Certificate Request, CRL Get and ACL Get Individual Info SVR database will be updated by received data from cloud
+# Details about all requests you can find in latest Convergence Spec (what will be sent to and received from Cloud)
+
+# Device-to-Device connection
+
+# Start both ./cloudClient <client database> and ./cloudServer <server database> in two terminals
+# In cloudClient Menu, Enter number 13 (Start Discovery). It will discover all resources in network.
+# After discover, you can execute (14/15/16) GET/PUT/POST requests.
+# Data for those requests will be automatically get from discovery (host, port and uri of first found secure resource)
index 23818ff..fc7005e 100644 (file)
@@ -28,16 +28,26 @@ target_os = provisioning_env.get('TARGET_OS')
 ######################################################################
 # Build flags
 ######################################################################
+with_upstream_libcoap = provisioning_env.get('WITH_UPSTREAM_LIBCOAP')
+if with_upstream_libcoap == '1':
+       # For bring up purposes only, we manually copy the forked version to where the unforked version is downloaded.
+       provisioning_env.AppendUnique(CPPPATH = ['#extlibs/libcoap/libcoap/include'])
+else:
+       # For bring up purposes only, the forked version will live here.
+       provisioning_env.AppendUnique(CPPPATH = ['../../../connectivity/lib/libcoap-4.1.1/include'])
+
 provisioning_env.AppendUnique(CPPPATH = [
                '../../../stack/include',
                '../../../ocrandom/include',
                '../../../logger/include',
                '../../../stack/include',
                '../../../security/include',
+               '../../../security/include/internal',
                '../../../security/provisioning/include/internal',
                '../../../../oc_logger/include',
                '../include',
                '../include/oxm',
+               '../include/cloud',
                '../../include',
                '../../../../../extlibs/tinydtls',
                '../../../../../extlibs/cjson',
@@ -45,8 +55,8 @@ provisioning_env.AppendUnique(CPPPATH = [
                '../../../connectivity/inc',
                '../../../connectivity/inc/pkix',
                '../../../connectivity/common/inc',
-               '../../../connectivity/lib/libcoap-4.1.1',
-               '../../../connectivity/api'
+               '../../../connectivity/api',
+               'cloud'
                ])
 
 target_os = env.get('TARGET_OS')
@@ -82,6 +92,7 @@ provisioning_env.AppendUnique(CPPDEFINES = ['TB_LOG'])
 
 if target_os == 'tizen':
     provisioning_env.AppendUnique(CPPDEFINES = ['__TIZEN__'])
+    provisioning_env.ParseConfig('pkg-config --cflags --libs sqlite3')
 
 ######################################################################
 # Source files and Targets
@@ -90,11 +101,19 @@ if target_os == 'tizen':
 provisioningclient = provisioning_env.Program('provisioningclient', 'provisioningclient.c')
 sampleserver_justworks = provisioning_env.Program('sampleserver_justworks', 'sampleserver_justworks.cpp')
 sampleserver_randompin = provisioning_env.Program('sampleserver_randompin', 'sampleserver_randompin.cpp')
+if provisioning_env.get('WITH_TCP') == True:
+    cloudClient_src = [
+        'cloudClient.c',
+        'cloud/cloudAuth.c',
+        'cloud/cloudWrapper.c',
+        'cloud/cloudDiscovery.c']
+    cloudClient = provisioning_env.Program('cloudClient', cloudClient_src)
 
 src_dir = provisioning_env.get('SRC_DIR')
 sec_provisioning_src_dir = src_dir + '/resource/csdk/security/provisioning/sample/'
 sec_provisioning_build_dir = env.get('BUILD_DIR') +'/resource/csdk/security/provisioning/sample/'
 
+
 clientdat = provisioning_env.Install(sec_provisioning_build_dir,
                                         sec_provisioning_src_dir + 'oic_svr_db_client.dat')
 justworksdat = provisioning_env.Install(sec_provisioning_build_dir,
@@ -103,8 +122,14 @@ randompindat = provisioning_env.Install(sec_provisioning_build_dir,
                                     sec_provisioning_src_dir+ 'oic_svr_db_server_randompin.dat')
 randompin_with_emptyuuid_dat = provisioning_env.Install(sec_provisioning_build_dir,
                                     sec_provisioning_src_dir+ 'oic_svr_db_randompin_with_empty_deviceid.dat')
+if provisioning_env.get('WITH_TCP') == True:
+    clouddat = provisioning_env.Install(sec_provisioning_build_dir,
+                                        sec_provisioning_src_dir + 'cloud.dat')
+    rootcert = provisioning_env.Install(sec_provisioning_build_dir,
+                                        sec_provisioning_src_dir + 'rootca.crt')
+    Alias("cloud", [clouddat, rootcert, cloudClient])
+    provisioning_env.AppendTarget("cloud")
 
 Alias("samples", [provisioningclient, sampleserver_justworks, sampleserver_randompin, clientdat, justworksdat, randompindat, randompin_with_emptyuuid_dat])
-
 provisioning_env.AppendTarget('samples')
 
diff --git a/resource/csdk/security/provisioning/sample/cloud.dat b/resource/csdk/security/provisioning/sample/cloud.dat
new file mode 100644 (file)
index 0000000..d08f163
Binary files /dev/null and b/resource/csdk/security/provisioning/sample/cloud.dat differ
diff --git a/resource/csdk/security/provisioning/sample/cloud.json b/resource/csdk/security/provisioning/sample/cloud.json
new file mode 100644 (file)
index 0000000..3ab5914
--- /dev/null
@@ -0,0 +1,68 @@
+{
+    "acl": {
+        "aclist": {
+            "aces": [
+                {
+                    "subjectuuid": "*",
+                    "resources": [
+                        {
+                            "href": "/oic/res",
+                            "rel": "",
+                            "rt": ["oic.wk.res"],
+                            "if": ["oic.if.ll"]
+                        },{
+                            "href": "/oic/d",
+                            "rel": "",
+                            "rt": ["oic.wk.d"],
+                            "if": ["oic.if.baseline", "oic.if.r"]
+                        },{
+                            "href": "/oic/p",
+                            "rel": "",
+                            "rt": ["oic.wk.p"],
+                            "if": ["oic.if.baseline", "oic.if.r"]
+                        }
+                    ],
+                    "permission": 2
+                },
+                {
+                    "subjectuuid": "*",
+                    "resources": [
+                        {
+                            "href": "/oic/sec/doxm",
+                            "rel": "",
+                            "rt": ["oic.r.doxm"],
+                            "if": ["oic.if.baseline"]
+                        },
+                        {
+                            "href": "/oic/sec/pstat",
+                            "rel": "",
+                            "rt": ["oic.r.pstat"],
+                            "if": ["oic.if.baseline"]
+                        }
+                    ],
+                    "permission": 2
+                }
+            ]
+        },
+        "rowneruuid" : "61646D69-6E44-6576-6963-655575696430"
+    },
+    "pstat": {
+        "isop": true,
+        "cm": 0,
+        "tm": 0,
+        "om": 3,
+        "sm": 3,
+        "deviceuuid": "61646D69-6E44-6576-6963-655575696430",
+        "rowneruuid": "61646D69-6E44-6576-6963-655575696430"
+    },
+    "doxm": {
+        "oxms": [0],
+        "oxmsel": 0,
+        "sct": 1,
+        "owned": true,
+        "deviceuuid": "61646D69-6E44-6576-6963-655575696430",
+        "x.org.iotivity.dpc": false,
+        "devowneruuid": "61646D69-6E44-6576-6963-655575696430",
+        "rowneruuid": "61646D69-6E44-6576-6963-655575696430"
+    }
+}
diff --git a/resource/csdk/security/provisioning/sample/cloud/cloudAuth.c b/resource/csdk/security/provisioning/sample/cloud/cloudAuth.c
new file mode 100644 (file)
index 0000000..27fafbb
--- /dev/null
@@ -0,0 +1,443 @@
+/* *****************************************************************
+ *
+ * Copyright 2016 Samsung Electronics 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.
+ *
+ * *****************************************************************/
+
+#include "octypes.h"
+#include "logger.h"
+#include "payload_logging.h"
+#include "ocstack.h"
+#include "ocpayload.h"
+#include "psinterface.h"
+#include "securevirtualresourcetypes.h"
+#include "doxmresource.h"
+#include "oic_malloc.h"
+#include "oic_string.h"
+#include "srmutility.h"
+#include "pmutility.h"
+#include "credresource.h"
+#include "payload_logging.h"
+
+#include "utils.h"
+#include "cloudAuth.h"
+#include "cloudCommon.h"
+
+#define TAG "cloudAuth"
+
+#define LOGIN_OK 4
+
+#define MAX_URI_QUERY MAX_URI_LENGTH + MAX_QUERY_LENGTH
+
+typedef struct
+{
+    char *accesstoken;
+    char *refreshtoken;
+    char *tokentype;
+    long  expiresin;
+    char *uid;
+    char *redirecturi;
+    char *certificate;
+    char *sid;
+} sessionObject_t;
+
+static sessionObject_t sessionObject = {0,0,0,0,0,0,0,0};
+
+/**
+ * Session free function
+ *
+ * @return  OCStackResult application result
+ */
+static void SessionFree()
+{
+    if (sessionObject.accesstoken)  OICFree(sessionObject.accesstoken);
+    if (sessionObject.refreshtoken) OICFree(sessionObject.refreshtoken);
+    if (sessionObject.tokentype)    OICFree(sessionObject.tokentype);
+    if (sessionObject.uid)          OICFree(sessionObject.uid);
+    if (sessionObject.redirecturi)  OICFree(sessionObject.redirecturi);
+    if (sessionObject.certificate)  OICFree(sessionObject.certificate);
+    if (sessionObject.sid)          OICFree(sessionObject.sid);
+
+    memset(&sessionObject, 0, sizeof(sessionObject_t));
+}
+
+/**
+ * Session init function
+ *
+ * @param[in] sessionObject session data
+ * @return  OCStackResult application result
+ */
+static OCStackResult SessionInit()
+{
+    OIC_LOG_V(DEBUG, TAG, "IN: %s", __func__);
+
+    SessionFree(sessionObject);
+
+    OIC_LOG_V(DEBUG, TAG, "OUT: %s", __func__);
+
+    return OC_STACK_OK;
+}
+
+/**
+ * Session parse payload
+ *
+ * @param[in] payload
+ * @param[in] sessionObject session data
+ * @return  OCStackResult application result
+ */
+static OCStackResult SessionParsePayload(OCRepPayload *payload)
+{
+    OIC_LOG_V(DEBUG, TAG, "IN: %s", __func__);
+
+    VERIFY_NON_NULL(TAG, payload, ERROR);
+
+    SessionInit();
+
+    if (!OCRepPayloadGetPropString(payload, OC_RSRVD_ACCESS_TOKEN,
+                                   &sessionObject.accesstoken))
+    {
+        OIC_LOG(ERROR, TAG, "Can't get: accesstoken");
+    }
+    if (!OCRepPayloadGetPropString(payload, OC_RSRVD_REFRESH_TOKEN,
+                                   &sessionObject.refreshtoken))
+    {
+        OIC_LOG(ERROR, TAG, "Can't get: refreshtoken");
+    }
+    if (!OCRepPayloadGetPropString(payload, OC_RSRVD_TOKEN_TYPE,
+                                   &sessionObject.tokentype))
+    {
+        OIC_LOG(ERROR, TAG, "Can't get: tokentype");
+    }
+    if (!OCRepPayloadGetPropInt(payload, OC_RSRVD_EXPIRES_IN,
+                                &(sessionObject.expiresin)))
+    {
+        OIC_LOG(ERROR, TAG, "Can't get: expiresin");
+    }
+    if (!OCRepPayloadGetPropString(payload, OC_RSRVD_USER_UUID,
+                                   &sessionObject.uid))
+    {
+        OIC_LOG(ERROR, TAG, "Can't get: uid");
+    }
+    if (!OCRepPayloadGetPropString(payload, OC_RSRVD_REDIRECT_URI,
+                                   &sessionObject.redirecturi))
+    {
+        OIC_LOG(ERROR, TAG, "Can't get: redirecturi");
+    }
+    if (!OCRepPayloadGetPropString(payload, OC_RSRVD_CERTIFICATE,
+                                   &sessionObject.certificate))
+    {
+        OIC_LOG(ERROR, TAG, "Can't get: certificate");
+    }
+    if (!OCRepPayloadGetPropString(payload, OC_RSRVD_SUBJECT_ID,
+                                   &sessionObject.sid))
+    {
+        OIC_LOG(ERROR, TAG, "Can't get: sid");
+    }
+
+    OIC_LOG_V(DEBUG, TAG, "OUT: %s", __func__);
+exit:
+    return OC_STACK_OK;
+}
+
+/**
+ * Sends Sign Up request to cloud
+ *
+ * @param[in] ctx                    context
+ * @param[in] handle                 handle
+ * @param[in] response               response from peer
+ * @return  OCStackApplicationResult application result
+ */
+static OCStackApplicationResult handleCloudSignUpResponse(void *ctx,
+                                                          OCDoHandle handle,
+                                                          OCClientResponse *response)
+{
+    OC_UNUSED(ctx);
+    OC_UNUSED(handle);
+
+    if (!response)
+    {
+        OIC_LOG(ERROR, TAG, "Received NULL response!");
+        goto exit;
+    }
+
+    if (response->payload)
+    {
+        OIC_LOG(ERROR, TAG, "Payload received");
+        OIC_LOG_PAYLOAD(DEBUG, response->payload);
+    }
+
+    if (response->result != LOGIN_OK)
+    {
+        OIC_LOG_V(ERROR, TAG, "Login error: %d",response->result);
+    }
+    else
+    {
+        OIC_LOG(DEBUG, TAG, "Login successful");
+        SessionParsePayload((OCRepPayload*)response->payload);
+    }
+exit:
+    return OC_STACK_DELETE_TRANSACTION;
+}
+
+OCStackResult CloudSignUp(const OCDevAddr *endPoint,
+                          const char *authProvider,
+                          const char *authToken)
+{
+    char uri[MAX_URI_LENGTH] = { 0 };
+
+    OIC_LOG_V(DEBUG, TAG, "IN: %s", __func__);
+
+    if (!endPoint || !authProvider || !authToken)
+    {
+        OIC_LOG(ERROR, TAG, "Some of the input params are NULL");
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    char *deviceId = getDeviceId();
+    if (!deviceId)
+    {
+        OIC_LOG(ERROR, TAG, "Can't get the device id");
+        return OC_STACK_ERROR;
+    }
+
+    snprintf(uri, MAX_URI_LENGTH, DEFAULT_QUERY,
+             endPoint->addr, endPoint->port, OC_RSRVD_ACCOUNT_URI);
+
+    OCCallbackData cbData;
+    memset(&cbData, 0, sizeof(OCCallbackData));
+    cbData.cb = handleCloudSignUpResponse;
+    cbData.cd = unlockMenu;
+
+    OCRepPayload *payload = OCRepPayloadCreate();
+    if (!payload)
+    {
+        OIC_LOG(ERROR, TAG, "Failed to memory allocation");
+        return OC_STACK_NO_MEMORY;
+    }
+
+    OCRepPayloadSetPropString(payload, OC_RSRVD_DEVICE_ID, deviceId);
+    OCRepPayloadSetPropString(payload, OC_RSRVD_AUTHPROVIDER, OICStrdup(authProvider));
+    OCRepPayloadSetPropString(payload, OC_RSRVD_AUTHCODE, OICStrdup(authToken));
+
+    return OCDoResource(NULL, OC_REST_POST, uri, NULL, (OCPayload *)payload,
+                        CT_ADAPTER_TCP, OC_LOW_QOS, &cbData, NULL, 0);
+}
+
+/**
+ * Sends Sign In request to cloud
+ *
+ * @param[in] ctx                    context
+ * @param[in] handle                 handle
+ * @param[in] response               response from peer
+ * @return  OCStackApplicationResult application result
+ */
+static OCStackApplicationResult handleCloudSignInResponse(void *ctx,
+                                                          OCDoHandle handle,
+                                                          OCClientResponse *response)
+{
+    OIC_LOG_V(DEBUG, TAG, "IN: %s", __func__);
+
+    OC_UNUSED(ctx);
+    OC_UNUSED(handle);
+
+    if (!response)
+    {
+        OIC_LOG(ERROR, TAG, "Received NULL response!");
+        goto exit;
+    }
+
+    if (response->payload)
+    {
+        OIC_LOG(ERROR, TAG, "Payload received");
+        OIC_LOG_PAYLOAD(DEBUG, response->payload);
+    }
+
+    if (response->result < 4 && response->payload)
+    {
+        OIC_LOG_V(ERROR, TAG, "Sign In error: result: %d, payload exist: %s",
+                  response->result, response->payload ? "yes" : "no");
+        goto exit;
+    }
+
+    if (!OCRepPayloadGetPropString((OCRepPayload*)response->payload, OC_RSRVD_USER_UUID,
+                                   &(sessionObject.uid)))
+    {
+        OIC_LOG(ERROR, TAG, "Can't get: uid");
+    }
+
+    if (!OCRepPayloadGetPropInt((OCRepPayload*)response->payload, OC_RSRVD_EXPIRES_IN,
+                                &(sessionObject.expiresin)))
+    {
+        OIC_LOG(ERROR, TAG, "Cann't get: expiresin");
+    }
+
+    OIC_LOG_V(DEBUG, TAG, "OUT: %s", __func__);
+
+exit:
+    return OC_STACK_DELETE_TRANSACTION;
+}
+
+OCStackResult CloudSignIn(const OCDevAddr  *endPoint)
+{
+    OIC_LOG_V(DEBUG, TAG, "IN: %s", __func__);
+
+    if (!endPoint)
+    {
+        OIC_LOG_V(ERROR, TAG, "%s: endPoint is NULL",__func__);
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    if (!sessionObject.uid)
+    {
+        OIC_LOG_V(ERROR, TAG, "%s: UID is missing. Please run Sign Up first",__func__);
+        return OC_STACK_ERROR;
+    }
+
+    if (!sessionObject.accesstoken)
+    {
+        OIC_LOG_V(ERROR, TAG, "%s: accesstoken is missing. Please run Sign Up first",__func__);
+        return OC_STACK_ERROR;
+    }
+
+    char *deviceId = getDeviceId();
+    if (!deviceId)
+    {
+        OIC_LOG(ERROR, TAG, "Can't get the device id");
+        return OC_STACK_ERROR;
+    }
+
+    OCRepPayload* payload = OCRepPayloadCreate();
+    if (NULL == payload)
+    {
+        OIC_LOG(ERROR, TAG, "Failed to memory allocation");
+        return OC_STACK_NO_MEMORY;
+    }
+
+    OCRepPayloadSetPropString(payload, OC_RSRVD_USER_UUID, sessionObject.uid);
+    OCRepPayloadSetPropString(payload, OC_RSRVD_DEVICE_ID, deviceId);
+    OCRepPayloadSetPropString(payload, OC_RSRVD_ACCESS_TOKEN,
+                              sessionObject.accesstoken);
+    OCRepPayloadSetPropBool(payload, OC_RSRVD_LOGIN, true);
+
+    char uri[MAX_URI_QUERY] = { 0, };
+    snprintf(uri, MAX_URI_QUERY, DEFAULT_QUERY,
+             endPoint->addr, endPoint->port,
+             OC_RSRVD_ACCOUNT_SESSION_URI);
+
+    OCCallbackData cbData;
+    memset(&cbData, 0, sizeof(OCCallbackData));
+    cbData.cb = handleCloudSignInResponse;
+    cbData.cd = unlockMenu;
+
+    return OCDoResource(NULL, OC_REST_POST, uri, NULL,
+                       (OCPayload *)payload,
+                       CT_ADAPTER_TCP,
+                       OC_LOW_QOS, &cbData, NULL, 0);
+}
+
+static OCStackApplicationResult handleCloudSignOutResponse(void *ctx,
+                                                           OCDoHandle handle,
+                                                           OCClientResponse *response)
+{
+    OIC_LOG_V(DEBUG, TAG, "IN: %s", __func__);
+
+    OC_UNUSED(ctx);
+    OC_UNUSED(handle);
+
+    if (!response)
+    {
+        OIC_LOG(ERROR, TAG, "Received NULL response!");
+        goto exit;
+    }
+
+    if (response->payload)
+    {
+        OIC_LOG(ERROR, TAG, "Payload received");
+        OIC_LOG_PAYLOAD(DEBUG, response->payload);
+    }
+
+    if (response->result < 4 && response->payload)
+    {
+        OIC_LOG_V(ERROR, TAG, "Sign Out error");
+        return OC_STACK_DELETE_TRANSACTION;
+    }
+    else
+    {
+        OIC_LOG_V(ERROR, TAG, "Sign Out OK");
+    }
+
+    SessionFree();
+
+    OIC_LOG_V(DEBUG, TAG, "OUT: %s", __func__);
+
+exit:
+    return OC_STACK_DELETE_TRANSACTION;
+}
+
+/**
+ * Sends Sign Out request to cloud
+ *
+ * @param[in] ctx                    context
+ * @param[in] handle                 handle
+ * @param[in] response               response from peer
+ * @return  OCStackApplicationResult application result
+ */
+OCStackResult CloudSignOut(const OCDevAddr *endPoint)
+{
+    OIC_LOG_V(DEBUG, TAG, "IN: %s", __func__);
+
+    if (!endPoint)
+    {
+        OIC_LOG_V(ERROR, TAG, "%s: endPoint is NULL",__func__);
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    char *deviceId = getDeviceId();
+    if (!deviceId)
+    {
+        OIC_LOG(ERROR, TAG, "Cann't get the device id");
+        return OC_STACK_ERROR;
+    }
+
+    OCRepPayload* payload = OCRepPayloadCreate();
+    if (!payload)
+    {
+        OIC_LOG(ERROR, TAG, "Failed to memory allocation");
+        return OC_STACK_NO_MEMORY;
+    }
+
+    OCRepPayloadSetPropString(payload, OC_RSRVD_DEVICE_ID, deviceId);
+    OCRepPayloadSetPropString(payload, OC_RSRVD_ACCESS_TOKEN,
+                              sessionObject.accesstoken);
+    OCRepPayloadSetPropBool(payload, OC_RSRVD_LOGIN, false);
+
+    char uri[MAX_URI_QUERY] = { 0, };
+    snprintf(uri, MAX_URI_QUERY, DEFAULT_QUERY,
+             endPoint->addr, endPoint->port,
+             OC_RSRVD_ACCOUNT_SESSION_URI);
+
+    OCCallbackData cbData;
+    memset(&cbData, 0, sizeof(OCCallbackData));
+    cbData.cb = handleCloudSignOutResponse;
+    cbData.cd = unlockMenu;
+
+    return OCDoResource(NULL, OC_REST_POST, uri, NULL,
+                       (OCPayload *)payload,
+                       CT_ADAPTER_TCP,
+                       OC_LOW_QOS, &cbData, NULL, 0);
+}
+
diff --git a/resource/csdk/security/provisioning/sample/cloud/cloudAuth.h b/resource/csdk/security/provisioning/sample/cloud/cloudAuth.h
new file mode 100644 (file)
index 0000000..cc84050
--- /dev/null
@@ -0,0 +1,54 @@
+/* *****************************************************************
+ *
+ * Copyright 2016 Samsung Electronics 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.
+ *
+ * *****************************************************************/
+#ifndef CLOUD_AUTH_H
+#define CLOUD_AUTH_H
+
+/**
+ * Sends Sign UP request to cloud
+ *
+ * @param[in] endPoint         peer endpoint
+ * @param[in] authProvider     authentication provider
+ * @param[in] authToken        authentication token
+ * @param[in] response         response callback
+ * @return  OCStackResult application result
+ */
+OCStackResult CloudSignUp(const OCDevAddr  *endPoint,
+                          const char *authProvider,
+                          const char *authToken);
+
+/**
+ * Sends Sign IN request to cloud
+ *
+ * @param[in] endPoint         peer endpoint
+ * @param[in] response         response callback
+ * @return  OCStackResult application result
+ */
+OCStackResult CloudSignIn(const OCDevAddr  *endPoint);
+
+/**
+ * Sends Sign OUT request to cloud
+ *
+ * @param[in] endPoint         peer endpoint
+ * @param[in] response         response callback
+ * @return  OCStackResult application result
+ */
+OCStackResult CloudSignOut(const OCDevAddr  *endPoint);
+
+#endif // CLOUD_AUTH_H
diff --git a/resource/csdk/security/provisioning/sample/cloud/cloudCommon.h b/resource/csdk/security/provisioning/sample/cloud/cloudCommon.h
new file mode 100644 (file)
index 0000000..1f617bc
--- /dev/null
@@ -0,0 +1,31 @@
+/* *****************************************************************
+ *
+ * Copyright 2016 Samsung Electronics 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.
+ *
+ * *****************************************************************/
+#ifndef CLOUD_COMMON_H
+#define CLOUD_COMMON_H
+
+/**
+ * Used to sync with main menu
+ * Create this function to have proper API for delete callbacks
+ *
+ * @param[in] data         data
+ */
+void unlockMenu(void *data);
+
+#endif // CLOUD_COMMON_H
diff --git a/resource/csdk/security/provisioning/sample/cloud/cloudDiscovery.c b/resource/csdk/security/provisioning/sample/cloud/cloudDiscovery.c
new file mode 100644 (file)
index 0000000..f81c0fe
--- /dev/null
@@ -0,0 +1,230 @@
+#include "ocstack.h"
+#include "logger.h"
+#include "ocpayload.h"
+#include "payload_logging.h"
+#include "oic_string.h"
+#include "srmresourcestrings.h"
+#include "pmutility.h"
+
+#include "cloudCommon.h"
+#include "cloudWrapper.h"
+
+#define TAG "cloudDiscovery"
+
+#define DISCOVERY_URI "/oic/res"
+
+static OCDevAddr endPoint;
+static OCConnectivityType ocConnType = CT_DEFAULT;
+static char gUri[MAX_URI_LENGTH] = {0};
+
+bool withTcp = true;
+
+/**
+ * This function clears internal data
+ */
+static void clearData()
+{
+    memset(&endPoint, 0, sizeof(endPoint));
+    memset(gUri, 0, sizeof(gUri));
+    ocConnType = CT_DEFAULT;
+}
+
+/**
+ * This function parses Discovery payload
+ * It tries to find secure devices
+ *
+ * @param[in] clientResponse   response from peer
+ */
+static void parseClientResponse(OCClientResponse * clientResponse)
+{
+    OCResourcePayload* res = ((OCDiscoveryPayload*)clientResponse->payload)->resources;
+
+    while (res)
+    {
+        char *uri = res->uri;
+        OIC_LOG_V(INFO, TAG, "Uri -- %s", uri);
+
+        if (0 == strcmp(uri, OIC_RSRC_DOXM_URI))
+        {
+            OIC_LOG(INFO,TAG,"Skip: doxm is secure virtual resource");
+            goto next;
+        }
+        if (0 == strcmp(uri, OIC_RSRC_PSTAT_URI))
+        {
+            OIC_LOG(INFO,TAG,"Skip: pstat is secure virtual resource");
+            goto next;
+        }
+
+        OIC_LOG_V(INFO, TAG, "Secure -- %s", res->secure ? "YES" : "NO");
+
+        if (res->secure)
+        {
+            ocConnType = clientResponse->connType;
+            endPoint = clientResponse->devAddr;
+
+            if(withTcp)
+            {
+                OIC_LOG_V(INFO,TAG,"SECUREPORT tcp: %d",res->tcpPort);
+                endPoint.port = res->tcpPort;
+            }
+            else
+            {
+                OIC_LOG_V(INFO,TAG,"SECUREPORT udp: %d",res->port);
+                endPoint.port = res->port;
+            }
+            OICStrcpy(gUri, sizeof(gUri), uri);
+            break;
+        }
+
+        next:
+        res = res->next;
+    }
+}
+
+/**
+ * This function handles discovery response
+ *
+ * @param[in] ctx                    context
+ * @param[in] handle                 handle
+ * @param[in] response               response from peer
+ * @return  OCStackApplicationResult application result
+ */
+static OCStackApplicationResult handleDiscoveryResponse(void *ctx, OCDoHandle handle,
+                                                        OCClientResponse * clientResponse)
+{
+    OC_UNUSED(ctx);
+    OC_UNUSED(handle);
+
+    if (NULL == clientResponse)
+    {
+        OIC_LOG(ERROR, TAG, "Receive NULL response");
+        return OC_STACK_DELETE_TRANSACTION;
+    }
+
+    if (OC_STACK_OK == clientResponse->result)
+    {
+        OIC_LOG(INFO, TAG, "Discovery successful!");
+    }
+    else
+    {
+        OIC_LOG_V(INFO, TAG, "Discovery fails with result: %d", clientResponse->result);
+    }
+
+    if (clientResponse->payload)
+    {
+        OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
+    }
+    else
+    {
+        OIC_LOG(ERROR, TAG, "Receive NULL payload");
+    }
+
+    OIC_LOG_V(INFO, TAG,
+            "Device =============> Discovered @ %s:%d",
+            clientResponse->devAddr.addr,
+            clientResponse->devAddr.port);
+
+    parseClientResponse(clientResponse);
+
+    return OC_STACK_KEEP_TRANSACTION;
+}
+
+/**
+ * This function handles any response from secure device
+ *
+ * @param[in] ctx                    context
+ * @param[in] handle                 handle
+ * @param[in] response               response from peer
+ * @return  OCStackApplicationResult application result
+ */
+static OCStackApplicationResult handleResponse(void *ctx, OCDoHandle handle,
+                                               OCClientResponse * clientResponse)
+{
+    OC_UNUSED(ctx);
+    OC_UNUSED(handle);
+
+    if(!clientResponse)
+    {
+        OIC_LOG_V(ERROR, TAG, "%s: Received NULL response",  __func__);
+        return OC_STACK_DELETE_TRANSACTION;
+    }
+
+    if (NULL == ctx)
+    {
+        OIC_LOG_V(ERROR, TAG, "%s: Received NULL context, exit",  __func__);
+        return OC_STACK_DELETE_TRANSACTION;
+    }
+
+    char *str = NULL;
+    OCMethod method = *((OCMethod*)ctx);
+
+    switch (method)
+    {
+        case OC_REST_GET:
+            str = "Get";
+            break;
+        case OC_REST_PUT:
+            str = "Put";
+            break;
+        case OC_REST_POST:
+            str = "Post";
+            break;
+        default:
+            OIC_LOG_V(INFO, TAG, "Received Wrong method %d. Skip response", method);
+            return OC_STACK_ERROR;
+    }
+
+    OIC_LOG_V(INFO, TAG, "StackResult: %d",  clientResponse->result);
+    OIC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
+    OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
+    OIC_LOG_V(INFO, TAG, "=============> %s Response", str);
+
+    return OC_STACK_DELETE_TRANSACTION;
+}
+
+OCStackResult InitDiscovery()
+{
+    clearData();
+
+    OCCallbackData cbData;
+    memset(&cbData, 0, sizeof(OCCallbackData));
+    cbData.cb = handleDiscoveryResponse;
+    cbData.cd = unlockMenu;
+
+    return OCDoResource(NULL, OC_REST_DISCOVER, DISCOVERY_URI, NULL, 0,
+                        CT_DEFAULT, OC_LOW_QOS, &cbData, NULL, 0);
+}
+
+OCStackResult InitRequest(OCMethod method)
+{
+    if (0 == endPoint.port || 0 == endPoint.addr[0])
+    {
+        OIC_LOG(ERROR, TAG, "Host or port are missing. Please execute Discovery first!");
+        return OC_STACK_ERROR;
+    }
+
+    OCMethod *tmp = OICCalloc(1, sizeof(OCMethod));
+    if (!tmp)
+    {
+        OIC_LOG(ERROR, TAG, "Can't allocate tmp");
+        return OC_STACK_NO_MEMORY;
+    }
+
+    *tmp = method;
+
+    OIC_LOG_V(INFO, TAG, "Executing uri = %s", gUri);
+    OIC_LOG_V(INFO, TAG, "Send Request to %s:%d", endPoint.addr, endPoint.port);
+
+    endPoint.flags = (OCTransportFlags)(endPoint.flags | OC_SECURE);
+    endPoint.adapter = OC_ADAPTER_TCP;
+
+
+    OCCallbackData cbData;
+    memset(&cbData, 0, sizeof(OCCallbackData));
+    cbData.cd = unlockMenu;
+    cbData.cb = handleResponse;
+    cbData.context = (void *)tmp;
+
+    return OCDoResource(NULL, method, gUri, &endPoint, 0,
+                        ocConnType, OC_LOW_QOS, &cbData, NULL, 0);
+}
diff --git a/resource/csdk/security/provisioning/sample/cloud/cloudDiscovery.h b/resource/csdk/security/provisioning/sample/cloud/cloudDiscovery.h
new file mode 100644 (file)
index 0000000..e9ad6d4
--- /dev/null
@@ -0,0 +1,38 @@
+/* *****************************************************************
+ *
+ * Copyright 2016 Samsung Electronics 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.
+ *
+ * *****************************************************************/
+#ifndef CLOUD_DISCOVERY_H
+#define CLOUD_DISCOVERY_H
+
+/**
+ * This function discovers devices
+ *
+ * @param[in] secure   secure flag
+ */
+OCStackResult InitDiscovery();
+
+/**
+ * This function sends GET/PUT/POST request to peer
+ * Peer info taken from previous discovery
+ *
+ * @param[in] method   request method
+ */
+OCStackResult InitRequest(OCMethod method);
+
+#endif // CLOUD_DISCOVERY_H
diff --git a/resource/csdk/security/provisioning/sample/cloud/cloudWrapper.c b/resource/csdk/security/provisioning/sample/cloud/cloudWrapper.c
new file mode 100644 (file)
index 0000000..3aa0eed
--- /dev/null
@@ -0,0 +1,594 @@
+#include "logger.h"
+#include "occloudprovisioning.h"
+#include "oic_malloc.h"
+#include "oic_string.h"
+
+#include "utils.h"
+
+#define TAG "CLOUD-WRAPPER"
+
+#define MAX_ID_LENGTH       (64)
+#define MAX_STRING_LENGTH   (256)
+
+#define UUID_EXAMPLE_1 "9cfbeb8e-5a1e-4d1c-9d01-2ae6fdb"
+#define UUID_EXAMPLE_2 "123e4567-e89b-12d3-a456-4266554"
+#define UUID_EXAMPLE_3 "987e6543-e21b-12d3-a456-4266554"
+#define SUBJECT_ID_EXAMPLE "72616E64-5069-6E44-6576-557569643030"
+
+#define ACL_ID_EXAMPLE "0f3d9f7fe5491d54077d"
+#define ACE_ID_EXAMPLE "a0001"
+
+#define ID_EXAMPLE_1   "78f98b4f25f21e2487e8"
+#define ID_EXAMPLE_2   "6caa7009386290fd3681"
+
+#define RESOURCE_URI_EXAMPLE "/a/light/0"
+#define RESOURCE_TYPE_EXAMPLE "core.light"
+#define INTERFACE_EXAMPLE "oic.if.baseline"
+
+//in case of optional parameters absence should be sent NULL
+#define OPTIONAL(str) (str[0] ? str : NULL)
+
+static bool readOptional(const char* description)
+{
+    if (NULL == description)
+    {
+        return false;
+    }
+
+    printf("Do you want to Enter %s (y/n):\n", description);
+    char choice = 0;
+
+    while(1)
+    {
+        scanf("%c", &choice);
+        getchar();
+
+        switch (choice)
+        {
+            case 'y': return true;
+            case 'n': return false;
+            default: printf("Wrong value entered. Please press 'y' or 'n'\n");
+        }
+    }
+    return false;
+}
+
+void readString(char* item, int length, const char* description, const char* example)
+{
+    printf("Enter %s (f.e. %s):\n", description, example);
+    char template[8] = { 0 };
+    snprintf(template, sizeof(template), "%%%ds", length - 1);
+    scanf(template, item);
+    getchar();
+}
+
+/**
+ * Read user input (expect string value, but it is optional and can be skipped by user)
+ *
+ * @param[out] item           string item to fill
+ * @param[in] length          max allowed string length
+ * @param[in] description     item description
+ * @param[in] example         item example
+ */
+static void readOptionalString(char* item, int length, const char* description, const char* example)
+{
+    if (readOptional(description))
+    {
+        readString(item, length, description, example);
+    }
+}
+
+void readInteger(int* item, const char* description, const char* example)
+{
+    printf("Enter %s (f.e. %s):\n", description, example);
+    scanf("%d", item);
+    getchar();
+}
+
+/**
+ * Read user input (expect array of strings)
+ *
+ * @param[out] list           array of strings structure
+ * @param[in] length          max allowed array item length
+ * @param[in] description     whole array description
+ * @param[in] example         array item example
+ */
+static void readStringArray(stringArray_t *list, int length, const char* description, const char* example)
+{
+    int i = 0;
+    int count = 0;
+    char hint[MAX_STRING_LENGTH] = { 0 };
+
+    snprintf(hint, sizeof(hint), "%s items count", description);
+    readInteger(&count, hint, "2");
+
+    char **item = NULL;
+
+    if (0 == count)
+    {
+        return;
+    }
+
+    item = OICCalloc(count, sizeof(char*));
+
+    if (NULL == item)
+    {
+        goto no_memory;
+    }
+
+    for (i = 0; i < count; i++)
+    {
+        item[i] = OICCalloc(length, sizeof(char));
+
+        if (NULL == item[i])
+        {
+            goto no_memory;
+        }
+
+        snprintf(hint, sizeof(hint), "%s %d item", description, i + 1);
+        readString(item[i], length, hint, example);
+    }
+    list->array  = item;
+    list->length = count;
+    return;
+
+no_memory:
+    //free already allocated memory here
+    for (int k = 0; k < i; k++)
+    {
+        OICFree(item[k]);
+    }
+    OICFree(item);
+}
+
+/**
+ * Read user input (expect array of strings)
+ * It is optional and can be skipped by user.
+ *
+ * @param[out] list           array of strings structure
+ * @param[in] length          max allowed array item length
+ * @param[in] description     whole array description
+ * @param[in] example         array item example
+ */
+static void readOptionalStringArray(stringArray_t *list, int length, const char* description, const char* example)
+{
+    if (readOptional(description))
+    {
+        readStringArray(list, length, description, example);
+    }
+}
+
+/**
+ * Copies whole binary file to crl variable
+ *
+ * @param[in] list           array of strings structure
+ * @param[out] crl           byte array to fill
+ * @return                   negative error code
+ * */
+static int ReadFile(const char *name, OCByteString *crl)
+{
+    FILE *file = NULL;
+    int length = 0;
+    uint8_t *buffer = NULL;
+    int result = 1;
+
+    //Open file
+    file = fopen(name, "rb");
+    if (!file)
+    {
+        OIC_LOG_V(ERROR, TAG, "Unable to open file %s", name);
+        return result;
+    }
+
+    //Get file length
+    result = fseek(file, 0, SEEK_END);
+    if (result)
+    {
+        OIC_LOG(ERROR, TAG, "Failed to SEEK_END");
+        goto exit;
+    }
+
+    length = ftell(file);
+    if (length < 0)
+    {
+        OIC_LOG(ERROR, TAG, "Failed to ftell");
+        goto exit;
+    }
+
+    result = fseek(file, 0, SEEK_SET);
+    if (result)
+    {
+        OIC_LOG(ERROR, TAG, "Failed to SEEK_SET");
+        goto exit;
+    }
+
+    //Allocate memory
+    buffer = (uint8_t *)malloc(length);
+    if (!buffer)
+    {
+        OIC_LOG(ERROR, TAG, "Failed to allocate buffer");
+        goto exit;
+    }
+
+    //Read file contents into buffer
+    size_t realLen = fread(buffer, length, 1, file);
+    if (realLen != (size_t)length)
+    {
+        OIC_LOG_V(ERROR, TAG, "Length mismatch: read %zu instead of %d bytes", realLen, length);
+        goto exit;
+    }
+
+    crl->bytes = buffer;
+    crl->len   = length;
+
+    result = 0;
+exit:
+    fclose(file);
+    return 0;
+}
+
+OCStackResult OCWrapperCertificateIssueRequest(const OCDevAddr *endPoint, OCCloudResponseCB callback)
+{
+    return OCCloudCertificateIssueRequest(NULL, endPoint, callback);
+}
+
+OCStackResult OCWrapperGetCRL(const OCDevAddr *endPoint, OCCloudResponseCB callback)
+{
+    return OCCloudGetCRL(NULL, endPoint, callback);
+}
+
+OCStackResult OCWrapperPostCRL(const OCDevAddr *endPoint, OCCloudResponseCB callback)
+{
+    OCStackResult result = OC_STACK_ERROR;
+    OCByteString crlData = {0, 0};
+    char filename[64] = {0};
+    char thisUpdate[16] = { 0 };
+    char nextUpdate[16] = { 0 };
+    stringArray_t serialNumbers = {0, 0};
+
+    readString(thisUpdate, sizeof(thisUpdate), "Crl's thisUpdate value", "20160727000000");
+    readString(nextUpdate, sizeof(nextUpdate), "Crl's nextUpdate value", "20161027000000");
+    readOptionalStringArray(&serialNumbers, 16, "Revoked serial numbers", "1234");
+
+    if (NULL == serialNumbers.array)
+    {
+        readString(filename, sizeof(filename),
+                   "filename from which binary Crl in DER format will be read", "crl");
+
+        if (ReadFile(filename, &crlData))
+        {
+            printf("Can't read crl from file %s\n", filename);
+            goto exit;
+        }
+    }
+    stringArray_t *rcsn = serialNumbers.array? &serialNumbers : NULL;
+    OCByteString *crl = crlData.bytes? &crlData : NULL;
+
+    result = OCCloudPostCRL(NULL, thisUpdate, nextUpdate, crl, rcsn,
+                            endPoint, callback);
+exit:
+    clearStringArray(&serialNumbers);
+    OICFree(crlData.bytes);
+
+    return result;
+}
+
+OCStackResult OCWrapperAclIdGetByDevice(const OCDevAddr *endPoint, OCCloudResponseCB callback)
+{
+    char di[MAX_ID_LENGTH] = { 0 };
+
+    readString(di, sizeof(di), "device id", UUID_EXAMPLE_1);
+
+    return OCCloudAclIdGetByDevice(NULL, di, endPoint, callback);
+}
+
+OCStackResult OCWrapperAclIdCreate(const OCDevAddr *endPoint, OCCloudResponseCB callback)
+{
+    char oid[MAX_ID_LENGTH]  = { 0 };
+    char di[MAX_ID_LENGTH]   = { 0 };
+
+    readString(oid, sizeof(oid), "owner id", UUID_EXAMPLE_2);
+    readString(di, sizeof(di), "device id", UUID_EXAMPLE_1);
+
+    return OCCloudAclIdCreate(NULL, oid, di, endPoint, callback);
+}
+
+OCStackResult OCWrapperAclIdDelete(const OCDevAddr *endPoint, OCCloudResponseCB callback)
+{
+    char aclid[MAX_ID_LENGTH] = { 0 };
+
+    readString(aclid, sizeof(aclid), "acl id", ACL_ID_EXAMPLE);
+
+    return OCCloudAclIdDelete(NULL, aclid, endPoint, callback);
+}
+
+OCStackResult OCWrapperAclIndividualGetInfo(const OCDevAddr *endPoint, OCCloudResponseCB callback)
+{
+    char aclid[MAX_ID_LENGTH] = { 0 };
+
+    readString(aclid, sizeof(aclid), "acl id", ACL_ID_EXAMPLE);
+
+    return OCCloudAclIndividualGetInfo(NULL, aclid, endPoint, callback);
+}
+
+OCStackResult OCWrapperAclIndividualUpdateAce(const OCDevAddr *endPoint, OCCloudResponseCB callback)
+{
+    OCStackResult result = OC_STACK_NO_MEMORY;
+    int i = 0, j = 0;
+
+    char aclid[MAX_ID_LENGTH] = { 0 };
+    readString(aclid, sizeof(aclid), "ace id", ACL_ID_EXAMPLE);
+
+    int acllist_count = 0;
+    readInteger(&acllist_count, "acl list count", "1");
+
+    cloudAce_t *aces = OICCalloc(acllist_count, sizeof(cloudAce_t));
+    if (!aces)
+    {
+        OIC_LOG(ERROR, TAG, "Can't allocate memory for aces");
+        goto exit;
+    }
+
+    for (i = 0; i < acllist_count; i++)
+    {
+        cloudAce_t *ace = &aces[i];
+        if (i != acllist_count - 1) ace->next = &aces[i + 1];
+
+        char aceid[MAX_ID_LENGTH] = { 0 };
+        char subjectuuid[MAX_ID_LENGTH] = { 0 };
+        int stype = 0;
+        int permission = 0;
+
+        readString(aceid, sizeof(aceid), "ace id", ACE_ID_EXAMPLE);
+        readString(subjectuuid, sizeof(subjectuuid), "subjectuuid", SUBJECT_ID_EXAMPLE);
+        readInteger(&stype, "subject type", "0 – Device, 1 – User, 2 - Group");
+        readInteger(&permission, "permission", "6");
+
+        ace->aceId = OICStrdup(aceid);
+        ace->stype = stype;
+        ace->permission = permission;
+        memcpy(&ace->subjectuuid, subjectuuid, sizeof(OicUuid_t));
+
+        int reslist_count = 0;
+        readInteger(&reslist_count, "resources list count", "1");
+
+        ace->resources = OICCalloc(reslist_count, sizeof(OicSecRsrc_t));
+        if (!ace->resources)
+        {
+            OIC_LOG(ERROR, TAG, "Can't allocate memory for resources");
+            goto exit;
+        }
+
+        for (j = 0; j < reslist_count; j++)
+        {
+            OicSecRsrc_t *res = &ace->resources[j];
+            if (j != reslist_count - 1) res->next = &ace->resources[j + 1];
+
+            char href[32] = { 0 };
+            readString(href, sizeof(href), "href", RESOURCE_URI_EXAMPLE);
+
+            stringArray_t rt = {0, 0};
+            readStringArray(&rt, MAX_ID_LENGTH, "resource type", RESOURCE_TYPE_EXAMPLE);
+
+            stringArray_t _if = {0, 0};
+            readStringArray(&_if, MAX_ID_LENGTH, "interface", INTERFACE_EXAMPLE);
+
+            res->href = OICStrdup(href);
+            res->types = rt.array;
+            res->typeLen = rt.length;
+            res->interfaces = _if.array;
+            res->interfaceLen = _if.length;
+        }
+    }
+
+    result = OCCloudAclIndividualUpdateAce(NULL, aclid, aces, endPoint, callback);
+exit:
+    if (aces)
+    {
+        for (int k = 0; k < i; k++)
+        {
+            cloudAce_t *ace = &aces[k];
+            OICFree(ace->aceId);
+
+            if (ace->resources)
+            {
+                for (int l = 0; l < j; l++)
+                {
+                    OicSecRsrc_t *res = &ace->resources[l];
+                    OICFree(res->href);
+
+                    stringArray_t rt = {.array = res->types, .length = res->typeLen};
+                    clearStringArray(&rt);
+
+                    stringArray_t _if = {.array = res->interfaces, .length = res->interfaceLen};
+                    clearStringArray(&_if);
+                }
+            }
+
+        }
+    }
+    return result;
+}
+
+OCStackResult OCWrapperAclIndividualDelete(const OCDevAddr *endPoint, OCCloudResponseCB callback)
+{
+    char aclid[MAX_ID_LENGTH] = { 0 };
+
+    readString(aclid, sizeof(aclid), "acl id", ACL_ID_EXAMPLE);
+
+    return OCCloudAclIndividualDelete(NULL, aclid, endPoint, callback);
+}
+
+OCStackResult OCWrapperAclCreateGroup(const OCDevAddr *endPoint, OCCloudResponseCB callback)
+{
+    char gtype[16] = { 0 };
+    char gmid[MAX_ID_LENGTH] = { 0 };
+
+    readString(gtype, sizeof(gtype), "Group type value", "Public");
+    readOptionalString(gmid, sizeof(gmid), "group member id value", UUID_EXAMPLE_2);
+
+    return OCCloudAclCreateGroup(NULL, gtype, OPTIONAL(gmid), endPoint, callback);
+}
+
+OCStackResult OCWrapperAclFindMyGroup(const OCDevAddr *endPoint, OCCloudResponseCB callback)
+{
+    char mid[MAX_ID_LENGTH]  = { 0 };
+
+    readOptionalString(mid, sizeof(mid), "member id value", UUID_EXAMPLE_2);
+
+    return OCCloudAclFindMyGroup(NULL, OPTIONAL(mid), endPoint, callback);
+}
+
+OCStackResult OCWrapperAclDeleteGroup(const OCDevAddr *endPoint, OCCloudResponseCB callback)
+{
+    char gid[MAX_ID_LENGTH]  = { 0 };
+    char gmid[MAX_ID_LENGTH] = { 0 };
+
+    readString(gid, sizeof(gid), "Group id value", ID_EXAMPLE_1);
+
+    readOptionalString(gmid, sizeof(gmid), "group member id value", UUID_EXAMPLE_2);
+
+    return OCCloudAclDeleteGroup(NULL, gid, OPTIONAL(gmid), endPoint, callback);
+}
+
+OCStackResult OCWrapperAclJoinToInvitedGroup(const OCDevAddr *endPoint, OCCloudResponseCB callback)
+{
+    char gid[MAX_ID_LENGTH]  = { 0 };
+
+    readString(gid, sizeof(gid), "Group id value", ID_EXAMPLE_1);
+
+    return OCCloudAclJoinToInvitedGroup(NULL, gid, endPoint, callback);
+}
+
+OCStackResult OCWrapperAclObserveGroup(const OCDevAddr *endPoint, OCCloudResponseCB callback)
+{
+    char gid[MAX_ID_LENGTH]  = { 0 };
+
+    readString(gid, sizeof(gid), "Group id value", ID_EXAMPLE_1);
+
+    return OCCloudAclObserveGroup(NULL, gid, endPoint, callback);
+}
+
+OCStackResult OCWrapperAclShareDeviceIntoGroup(const OCDevAddr *endPoint, OCCloudResponseCB callback)
+{
+    OCStackResult result = OC_STACK_NO_MEMORY;
+    char gid[MAX_ID_LENGTH]  = { 0 };
+    stringArray_t midlist = {0,0};
+    stringArray_t dilist = {0,0};
+
+    readString(gid, sizeof(gid), "Group id value", ID_EXAMPLE_1);
+
+    readStringArray(&midlist, MAX_ID_LENGTH, "member id list", UUID_EXAMPLE_2);
+
+    readStringArray(&dilist, MAX_ID_LENGTH, "device list", UUID_EXAMPLE_1);
+
+    result = OCCloudAclShareDeviceIntoGroup(NULL, gid, &midlist, &dilist, endPoint, callback);
+
+    clearStringArray(&midlist);
+    clearStringArray(&dilist);
+
+    return result;
+}
+
+OCStackResult OCWrapperAclDeleteDeviceFromGroup(const OCDevAddr *endPoint, OCCloudResponseCB callback)
+{
+    OCStackResult result = OC_STACK_NO_MEMORY;
+    char gid[MAX_ID_LENGTH]  = { 0 };
+    stringArray_t midlist = {0,0};
+    stringArray_t dilist = {0,0};
+
+    readString(gid, sizeof(gid), "Group id value", ID_EXAMPLE_1);
+
+    readStringArray(&midlist, MAX_ID_LENGTH, "member id list", UUID_EXAMPLE_2);
+
+    readStringArray(&dilist, MAX_ID_LENGTH, "device list", UUID_EXAMPLE_1);
+
+    result = OCCloudAclDeleteDeviceFromGroup(NULL, gid, &midlist, &dilist, endPoint, callback);
+
+    clearStringArray(&midlist);
+    clearStringArray(&dilist);
+
+    return result;
+}
+
+OCStackResult OCWrapperAclGroupGetInfo(const OCDevAddr *endPoint, OCCloudResponseCB callback)
+{
+    char gid[MAX_ID_LENGTH]  = { 0 };
+    char mid[MAX_ID_LENGTH]  = { 0 };
+
+    readString(gid, sizeof(gid), "Group id value", ID_EXAMPLE_1);
+
+    readOptionalString(mid, sizeof(mid), "member id value", UUID_EXAMPLE_2);
+
+    return OCCloudAclGroupGetInfo(NULL, gid, OPTIONAL(mid), endPoint, callback);
+}
+
+OCStackResult OCWrapperAclInviteUser(const OCDevAddr *endPoint, OCCloudResponseCB callback)
+{
+    OCStackResult result = OC_STACK_NO_MEMORY;
+    char uid[MAX_ID_LENGTH]  = { 0 };
+    stringArray_t midlist = {0,0};
+    stringArray_t gidlist = {0,0};
+
+    readOptionalString(uid, sizeof(uid), "user id value", UUID_EXAMPLE_2);
+
+    readStringArray(&gidlist, MAX_ID_LENGTH, "group id list", UUID_EXAMPLE_1);
+
+    readStringArray(&midlist, MAX_ID_LENGTH, "member id list", UUID_EXAMPLE_2);
+
+    result = OCCloudAclInviteUser(NULL, OPTIONAL(uid), &gidlist, &midlist, endPoint, callback);
+
+    clearStringArray(&midlist);
+    clearStringArray(&gidlist);
+
+    return result;
+}
+
+OCStackResult OCWrapperAclGetInvitation(const OCDevAddr *endPoint, OCCloudResponseCB callback)
+{
+    char uid[MAX_ID_LENGTH]  = { 0 };
+
+    readOptionalString(uid, sizeof(uid), "user uuid value", UUID_EXAMPLE_2);
+
+    return OCCloudAclGetInvitation(NULL, OPTIONAL(uid), endPoint, callback);
+}
+
+OCStackResult OCWrapperAclDeleteInvitation(const OCDevAddr *endPoint, OCCloudResponseCB callback)
+{
+    char uid[MAX_ID_LENGTH]  = { 0 };
+    char gid[MAX_ID_LENGTH]  = { 0 };
+
+    readOptionalString(uid, sizeof(uid), "user uuid value", UUID_EXAMPLE_2);
+    readString(gid, sizeof(gid), "Group id value", ID_EXAMPLE_1);
+
+    return OCCloudAclDeleteInvitation(NULL, OPTIONAL(uid), gid, endPoint, callback);
+}
+
+OCStackResult OCWrapperAclCancelInvitation(const OCDevAddr *endPoint, OCCloudResponseCB callback)
+{
+    char uid[MAX_ID_LENGTH]  = { 0 };
+    char gid[MAX_ID_LENGTH]  = { 0 };
+    char mid[MAX_ID_LENGTH]  = { 0 };
+
+    readOptionalString(uid, sizeof(uid), "user uuid value", UUID_EXAMPLE_2);
+
+    readString(gid, sizeof(gid), "Group id value", ID_EXAMPLE_1);
+    readString(mid, sizeof(mid), "member id value", ID_EXAMPLE_1);
+
+    return OCCloudAclCancelInvitation(NULL, OPTIONAL(uid), gid, mid, endPoint, callback);
+}
+
+OCStackResult OCWrapperAclPolicyCheck(const OCDevAddr *endPoint, OCCloudResponseCB callback)
+{
+    char sid[MAX_ID_LENGTH] = { 0 };
+    char di[MAX_ID_LENGTH]  = { 0 };
+    char rm[16]  = { 0 };
+    char user_uri[32] = { 0 };
+
+    readString(sid, sizeof(sid), "subject id", UUID_EXAMPLE_1);
+    readString(di, sizeof(di), "device id", UUID_EXAMPLE_2);
+    readString(rm, sizeof(rm), "request method", "GET or POST or DELETE");
+    readString(user_uri, sizeof(user_uri), "request uri", RESOURCE_URI_EXAMPLE);
+
+    return OCCloudAclPolicyCheck(NULL, sid, di, rm, user_uri, endPoint, callback);
+}
diff --git a/resource/csdk/security/provisioning/sample/cloud/cloudWrapper.h b/resource/csdk/security/provisioning/sample/cloud/cloudWrapper.h
new file mode 100644 (file)
index 0000000..a8f3116
--- /dev/null
@@ -0,0 +1,243 @@
+/* *****************************************************************
+ *
+ * Copyright 2016 Samsung Electronics 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.
+ *
+ * *****************************************************************/
+#ifndef OC_CLOUD_WRAPPER_H
+#define OC_CLOUD_WRAPPER_H
+
+#include "occloudprovisioning.h"
+
+/**
+ * Certificate-Issue request function
+ *
+ * @param[in] endPoint          cloud host and port
+ * @param[in] callback          result callback
+ * @return  OCStackResult application result
+ */
+OCStackResult OCWrapperCertificateIssueRequest(const OCDevAddr *endPoint, OCCloudResponseCB callback);
+
+/**
+ * CRL GET request function
+ *
+ * @param[in] endPoint          cloud host and port
+ * @param[in] callback          result callback
+ * @return  OCStackResult application result
+ */
+OCStackResult OCWrapperGetCRL(const OCDevAddr *endPoint, OCCloudResponseCB callback);
+
+/**
+ * CRL POST request function (with Serial Numbers list to revoke)
+ *
+ * @param[in] endPoint          cloud host and port
+ * @param[in] callback          result callback
+ * @return  OCStackResult application result
+ */
+OCStackResult OCWrapperPostCRL(const OCDevAddr *endPoint, OCCloudResponseCB callback);
+
+/**
+ * ACL id retrieve by device id
+ *
+ * @param[in] endPoint          cloud host and port
+ * @param[in] callback          result callback
+ * @return  OCStackResult application result
+ */
+OCStackResult OCWrapperAclIdGetByDevice(const OCDevAddr *endPoint, OCCloudResponseCB callback);
+
+/**
+ * ACL id create
+ *
+ * @param[in] endPoint          cloud host and port
+ * @param[in] callback          result callback
+ * @return  OCStackResult application result
+ */
+OCStackResult OCWrapperAclIdCreate(const OCDevAddr *endPoint, OCCloudResponseCB callback);
+
+/**
+ * ACL id delete
+ *
+ * @param[in] endPoint          cloud host and port
+ * @param[in] callback          result callback
+ * @return  OCStackResult application result
+ */
+OCStackResult OCWrapperAclIdDelete(const OCDevAddr *endPoint, OCCloudResponseCB callback);
+
+/**
+ * ACL individual get info
+ *
+ * @param[in] endPoint          cloud host and port
+ * @param[in] callback          result callback
+ * @return  OCStackResult application result
+ */
+OCStackResult OCWrapperAclIndividualGetInfo(const OCDevAddr *endPoint, OCCloudResponseCB callback);
+
+/**
+ * ACL individual update ACE
+ *
+ * @param[in] endPoint          cloud host and port
+ * @param[in] callback          result callback
+ * @return  OCStackResult application result
+ */
+OCStackResult OCWrapperAclIndividualUpdateAce(const OCDevAddr *endPoint, OCCloudResponseCB callback);
+
+/**
+ * ACL individual delete
+ *
+ * @param[in] endPoint          cloud host and port
+ * @param[in] callback          result callback
+ * @return  OCStackResult application result
+ */
+OCStackResult OCWrapperAclIndividualDelete(const OCDevAddr *endPoint, OCCloudResponseCB callback);
+
+/**
+ * ACL post group request function
+ *
+ * @param[in] endPoint          cloud host and port
+ * @param[in] callback          result callback
+ * @return  OCStackResult application result
+ */
+OCStackResult OCWrapperAclCreateGroup(const OCDevAddr *endPoint, OCCloudResponseCB callback);
+
+/**
+ * ACL get group request function
+ *
+ * @param[in] endPoint          cloud host and port
+ * @param[in] callback          result callback
+ * @return  OCStackResult application result
+ */
+OCStackResult OCWrapperAclFindMyGroup(const OCDevAddr *endPoint, OCCloudResponseCB callback);
+
+/**
+ * ACL delete group request function
+ *
+ * @param[in] endPoint          cloud host and port
+ * @param[in] callback          result callback
+ * @return  OCStackResult application result
+ */
+OCStackResult OCWrapperAclDeleteGroup(const OCDevAddr *endPoint, OCCloudResponseCB callback);
+
+/**
+ * ACL join to invited group request function
+ *
+ * @param[in] endPoint          cloud host and port
+ * @param[in] callback          result callback
+ * @return  OCStackResult application result
+ */
+OCStackResult OCWrapperAclJoinToInvitedGroup(const OCDevAddr *endPoint, OCCloudResponseCB callback);
+
+/**
+ * ACL observe group request function
+ *
+ * @param[in] endPoint          cloud host and port
+ * @param[in] callback          result callback
+ * @return  OCStackResult application result
+ */
+OCStackResult OCWrapperAclObserveGroup(const OCDevAddr *endPoint, OCCloudResponseCB callback);
+
+/**
+ * ACL share device into group request function
+ *
+ * @param[in] endPoint          cloud host and port
+ * @param[in] callback          result callback
+ * @return  OCStackResult application result
+ */
+OCStackResult OCWrapperAclShareDeviceIntoGroup(const OCDevAddr *endPoint, OCCloudResponseCB callback);
+
+/**
+ * ACL delete device from group request function
+ *
+ * @param[in] endPoint          cloud host and port
+ * @param[in] callback          result callback
+ * @return  OCStackResult application result
+ */
+OCStackResult OCWrapperAclDeleteDeviceFromGroup(const OCDevAddr *endPoint, OCCloudResponseCB callback);
+
+/**
+ * ACL get group info request function
+ *
+ * @param[in] endPoint          cloud host and port
+ * @param[in] callback          result callback
+ * @return  OCStackResult application result
+ */
+OCStackResult OCWrapperAclGroupGetInfo(const OCDevAddr *endPoint, OCCloudResponseCB callback);
+
+/**
+ * ACL invite user to group request function
+ *
+ * @param[in] endPoint          cloud host and port
+ * @param[in] callback          result callback
+ * @return  OCStackResult application result
+ */
+OCStackResult OCWrapperAclInviteUser(const OCDevAddr *endPoint, OCCloudResponseCB callback);
+
+/**
+ * ACL get invitation request function
+ *
+ * @param[in] endPoint          cloud host and port
+ * @param[in] callback          result callback
+ * @return  OCStackResult application result
+ */
+OCStackResult OCWrapperAclGetInvitation(const OCDevAddr *endPoint, OCCloudResponseCB callback);
+
+/**
+ * ACL delete invitation request function (by receiver)
+ *
+ * @param[in] endPoint          cloud host and port
+ * @param[in] callback          result callback
+ * @return  OCStackResult application result
+ */
+OCStackResult OCWrapperAclDeleteInvitation(const OCDevAddr *endPoint, OCCloudResponseCB callback);
+
+/**
+ * ACL cancel invitation request function (by sender)
+ *
+ * @param[in] endPoint          cloud host and port
+ * @param[in] callback          result callback
+ * @return  OCStackResult application result
+ */
+OCStackResult OCWrapperAclCancelInvitation(const OCDevAddr *endPoint, OCCloudResponseCB callback);
+
+/**
+ * ACL check that given request can be applied to resource
+ *
+ * @param[in] endPoint          cloud host and port
+ * @param[in] callback          result callback
+ * @return  OCStackResult application result
+ */
+OCStackResult OCWrapperAclPolicyCheck(const OCDevAddr *endPoint, OCCloudResponseCB callback);
+
+/**
+ * Read user input (expect string value)
+ *
+ * @param[out] item           string item to fill
+ * @param[in] length          max allowed string length
+ * @param[in] description     item description
+ * @param[in] example         item example
+ */
+void readString(char* item, int length, const char* description, const char* example);
+
+/**
+ * Read user input (expect integer value)
+ *
+ * @param[out] item           integer item to fill
+ * @param[in] description     item description
+ * @param[in] example         item example
+ */
+void readInteger(int* item, const char* description, const char* example);
+
+
+#endif //OC_CLOUD_WRAPPER_H
diff --git a/resource/csdk/security/provisioning/sample/cloudClient.c b/resource/csdk/security/provisioning/sample/cloudClient.c
new file mode 100644 (file)
index 0000000..78a5ea0
--- /dev/null
@@ -0,0 +1,523 @@
+//******************************************************************
+//
+// Copyright 2016 Samsung Electronics 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "ocstack.h"
+#include "logger.h"
+#include "camutex.h"
+#include "cathreadpool.h"
+#include "ocpayload.h"
+#include "payload_logging.h"
+#include "ocprovisioningmanager.h"
+
+#include "utils.h"
+#include "cloudAuth.h"
+#include "cloudWrapper.h"
+#include "cloudDiscovery.h"
+
+#ifdef __unix__
+#include <unistd.h> //for unlink
+#endif
+
+#define TAG "cloudClient"
+
+#define DEFAULT_HOST            "10.113.68.85"//"127.0.0.1"
+#define DEFAULT_PORT            OC_MULTICAST_PORT
+#define DEFAULT_DEVICEID        "6A757374-776F-726B-4465-765575696430"
+#define DEFAULT_USERID          "6A757374-776F-726B-4465-765575696430"
+#define DEFAULT_AUTH_PROVIDER   "github"
+#define DEFAULT_DB_FILE         "./cloud.dat"
+#define DEFAULT_RESPONSE_WAIT_TIME (10 * 1000000) //10s
+
+#define GITHUB_AUTH_LINK        "https://github.com/login?return_to=%2Flogin%2Foauth%2Fauthorize%3Fclient_id%3Dea9c18f540323b0213d0%26redirect_uri%3Dhttp%253A%252F%252Fwww.example.com%252Foauth_callback%252F"
+
+static bool fExit = false;
+
+static OCDevAddr endPoint;
+static char token[1024];
+static char authProvider[1024];
+static char *fname = DEFAULT_DB_FILE;
+static uint64_t timeout;
+static uint16_t g_credId = 0;
+
+oc_cond cond;
+oc_mutex mutex;
+
+typedef enum {
+    SIGN_UP       = 1,
+    SIGN_IN       = 2,
+    SIGN_OUT      = 3,
+
+    HOST          = 4,
+    PORT          = 5,
+    DB_FILE       = 6,
+    AUTH_PROVIDER = 7,
+    USE_RSA = 8,
+    SAVE_TRUST_CERT = 9,
+    USE_SECURE_CONN = 10,
+
+    DISCOVERY     = 13,
+    GET           = 14,
+    PUT           = 15,
+    POST          = 16,
+
+    CSR_SIGN      = 19,
+
+    CRL_GET       = 20,
+    CRL_POST      = 21,
+
+    ACL_ID_CREATE = 30,
+    ACL_ID_GET_BY_DEVICE = 31,
+    ACL_ID_DELETE = 32,
+
+    ACL_INDIVIDUAL_GET_INFO = 40,
+    ACL_INDIVIDUAL_UPDATE_ACE = 41,
+    ACL_INDIVIDUAL_DELETE = 42,
+
+    ACL_GROUP_CREATE = 50,
+    ACL_GROUP_FIND   = 51,
+    ACL_GROUP_JOIN   = 52,
+    ACL_GROUP_OBSERVE= 53,
+    ACL_GROUP_DELETE = 54,
+
+    ACL_GROUP_SHARE_DEVICE  = 60,
+    ACL_GROUP_DELETE_DEVICE  = 61,
+    ACL_GROUP_GET_INFO  = 62,
+
+    ACL_POLICY_CHECK_REQUEST = 70,
+
+    ACL_GROUP_INVITE_USER = 80,
+    ACL_GROUP_GET_INVITE  = 81,
+    ACL_GROUP_DELETE_INVITE  = 82,
+    ACL_GROUP_CANCEL_INVITE  = 83,
+
+    EXIT          = 99
+}CloudRequest;
+
+void printMenu()
+{
+    printf("************************************************************\n");
+    printf("****************** Cloud Client Requests *******************\n");
+    printf("************************************************************\n");
+    printf("** AUTHORIZATION\n");
+    printf("** %d - Sign Up request\n", SIGN_UP);
+    printf("** %d - Sign In request\n", SIGN_IN);
+    printf("** %d - Sign Out request\n", SIGN_OUT);
+
+    printf("** SETTINGS \n");
+    printf("** %d - Change default host\n", HOST);
+    printf("** %d - Change default port\n", PORT);
+    printf("** %d - Change default database filename\n", DB_FILE);
+    printf("** %d - Change default auth provider\n", AUTH_PROVIDER);
+    printf("** %d - Change TLS cipher suite to RSA\n", USE_RSA);
+    printf("** %d - Save Trust Cert. Chain into Cred of SVR\n", SAVE_TRUST_CERT);
+    printf("** %d - Change Protocol type (CoAP/CoAPs)\n", USE_SECURE_CONN);
+
+    printf("** DISCOVERY\n");
+    printf("** %d - Start Discovery\n", DISCOVERY);
+    printf("** %d - Get Request\n", GET);
+    printf("** %d - Put Request\n", PUT);
+    printf("** %d - Post Request\n", POST);
+
+    printf("** CERTIFICATE REQUEST\n");
+    printf("** %d - Certificate Request\n", CSR_SIGN);
+
+    printf("** CRL\n");
+    printf("** %d - CRL GET Request\n", CRL_GET);
+    printf("** %d - CRL POST Request\n", CRL_POST);
+
+    printf("** ACL MANAGER\n");
+    printf("** %d - ACL id create Request\n", ACL_ID_CREATE);
+    printf("** %d - ACL id retrieve by device Request\n", ACL_ID_GET_BY_DEVICE);
+    printf("** %d - ACL id delete Request\n", ACL_ID_DELETE);
+
+    printf("** ACL INDIVIDUAL\n");
+    printf("** %d - ACL individual get info Request\n", ACL_INDIVIDUAL_GET_INFO);
+    printf("** %d - ACL individual update ACE Request\n", ACL_INDIVIDUAL_UPDATE_ACE);
+    printf("** %d - ACL individual delete Request\n", ACL_INDIVIDUAL_DELETE);
+
+    printf("** ACL GROUP MANAGER\n");
+    printf("** %d - ACL Create Group Request\n", ACL_GROUP_CREATE);
+    printf("** %d - ACL Find Group Request\n", ACL_GROUP_FIND);
+    printf("** %d - ACL Join to invited Group Request\n", ACL_GROUP_JOIN);
+    printf("** %d - ACL Observe Group Request\n", ACL_GROUP_OBSERVE);
+    printf("** %d - ACL Delete Group Request\n", ACL_GROUP_DELETE);
+
+    printf("** ACL INDIVIDUAL GROUP\n");
+    printf("** %d - ACL Share device into Group Request\n", ACL_GROUP_SHARE_DEVICE);
+    printf("** %d - ACL Delete device from Group Request\n", ACL_GROUP_DELETE_DEVICE);
+    printf("** %d - ACL Get Group Info Request\n", ACL_GROUP_GET_INFO);
+
+    printf("** ACL POLICY ENFORCEMENT\n");
+    printf("** %d - ACL Check Permissions Request\n", ACL_POLICY_CHECK_REQUEST);
+
+    printf("** ACL MEMBER INVITATION\n");
+    printf("** %d - ACL Invite user to group Request\n", ACL_GROUP_INVITE_USER);
+    printf("** %d - ACL Retrieve invitation Request\n", ACL_GROUP_GET_INVITE);
+    printf("** %d - ACL Delete invitation Request\n", ACL_GROUP_DELETE_INVITE);
+    printf("** %d - ACL Cancel invitation Request\n", ACL_GROUP_CANCEL_INVITE);
+
+    printf("** EXIT\n");
+    printf("** %d - Exit cloud client\n\n", EXIT);
+    printf("************************************************************\n");
+
+    printf(">> Enter Menu number:\n");
+}
+
+void unlockMenu(void *data)
+{
+    OICFree(data);
+
+    oc_mutex_lock(mutex);
+    oc_cond_signal(cond);
+    oc_mutex_unlock(mutex);
+}
+
+/**
+ * This is default callback to all requests
+ * Used to sync with main menu
+ *
+ * @param[in] ctx          context
+ * @param[in] result       result
+ * @param[in] data         data
+ */
+static void handleCB(void* ctx, OCStackResult result, void* data)
+{
+    OC_UNUSED(ctx);
+    OC_UNUSED(data);
+
+    OIC_LOG_V(INFO, TAG, "%s: Received result = %d", __func__, result);
+
+    unlockMenu(NULL);
+}
+
+static int saveTrustCert(void)
+{
+    OCStackResult res = OC_STACK_ERROR;
+    OIC_LOG(INFO, TAG, "Save Trust Cert. Chain into Cred of SVR");
+
+    ByteArray trustCertChainArray = {0, 0};
+
+    FILE *fp = fopen("rootca.crt", "rb+");
+
+    if (fp)
+    {
+        size_t fsize;
+        if (fseeko(fp, 0, SEEK_END) == 0 && (fsize = ftello(fp)))
+        {
+            trustCertChainArray.data = OICCalloc(1, fsize+1);
+            trustCertChainArray.len = fsize+1;
+            if (NULL == trustCertChainArray.data)
+            {
+                OIC_LOG(ERROR,TAG,"OICCalloc");
+                fclose(fp);
+                return res;
+            }
+            rewind(fp);
+            fsize = fread(trustCertChainArray.data, 1, fsize, fp);
+            fclose(fp);
+        }
+    }
+    OIC_LOG_BUFFER(DEBUG, TAG, trustCertChainArray.data, trustCertChainArray.len);
+
+    res = OCSaveTrustCertChain(trustCertChainArray.data, trustCertChainArray.len, OIC_ENCODING_PEM,&g_credId);
+
+    if(OC_STACK_OK != res)
+    {
+        OIC_LOG(ERROR, TAG, "OCSaveTrustCertChainBin API error");
+        return res;
+    }
+    OIC_LOG_V(INFO, TAG, "CredId of Saved Trust Cert. Chain into Cred of SVR : %d.\n", g_credId);
+
+    return res;
+}
+
+static void userRequests()
+{
+    //defaults
+    memset(token, 0, sizeof(token));
+    memset(authProvider, 0, sizeof(authProvider));
+    strncpy(authProvider, DEFAULT_AUTH_PROVIDER, sizeof(authProvider));
+    memset(&endPoint, 0, sizeof(endPoint));
+    strncpy(endPoint.addr, DEFAULT_HOST, sizeof(endPoint.addr));
+    endPoint.port = DEFAULT_PORT;
+
+    mutex = oc_mutex_new();
+    cond = oc_cond_new();
+
+    while (false == fExit)
+    {
+        OCStackResult res = OC_STACK_ERROR;
+        timeout = DEFAULT_RESPONSE_WAIT_TIME;
+        //startup report
+        printf("-----------------------------------------------------------\n");
+        printf("Connecting to: %s:%d\n", endPoint.addr, endPoint.port);
+        printf("via auth provider: %s\n", authProvider);
+        printf("srv file: %s\n", fname);
+        printf("CoAP prefix: %s\n", DEFAULT_PREFIX);
+        printf("-----------------------------------------------------------\n");
+
+        printMenu();
+
+        int request = 0;
+        scanf("%d", &request);
+
+        switch (request)
+        {
+        case SIGN_UP:
+            if (0 == strncmp(authProvider, DEFAULT_AUTH_PROVIDER, sizeof(authProvider)))
+            {
+                printf("Paste to browser %s and get auth code\n", GITHUB_AUTH_LINK);
+            }
+            readString(token, sizeof(token), "auth token", "check link above");
+            res = CloudSignUp(&endPoint, authProvider, token);
+            break;
+        case SIGN_IN:
+            res = CloudSignIn(&endPoint);
+            break;
+        case SIGN_OUT:
+            res = CloudSignOut(&endPoint);
+            break;
+        case HOST:
+            readString(endPoint.addr, sizeof(endPoint.addr), "host ip address", DEFAULT_HOST);
+            break;
+        case PORT:
+        {
+            char example[8];
+            snprintf(example, sizeof(example), "%d", DEFAULT_PORT);
+            int tmp = 0;
+            readInteger(&tmp, "port number", example);
+            endPoint.port = tmp;
+        }
+        break;
+        case CRL_GET:
+            res = OCWrapperGetCRL(&endPoint, handleCB);
+            break;
+        case CRL_POST:
+            res = OCWrapperPostCRL(&endPoint, handleCB);
+            break;
+        case ACL_GROUP_CREATE:
+            res = OCWrapperAclCreateGroup(&endPoint, handleCB);
+            break;
+        case ACL_GROUP_FIND:
+            res = OCWrapperAclFindMyGroup(&endPoint, handleCB);
+            break;
+        case ACL_GROUP_DELETE:
+            res = OCWrapperAclDeleteGroup(&endPoint, handleCB);
+            break;
+        case ACL_GROUP_JOIN:
+            res = OCWrapperAclJoinToInvitedGroup(&endPoint, handleCB);
+            break;
+        case ACL_GROUP_OBSERVE:
+            res = OCWrapperAclObserveGroup(&endPoint, handleCB);
+            break;
+        case ACL_GROUP_SHARE_DEVICE:
+            res = OCWrapperAclShareDeviceIntoGroup(&endPoint, handleCB);
+            break;
+        case ACL_GROUP_DELETE_DEVICE:
+            res = OCWrapperAclDeleteDeviceFromGroup(&endPoint, handleCB);
+            break;
+        case ACL_GROUP_GET_INFO:
+            res = OCWrapperAclGroupGetInfo(&endPoint, handleCB);
+            break;
+        case ACL_GROUP_INVITE_USER:
+            res = OCWrapperAclInviteUser(&endPoint, handleCB);
+            break;
+        case ACL_GROUP_GET_INVITE:
+            res = OCWrapperAclGetInvitation(&endPoint, handleCB);
+            break;
+        case ACL_GROUP_DELETE_INVITE:
+            res = OCWrapperAclDeleteInvitation(&endPoint, handleCB);
+            break;
+        case ACL_GROUP_CANCEL_INVITE:
+            res = OCWrapperAclCancelInvitation(&endPoint, handleCB);
+            break;
+        case ACL_POLICY_CHECK_REQUEST:
+            res = OCWrapperAclPolicyCheck(&endPoint, handleCB);
+            break;
+        case ACL_ID_GET_BY_DEVICE:
+            res = OCWrapperAclIdGetByDevice(&endPoint, handleCB);
+            break;
+        case ACL_ID_CREATE:
+            res = OCWrapperAclIdCreate(&endPoint, handleCB);
+            break;
+        case ACL_ID_DELETE:
+            res = OCWrapperAclIdDelete(&endPoint, handleCB);
+            break;
+        case ACL_INDIVIDUAL_GET_INFO:
+            res = OCWrapperAclIndividualGetInfo(&endPoint, handleCB);
+            break;
+        case ACL_INDIVIDUAL_UPDATE_ACE:
+            res = OCWrapperAclIndividualUpdateAce(&endPoint, handleCB);
+            break;
+        case ACL_INDIVIDUAL_DELETE:
+            res = OCWrapperAclIndividualDelete(&endPoint, handleCB);
+            break;
+        case CSR_SIGN:
+            res = OCWrapperCertificateIssueRequest(&endPoint, handleCB);
+            break;
+        case DISCOVERY:
+            res = InitDiscovery();
+            break;
+        case GET:
+            res = InitRequest(OC_REST_GET);
+            break;
+        case PUT:
+            res= InitRequest(OC_REST_PUT);
+            break;
+        case POST:
+            res= InitRequest(OC_REST_POST);
+            break;
+        case USE_RSA:
+            CASelectCipherSuite(0x35, CA_ADAPTER_TCP);
+            break;
+        case SAVE_TRUST_CERT:
+            saveTrustCert();
+            break;
+        case USE_SECURE_CONN:
+        {
+            int tmp = 0;
+            readInteger(&tmp, "CoAP protocol type", "0 - non-secure, 1 - secure");
+            setCoapPrefix(0 == tmp ? false : true);
+        }
+            break;
+        case EXIT:
+            oc_mutex_free(mutex);
+            oc_cond_free(cond);
+            fExit = true;
+            break;
+        default:
+            printf(">> Entered Wrong Menu Number. Please Enter Again\n\n");
+            break;
+        }
+
+        //if requests were sent then wait response
+        if (res == OC_STACK_OK)
+        {
+            oc_mutex_lock(mutex);
+            oc_cond_wait_for(cond, mutex, timeout);
+            oc_mutex_unlock(mutex);
+        }
+    }
+}
+
+FILE* server_fopen(const char *path, const char *mode)
+{
+    OC_UNUSED(path);
+    return fopen(fname, mode);
+}
+
+/**
+ * Check file accessibility
+ *
+ * @param[in] name        file path
+ * @return true           if check was successful
+ */
+static bool checkConfig(const char *name)
+{
+    FILE* file = fopen(name, "rb");
+
+    if (file)
+    {
+        fclose(file);
+        return true;
+    }
+    return false;
+}
+
+static void printUsage(char *name)
+{
+    printf("Wrong arguments count!\n");
+    printf("Usage : %s <database_filename>\n", name);
+    printf("Examples : 1) %s 2) %s cloud.dat\n", name, name);
+}
+
+//==============================================================
+int main(int argc, char *argv[])
+{
+    OC_UNUSED(argc);
+    OC_UNUSED(argv);
+
+    if (2 == argc)
+    {
+        fname = argv[1];
+
+        if (!checkConfig(fname))
+        {
+            OIC_LOG_V(ERROR, TAG, "Can't open database file %s, exit!", fname);
+            return -1;
+        }
+    }
+    else if (argc > 2)
+    {
+        printUsage(argv[0]);
+    }
+
+    //Initialize Persistent Storage for SVR database
+    OCPersistentStorage ps = {server_fopen, fread, fwrite, fclose, unlink};
+
+    OCRegisterPersistentStorageHandler(&ps);
+
+    OCMode stackMode = OC_CLIENT_SERVER;
+    if (OCInit(NULL, 0, stackMode) != OC_STACK_OK)
+    {
+        OIC_LOG(ERROR, TAG, "OCStack init error, exit\n");
+        return 1;
+    }
+
+    ca_thread_pool_t g_threadPoolHandle = NULL;
+    CAResult_t res = ca_thread_pool_init(1, &g_threadPoolHandle);
+    if (CA_STATUS_OK != res)
+    {
+        OIC_LOG(ERROR, TAG, "thread pool initialize error.");
+        return res;
+    }
+
+    res = ca_thread_pool_add_task(g_threadPoolHandle, userRequests, NULL);
+    if (CA_STATUS_OK != res)
+    {
+        OIC_LOG(ERROR, TAG, "thread pool add task error.");
+        goto error;
+    }
+
+    while(false == fExit)
+    {
+        if (OCProcess() != OC_STACK_OK)
+        {
+            OIC_LOG(ERROR, TAG,"OCProcess process error, exit\n");
+            return 2;
+        }
+    }
+
+    if (OCStop() != OC_STACK_OK)
+    {
+        OIC_LOG(ERROR, TAG, "OCStop process error\n");
+    }
+
+    error:
+    if (g_threadPoolHandle)
+    {
+        ca_thread_pool_free(g_threadPoolHandle);
+    }
+
+    return 0;
+}
index b0454ee..473551e 100644 (file)
  *
  *****************************************************************/
 
+#include "iotivity_config.h"
+
 #include <stdio.h>
 #include <string.h>
 #ifdef HAVE_UNISTD_H
 #include <unistd.h>
 #endif
 
-#include "platform_features.h"
 #include "utlist.h"
 #include "logger.h"
 #include "oic_malloc.h"
@@ -596,7 +597,7 @@ static int provisionCred(void)
 
     // display the CRED-provisioned result
     printf("   > Provisioned Selected Pairwise Crendentials\n");
-    printf("   > Please Check Device's Status for the Linked Result, with [33] Menu\n");
+    printf("   > Please Check Device's Status for the Linked Result, with [34] Menu\n");
 
     return 0;
 }
diff --git a/resource/csdk/security/provisioning/sample/rootca.crt b/resource/csdk/security/provisioning/sample/rootca.crt
new file mode 100644 (file)
index 0000000..54ec780
--- /dev/null
@@ -0,0 +1,19 @@
+-----BEGIN CERTIFICATE-----
+MIIC/jCCAeYCAQEwDQYJKoZIhvcNAQELBQAwRTELMAkGA1UEBhMCQVUxEzARBgNV
+BAgMClNvbWUtU3RhdGUxITAfBgNVBAoMGEludGVybmV0IFdpZGdpdHMgUHR5IEx0
+ZDAeFw0xNjA2MjgwNTMzNThaFw0yNjA2MjYwNTMzNThaMEUxCzAJBgNVBAYTAkFV
+MRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBXaWRnaXRz
+IFB0eSBMdGQwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC1HHkfMG9c
+BJ7ZeCIBKe7pSjpptvi+hzpdV72W7szpWDlTQdUaRxKL9aoNxbyuF5OL8xAQ9s28
+IqIxdPW7X3JAmkLigzMCo2xtXHz/OyvomU6fhibneQw5De+iUoD68zdG+/k1NcAW
+xx+VEAMw4fvZvYSVEQ1aKFnjtrQ8o6Zfe5+MRTvBq+G0+jwZWJEoKbpxIPpNWPGx
+AV17tEpe+lg27jEYDYG1QUiL2TG80ZjQQL95OjETYf8EIxoqrKHvHCvDin0zdd+E
+qPN0Y+Rhkl3PYoxWm7d8z0p1mD7lcwOMvy1KgEgtJ7SHy0D2SIW/KaDox/kRPC1P
+ksFeAS2B0Z9zAgMBAAEwDQYJKoZIhvcNAQELBQADggEBAAtHjimMywXn893Ifu1v
+tNnL9ITMpQhsHAlg1QBVEyjGZLIjUgMhsWljVwTC1PdBrO7V0ElYbeV+LKYGwDk6
+fjBJogCLgZiUw18F8TjHC/qDsoWEsm1iB4KcTZkk0nm/2vidHK0TMLzCohR71/vN
+KS2rtiQDYGKe9EzjNSO3GlCWkVTYtJNhALa/BfDza5keRkwmldJYhlx4rQH5yVRn
+t5k87vjX0h7m8MzIwiAb2s/b9XBlM1FuFx3FxcVjBl7KtUAU7twU8v5LenjWDSH1
+D1jnKiZUUspgovhosPRqmxGNXldaX1E+RJmxdtqUVg4co/zjAbTY7C+7ZYIZBo46
+Ll0=
+-----END CERTIFICATE-----
index adec06f..fcf752d 100644 (file)
@@ -20,6 +20,7 @@
 ///////////////////////////////////////////////////////////////////////
 //NOTE :  This sample server is generated based on ocserverbasicops.cpp
 ///////////////////////////////////////////////////////////////////////
+#include "iotivity_config.h"
 #include <stdio.h>
 #include <string.h>
 #include <stdlib.h>
index 06a5512..56156ba 100644 (file)
@@ -20,6 +20,7 @@
 ///////////////////////////////////////////////////////////////////////
 //NOTE :  This sample server is generated based on ocserverbasicops.cpp
 ///////////////////////////////////////////////////////////////////////
+#include "iotivity_config.h"
 #include <stdio.h>
 #include <string.h>
 #include <stdlib.h>
diff --git a/resource/csdk/security/provisioning/src/cloud/aclgroup.c b/resource/csdk/security/provisioning/src/cloud/aclgroup.c
new file mode 100644 (file)
index 0000000..ea38b53
--- /dev/null
@@ -0,0 +1,305 @@
+#include <string.h>
+#include <stdio.h>
+#include <stdlib.h>
+
+#include "utils.h"
+
+#include "oic_malloc.h"
+#include "logger.h"
+#include "ocstack.h"
+#include "ocpayload.h"
+#include "pmutility.h"
+#include "cacommonutil.h"
+
+#define TAG "CLOUD-ACL-GROUP"
+
+/**
+ * ACL create group request received data handler
+ *
+ * @param[in] ctx       context
+ * @param[out] data     data required to external application
+ * @param[in] response  peer response
+ * @return  OCStackResult application result
+ */
+static OCStackResult handleAclCreateGroupResponse(void *ctx, void **data, OCClientResponse *response)
+{
+    OC_UNUSED(ctx);
+    if (NULL == response->payload)
+    {
+        OIC_LOG(ERROR, TAG, "Receive NULL payload");
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    char *gid = NULL;
+
+    if (!OCRepPayloadGetPropString((const OCRepPayload *)response->payload, OC_RSRVD_GROUP_ID, &gid))
+    {
+        OIC_LOG_V(ERROR, TAG, "Can't get: %s", OC_RSRVD_GROUP_ID);
+        return OC_STACK_MALFORMED_RESPONSE;
+    }
+
+    *data = gid;
+    return OC_STACK_OK;
+}
+
+/**
+ * ACL find my group received data handler
+ *
+ * @param[in] ctx       context
+ * @param[out] data     data required to external application
+ * @param[in] response  peer response
+ * @return  OCStackResult application result
+ */
+static OCStackResult handleAclFindMyGroupResponse(void *ctx, void **data, OCClientResponse *response)
+{
+    OC_UNUSED(ctx);
+    if (NULL == response->payload)
+    {
+        OIC_LOG(ERROR, TAG, "Receive NULL payload");
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    const OCRepPayload *payload = (const OCRepPayload *)response->payload;
+    size_t dimensions[MAX_REP_ARRAY_DEPTH] = { 0 };
+
+    stringArray_t *gidlist = OICCalloc(1, sizeof(stringArray_t));
+    if (NULL == gidlist)
+    {
+        OIC_LOG(ERROR, TAG, "Can't allocate gidlist");
+        return OC_STACK_NO_MEMORY;
+    }
+
+    if (!OCRepPayloadGetStringArray(payload, OC_RSRVD_GROUP_ID_LIST, &gidlist->array, dimensions))
+    {
+        OIC_LOG_V(ERROR, TAG, "Can't get: %s", OC_RSRVD_GROUP_ID_LIST);
+        OICFree(gidlist);
+        return OC_STACK_MALFORMED_RESPONSE;
+    }
+
+    gidlist->length = calcDimTotal(dimensions);
+
+    *data = gidlist;
+    return OC_STACK_OK;
+}
+
+OCStackResult OCCloudAclCreateGroup(void* ctx,
+                                    const char *groupType,
+                                    const char *groupMasterId,
+                                    const OCDevAddr *endPoint,
+                                    OCCloudResponseCB callback)
+{
+    char uri[MAX_URI_LENGTH] = { 0 };
+
+    VERIFY_NON_NULL_RET(groupType, TAG, "NULL input param", OC_STACK_INVALID_PARAM);
+
+    snprintf(uri, MAX_URI_LENGTH, "%s%s:%d%s", DEFAULT_PREFIX,
+            endPoint->addr, endPoint->port, OC_RSRVD_ACL_GROUP_URL);
+
+    OCCallbackData cbData;
+    fillCallbackData(&cbData, ctx, callback, handleAclCreateGroupResponse, NULL);
+
+    OCRepPayload *payload = OCRepPayloadCreate();
+    if (!payload)
+    {
+        return OC_STACK_NO_MEMORY;
+    }
+
+    OCRepPayloadSetPropString(payload, OC_RSRVD_GROUP_TYPE, groupType);
+
+    //add next fields if they were filled
+    if (groupMasterId) OCRepPayloadSetPropString(payload, OC_RSRVD_GROUP_MASTER_ID, groupMasterId);
+
+    return OCDoResource(NULL, OC_REST_POST, uri, NULL, (OCPayload *)payload,
+                        CT_ADAPTER_TCP, OC_LOW_QOS, &cbData, NULL, 0);
+}
+
+OCStackResult OCCloudAclFindMyGroup(void* ctx,
+                                    const char *memberId,
+                                    const OCDevAddr *endPoint,
+                                    OCCloudResponseCB callback)
+{
+    char uri[MAX_URI_LENGTH] = { 0 };
+
+    snprintf(uri, MAX_URI_LENGTH, "%s%s:%d%s", DEFAULT_PREFIX,
+            endPoint->addr, endPoint->port, OC_RSRVD_ACL_GROUP_URL);
+
+    if (memberId)
+    {
+        size_t len = strlen(uri);
+        snprintf(uri + len, MAX_URI_LENGTH - len, "?%s=%s", OC_RSRVD_MEMBER_ID, memberId);
+    }
+
+    OCCallbackData cbData;
+    fillCallbackData(&cbData, ctx, callback, handleAclFindMyGroupResponse, NULL);
+
+    return OCDoResource(NULL, OC_REST_GET, uri, NULL, NULL,
+                        CT_ADAPTER_TCP, OC_LOW_QOS, &cbData, NULL, 0);
+}
+
+OCStackResult OCCloudAclDeleteGroup(void* ctx,
+                                    const char *groupId,
+                                    const char *groupMasterId,
+                                    const OCDevAddr *endPoint,
+                                    OCCloudResponseCB callback)
+{
+    char uri[MAX_URI_LENGTH] = { 0 };
+
+    VERIFY_NON_NULL_RET(groupId, TAG, "NULL input param", OC_STACK_INVALID_PARAM);
+
+    snprintf(uri, MAX_URI_LENGTH, "%s%s:%d%s?%s=%s", DEFAULT_PREFIX,
+            endPoint->addr, endPoint->port, OC_RSRVD_ACL_GROUP_URL, OC_RSRVD_GROUP_ID, groupId);
+
+    if (groupMasterId)
+    {
+        size_t len = strlen(uri);
+        snprintf(uri + len, MAX_URI_LENGTH - len, "&%s=%s", OC_RSRVD_GROUP_MASTER_ID, groupMasterId);
+    }
+
+    OCCallbackData cbData;
+    fillCallbackData(&cbData, ctx, callback, NULL, NULL);
+
+    return OCDoResource(NULL, OC_REST_DELETE, uri, NULL, NULL,
+                        CT_ADAPTER_TCP, OC_LOW_QOS, &cbData, NULL, 0);
+}
+
+OCStackResult OCCloudAclJoinToInvitedGroup(void* ctx,
+                                           const char *groupId,
+                                           const OCDevAddr *endPoint,
+                                           OCCloudResponseCB callback)
+{
+    char uri[MAX_URI_LENGTH] = { 0 };
+
+    VERIFY_NON_NULL_RET(groupId, TAG, "NULL input param", OC_STACK_INVALID_PARAM);
+
+    snprintf(uri, MAX_URI_LENGTH, "%s%s:%d%s/%s", DEFAULT_PREFIX,
+            endPoint->addr, endPoint->port, OC_RSRVD_ACL_GROUP_URL, groupId);
+
+    OCCallbackData cbData;
+    fillCallbackData(&cbData, ctx, callback, NULL, NULL);
+
+    return OCDoResource(NULL, OC_REST_POST, uri, NULL, NULL,
+                        CT_ADAPTER_TCP, OC_LOW_QOS, &cbData, NULL, 0);
+}
+
+OCStackResult OCCloudAclObserveGroup(void* ctx,
+                                     const char *groupId,
+                                     const OCDevAddr *endPoint,
+                                     OCCloudResponseCB callback)
+{
+    char uri[MAX_URI_LENGTH] = { 0 };
+
+    VERIFY_NON_NULL_RET(groupId, TAG, "NULL input param", OC_STACK_INVALID_PARAM);
+
+    snprintf(uri, MAX_URI_LENGTH, "%s%s:%d%s/%s", DEFAULT_PREFIX,
+            endPoint->addr, endPoint->port, OC_RSRVD_ACL_GROUP_URL, groupId);
+
+    OCCallbackData cbData;
+    fillCallbackData(&cbData, ctx, callback, NULL, NULL);
+
+    return OCDoResource(NULL, OC_REST_OBSERVE, uri, NULL, NULL,
+                        CT_ADAPTER_TCP, OC_LOW_QOS, &cbData, NULL, 0);
+}
+
+OCStackResult OCCloudAclShareDeviceIntoGroup(void* ctx,
+                                             const char *groupId,
+                                             const stringArray_t *memberIds,
+                                             const stringArray_t *deviceIds,
+                                             const OCDevAddr *endPoint,
+                                             OCCloudResponseCB callback)
+{
+    size_t dimensions[MAX_REP_ARRAY_DEPTH] = { 0 };
+    char uri[MAX_URI_LENGTH] = { 0 };
+
+    VERIFY_NON_NULL_RET(groupId, TAG, "NULL input param", OC_STACK_INVALID_PARAM);
+    VERIFY_NON_NULL_RET(memberIds, TAG, "NULL input param", OC_STACK_INVALID_PARAM);
+    VERIFY_NON_NULL_RET(deviceIds, TAG, "NULL input param", OC_STACK_INVALID_PARAM);
+
+    snprintf(uri, MAX_URI_LENGTH, "%s%s:%d%s/%s", DEFAULT_PREFIX,
+            endPoint->addr, endPoint->port, OC_RSRVD_ACL_GROUP_URL, groupId);
+
+    OCCallbackData cbData;
+    fillCallbackData(&cbData, ctx, callback, NULL, NULL);
+
+    OCRepPayload *payload = OCRepPayloadCreate();
+    if (!payload)
+    {
+        return OC_STACK_NO_MEMORY;
+    }
+
+    dimensions[0] = memberIds->length;
+    OCRepPayloadSetStringArray(payload, OC_RSRVD_MEMBER_ID_LIST,
+                               (const char **)memberIds->array, dimensions);
+    dimensions[0] = deviceIds->length;
+    OCRepPayloadSetStringArray(payload, OC_RSRVD_DEVICE_ID_LIST,
+                               (const char **)deviceIds->array, dimensions);
+
+    return OCDoResource(NULL, OC_REST_POST, uri, NULL, (OCPayload *)payload,
+                        CT_ADAPTER_TCP, OC_LOW_QOS, &cbData, NULL, 0);
+}
+
+OCStackResult OCCloudAclDeleteDeviceFromGroup(void* ctx,
+                                              const char *groupId,
+                                              const stringArray_t *memberIds,
+                                              const stringArray_t *deviceIds,
+                                              const OCDevAddr *endPoint,
+                                              OCCloudResponseCB callback)
+
+{
+    char uri[MAX_URI_LENGTH * 4] = { 0 };
+    int max_size = sizeof(uri);
+
+    VERIFY_NON_NULL_RET(groupId, TAG, "NULL input param", OC_STACK_INVALID_PARAM);
+    VERIFY_NON_NULL_RET(memberIds, TAG, "NULL input param", OC_STACK_INVALID_PARAM);
+    VERIFY_NON_NULL_RET(deviceIds, TAG, "NULL input param", OC_STACK_INVALID_PARAM);
+
+    snprintf(uri, max_size, "%s%s:%d%s/%s", DEFAULT_PREFIX,
+            endPoint->addr, endPoint->port, OC_RSRVD_ACL_GROUP_URL, groupId);
+
+    for (size_t i = 0; i < memberIds->length; i++)
+    {
+        size_t len = strlen(uri);
+        snprintf(uri + len, max_size - len, "%c%s=%s", (0 == i)?'?':'&',
+                OC_RSRVD_MEMBER_ID_LIST, memberIds->array[i]);
+    }
+
+    for (size_t i = 0; i < deviceIds->length; i++)
+    {
+        size_t len = strlen(uri);
+        snprintf(uri + len, max_size - len, "%c%s=%s",
+                (0 == i && 0 == memberIds->length)?'?':'&',
+                OC_RSRVD_DEVICE_ID_LIST, deviceIds->array[i]);
+    }
+
+    OCCallbackData cbData;
+    fillCallbackData(&cbData, ctx, callback, NULL, NULL);
+
+    return OCDoResource(NULL, OC_REST_DELETE, uri, NULL, NULL,
+                        CT_ADAPTER_TCP, OC_LOW_QOS, &cbData, NULL, 0);
+}
+
+OCStackResult OCCloudAclGroupGetInfo(void* ctx,
+                                     const char *groupId,
+                                     const char *memberId,
+                                     const OCDevAddr *endPoint,
+                                     OCCloudResponseCB callback)
+{
+    char uri[MAX_URI_LENGTH] = { 0 };
+
+    VERIFY_NON_NULL_RET(groupId, TAG, "NULL input param", OC_STACK_INVALID_PARAM);
+
+    snprintf(uri, MAX_URI_LENGTH, "%s%s:%d%s/%s", DEFAULT_PREFIX,
+            endPoint->addr, endPoint->port, OC_RSRVD_ACL_GROUP_URL, groupId);
+
+    if (memberId)
+    {
+        size_t len = strlen(uri);
+        snprintf(uri + len, MAX_URI_LENGTH - len, "?%s=%s", OC_RSRVD_MEMBER_ID, memberId);
+    }
+
+    OCCallbackData cbData;
+    fillCallbackData(&cbData, ctx, callback, NULL, NULL);
+
+    return OCDoResource(NULL, OC_REST_GET, uri, NULL, NULL,
+                        CT_ADAPTER_TCP, OC_LOW_QOS, &cbData, NULL, 0);
+}
+
diff --git a/resource/csdk/security/provisioning/src/cloud/aclid.c b/resource/csdk/security/provisioning/src/cloud/aclid.c
new file mode 100644 (file)
index 0000000..e698e34
--- /dev/null
@@ -0,0 +1,321 @@
+#include "utils.h"
+
+#include "oic_malloc.h"
+#include "logger.h"
+#include "ocstack.h"
+#include "ocpayload.h"
+#include "pmutility.h"
+#include "cacommonutil.h"
+#include "aclresource.h"
+#include "ocpayloadcbor.h"
+#include "payload_logging.h"
+
+#define TAG "CLOUD-ACL-ID"
+
+/**
+ * ACL Id create request received data handler
+ *
+ * @param[in] ctx       context
+ * @param[out] data     data required to external application
+ * @param[in] response  peer response
+ * @return  OCStackResult application result
+ */
+static OCStackResult handleAclIdCreateResponse(void *ctx, void **data, OCClientResponse *response)
+{
+    OC_UNUSED(ctx);
+    if (NULL == response->payload)
+    {
+        OIC_LOG(ERROR, TAG, "Receive NULL payload");
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    char *aclid = NULL;
+
+    if (!OCRepPayloadGetPropString((const OCRepPayload *)response->payload, OC_RSRVD_ACL_ID, &aclid))
+    {
+        OIC_LOG_V(ERROR, TAG, "Can't get: %s", OC_RSRVD_ACL_ID);
+        return OC_STACK_MALFORMED_RESPONSE;
+    }
+
+    *data = aclid;
+    return OC_STACK_OK;
+}
+
+OCStackResult OCCloudAclIdGetByDevice(void* ctx,
+                                      const char *deviceId,
+                                      const OCDevAddr *endPoint,
+                                      OCCloudResponseCB callback)
+{
+    char uri[MAX_URI_LENGTH] = { 0 };
+
+    VERIFY_NON_NULL_RET(deviceId, TAG, "NULL input param", OC_STACK_INVALID_PARAM);
+
+    snprintf(uri, MAX_URI_LENGTH, "%s%s:%d%s?%s=%s", DEFAULT_PREFIX,
+            endPoint->addr, endPoint->port, OC_RSRVD_ACL_ID_URL, OC_RSRVD_DEVICE_ID, deviceId);
+
+    OCCallbackData cbData;
+    fillCallbackData(&cbData, ctx, callback, handleAclIdCreateResponse, NULL);
+
+    return OCDoResource(NULL, OC_REST_GET, uri, NULL, NULL,
+                        CT_ADAPTER_TCP, OC_LOW_QOS, &cbData, NULL, 0);
+}
+
+OCStackResult OCCloudAclIdCreate(void* ctx,
+                                 const char *ownerId,
+                                 const char *deviceId,
+                                 const OCDevAddr *endPoint,
+                                 OCCloudResponseCB callback)
+{
+    char uri[MAX_URI_LENGTH] = { 0 };
+
+    VERIFY_NON_NULL_RET(ownerId, TAG, "NULL input param", OC_STACK_INVALID_PARAM);
+    VERIFY_NON_NULL_RET(deviceId, TAG, "NULL input param", OC_STACK_INVALID_PARAM);
+
+    snprintf(uri, MAX_URI_LENGTH, "%s%s:%d%s?%s=%s&%s=%s", DEFAULT_PREFIX,
+            endPoint->addr, endPoint->port, OC_RSRVD_ACL_ID_URL,
+            OC_RSRVD_OWNER_ID, ownerId, OC_RSRVD_DEVICE_ID, deviceId);
+
+    OCCallbackData cbData;
+    fillCallbackData(&cbData, ctx, callback, handleAclIdCreateResponse, NULL);
+
+    return OCDoResource(NULL, OC_REST_PUT, uri, NULL, NULL,
+                        CT_ADAPTER_TCP, OC_LOW_QOS, &cbData, NULL, 0);
+}
+
+OCStackResult OCCloudAclIdDelete(void* ctx,
+                                 const char *aclId,
+                                 const OCDevAddr *endPoint,
+                                 OCCloudResponseCB callback)
+{
+    char uri[MAX_URI_LENGTH]  = { 0 };
+
+    VERIFY_NON_NULL_RET(aclId, TAG, "NULL input param", OC_STACK_INVALID_PARAM);
+
+    snprintf(uri, MAX_URI_LENGTH, "%s%s:%d%s?%s=%s", DEFAULT_PREFIX,
+            endPoint->addr, endPoint->port, OC_RSRVD_ACL_ID_URL, OC_RSRVD_ACL_ID, aclId);
+
+    OCCallbackData cbData;
+    fillCallbackData(&cbData, ctx, callback, NULL, NULL);
+
+    return OCDoResource(NULL, OC_REST_DELETE, uri, NULL, NULL,
+                        CT_ADAPTER_TCP, OC_LOW_QOS, &cbData, NULL, 0);
+}
+
+/**
+ * ACL Get Info received data handler
+ *
+ * @param[in] ctx       context
+ * @param[out] data     data required to external application
+ * @param[in] response  peer response
+ * @return  OCStackResult application result
+ */
+static OCStackResult handleAclGetInfoResponse(void *ctx, void **data, OCClientResponse *response)
+{
+    OCStackResult result = OC_STACK_OK;
+    uint8_t *cbor = NULL;
+    size_t size   = 0;
+
+    OC_UNUSED(ctx);
+    OC_UNUSED(data);
+
+    if (NULL == response->payload)
+    {
+        OIC_LOG(ERROR, TAG, "Receive NULL payload\n");
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    result = OCConvertPayload(response->payload, &cbor, &size);
+    if (result != OC_STACK_OK)
+    {
+        OIC_LOG(ERROR, TAG, "Can't convert OCPayload to cbor");
+        goto exit;
+    }
+
+    OicSecAcl_t* acl = CBORPayloadToAcl2(cbor, size);
+    if (NULL == acl)
+    {
+        OIC_LOG(ERROR, TAG, "Can't parse CBOR payload");
+        goto exit;
+    }
+
+    result = InstallNewACL2(acl);
+    if (result != OC_STACK_OK)
+    {
+        OIC_LOG(ERROR, TAG, "Can't update ACL resource");
+    }
+
+exit:
+    //can't delete acl because aces was added to gAcl
+    OICFree(cbor);
+    return result;
+}
+
+OCStackResult OCCloudAclIndividualGetInfo(void* ctx,
+                                          const char *aclId,
+                                          const OCDevAddr *endPoint,
+                                          OCCloudResponseCB callback)
+{
+    char uri[MAX_URI_LENGTH]  = { 0 };
+
+    VERIFY_NON_NULL_RET(aclId, TAG, "NULL input param", OC_STACK_INVALID_PARAM);
+
+    snprintf(uri, MAX_URI_LENGTH, "%s%s:%d%s/%s", DEFAULT_PREFIX,
+            endPoint->addr, endPoint->port, OC_RSRVD_ACL_ID_URL, aclId);
+
+    OCCallbackData cbData;
+    fillCallbackData(&cbData, ctx, callback, handleAclGetInfoResponse, NULL);
+
+    return OCDoResource(NULL, OC_REST_GET, uri, NULL, NULL,
+                        CT_ADAPTER_TCP, OC_LOW_QOS, &cbData, NULL, 0);
+}
+
+OCStackResult OCCloudAclIndividualUpdateAce(void* ctx,
+                                            const char *aclId,
+                                            const cloudAce_t *aces,
+                                            const OCDevAddr *endPoint,
+                                            OCCloudResponseCB callback)
+{
+    size_t dimensions[MAX_REP_ARRAY_DEPTH] = { 0 };
+    char uri[MAX_URI_LENGTH]  = { 0 };
+
+    int i = 0, j = 0;
+
+    OCRepPayload **helperPayload  = NULL;
+    OCRepPayload **helperPayload2 = NULL;
+
+    VERIFY_NON_NULL_RET(aclId, TAG, "NULL input param", OC_STACK_INVALID_PARAM);
+    VERIFY_NON_NULL_RET(aces, TAG, "NULL input param", OC_STACK_INVALID_PARAM);
+
+    snprintf(uri, MAX_URI_LENGTH, "%s%s:%d%s/%s", DEFAULT_PREFIX,
+            endPoint->addr, endPoint->port, OC_RSRVD_ACL_ID_URL, aclId);
+
+    OCRepPayload *payload = OCRepPayloadCreate();
+    if (!payload)
+    {
+        OIC_LOG_V(DEBUG, TAG, "Can't allocate memory for payload");
+        goto no_memory;
+    }
+
+    int acllist_count = 0;
+    if (aces)
+    {
+        cloudAce_t *ace = (cloudAce_t *)&aces[acllist_count++];
+        while (ace->next)
+        {
+            ace = ace->next;
+            acllist_count++;
+        }
+    }
+
+    helperPayload = OICCalloc(acllist_count, sizeof(OCRepPayload *));
+    if (!helperPayload)
+    {
+        OIC_LOG_V(DEBUG, TAG, "Can't allocate memory for helperPayload");
+        goto no_memory;
+    }
+
+    for (int i = 0; i < acllist_count; i++)
+    {
+        OCRepPayload *payload = OCRepPayloadCreate();
+        if (!payload)
+        {
+            OIC_LOG_V(DEBUG, TAG, "Can't allocate memory for helperPayload[i]");
+            goto no_memory;
+        }
+        helperPayload[i] = payload;
+
+        const cloudAce_t *ace = &aces[i];
+
+        OCRepPayloadSetPropString(payload, OC_RSRVD_ACE_ID, ace->aceId);
+        OCRepPayloadSetPropString(payload, OC_RSRVD_SUBJECT_UUID, (const char *)ace->subjectuuid.id);
+        OCRepPayloadSetPropInt(payload, OC_RSRVD_SUBJECT_TYPE, ace->stype);
+        OCRepPayloadSetPropInt(payload, OC_RSRVD_PERMISSION_MASK, ace->permission);
+
+        int reslist_count = 0;
+        if (ace->resources)
+        {
+            OicSecRsrc_t *res = &ace->resources[reslist_count++];
+            while (res->next)
+            {
+                res = res->next;
+                reslist_count++;
+            }
+        }
+
+        helperPayload2 = OICCalloc(reslist_count, sizeof(OCRepPayload *));
+        if (!helperPayload2)
+        {
+            goto no_memory;
+        }
+
+        for (int j = 0; j < reslist_count; j++)
+        {
+            OCRepPayload *payload = OCRepPayloadCreate();
+            if (!payload)
+            {
+                OIC_LOG_V(DEBUG, TAG, "Can't allocate memory for payload");
+                goto no_memory;
+            }
+            helperPayload2[j] = payload;
+
+            const OicSecRsrc_t *res = &ace->resources[j];
+
+            OCRepPayloadSetPropString(payload, OC_RSRVD_HREF, res->href);
+
+            dimensions[0] = res->typeLen;
+            OCRepPayloadSetStringArray(payload, OC_RSRVD_RESOURCE_TYPE,
+                                       (const char **)res->types, dimensions);
+
+            dimensions[0] = res->interfaceLen;
+            OCRepPayloadSetStringArray(payload, OC_RSRVD_INTERFACE,
+                                       (const char **)res->interfaces, dimensions);
+        }
+        dimensions[0] = reslist_count;
+        OCRepPayloadSetPropObjectArray(payload, OC_RSRVD_RESOURCES,
+                (const OCRepPayload **)helperPayload2, dimensions);
+    }
+    dimensions[0] = acllist_count;
+    OCRepPayloadSetPropObjectArray(payload, OC_RSRVD_ACCESS_CONTROL_LIST,
+            (const OCRepPayload **)helperPayload, dimensions);
+
+    OCCallbackData cbData;
+    fillCallbackData(&cbData, ctx, callback, NULL, NULL);
+
+    OIC_LOG(DEBUG, TAG, "Next payload created:");
+    OIC_LOG_PAYLOAD(DEBUG, (OCPayload *)payload);
+
+    return OCDoResource(NULL, OC_REST_POST, uri, NULL, (OCPayload *)payload,
+                        CT_ADAPTER_TCP, OC_LOW_QOS, &cbData, NULL, 0);
+no_memory:
+    if (helperPayload2)
+    {
+        for (int k = 0; k < j; k++) OCRepPayloadDestroy(helperPayload2[k]);
+        OICFree(helperPayload2);
+    }
+    if (helperPayload)
+    {
+        for (int k = 0; k < i; k++) OCRepPayloadDestroy(helperPayload[k]);
+        OICFree(helperPayload);
+    }
+    OCRepPayloadDestroy(payload);
+    return OC_STACK_NO_MEMORY;
+}
+
+OCStackResult OCCloudAclIndividualDelete(void* ctx,
+                                         const char *aclId,
+                                         const OCDevAddr *endPoint,
+                                         OCCloudResponseCB callback)
+{
+    char uri[MAX_URI_LENGTH]  = { 0 };
+
+    VERIFY_NON_NULL_RET(aclId, TAG, "NULL input param", OC_STACK_INVALID_PARAM);
+
+    snprintf(uri, MAX_URI_LENGTH, "%s%s:%d%s/%s", DEFAULT_PREFIX,
+            endPoint->addr, endPoint->port, OC_RSRVD_ACL_ID_URL, aclId);
+
+    OCCallbackData cbData;
+    fillCallbackData(&cbData, ctx, callback, NULL, NULL);
+
+    return OCDoResource(NULL, OC_REST_DELETE, uri, NULL, NULL,
+                        CT_ADAPTER_TCP, OC_LOW_QOS, &cbData, NULL, 0);
+}
diff --git a/resource/csdk/security/provisioning/src/cloud/aclinvite.c b/resource/csdk/security/provisioning/src/cloud/aclinvite.c
new file mode 100644 (file)
index 0000000..9b77374
--- /dev/null
@@ -0,0 +1,360 @@
+#include <string.h>
+#include <stdio.h>
+#include <stdlib.h>
+
+#include "occloudprovisioning.h"
+#include "utils.h"
+
+#include "oic_malloc.h"
+#include "logger.h"
+#include "ocstack.h"
+#include "ocpayload.h"
+#include "pmutility.h"
+#include "cacommonutil.h"
+
+#define TAG "CLOUD-ACL-INVITE"
+
+/**
+ * This helper function parses "name" : { "gid":[], "mid":[] } payload
+ *
+ * @param[in] payload     received payload
+ * @param[in] name        property name
+ * @param[out] out        string array pair to fill
+ * @return  OCStackResult application result
+ */
+static OCStackResult parseInvitePayload(const OCRepPayload *payload, const char *name, stringArrayPair_t *out)
+{
+    OCStackResult result = OC_STACK_NO_MEMORY;
+    size_t dimensions[MAX_REP_ARRAY_DEPTH] = { 0 };
+    OCRepPayload **heplerPayload  = NULL;
+    size_t i = 0;
+
+    if (!OCRepPayloadGetPropObjectArray(payload, name, &heplerPayload, dimensions))
+    {
+        OIC_LOG_V(ERROR, TAG, "Can't get: %s", name);
+        return OC_STACK_MALFORMED_RESPONSE;
+    }
+
+    int count = calcDimTotal(dimensions);
+
+    stringArray_t *gidlist = &out->gidlist;
+    stringArray_t *midlist = &out->midlist;
+
+    gidlist->length = count;
+    midlist->length = count;
+
+    gidlist->array = OICCalloc(gidlist->length, sizeof(char *));
+    if (NULL == gidlist->array)
+    {
+        OIC_LOG(ERROR, TAG, "Can't allocate gidlist->array");
+        goto exit;
+    }
+
+    midlist->array = OICCalloc(midlist->length, sizeof(char *));
+    if (NULL == midlist->array)
+    {
+        OIC_LOG(ERROR, TAG, "Can't allocate midlist->array");
+        goto exit;
+    }
+
+    for (i = 0; i < gidlist->length; i++)
+    {
+        const OCRepPayload *payload = heplerPayload[i];
+
+        if (!OCRepPayloadGetPropString(payload, OC_RSRVD_GROUP_ID, &gidlist->array[i]))
+        {
+            OIC_LOG_V(ERROR, TAG, "Can't get: %s", OC_RSRVD_GROUP_ID);
+            result = OC_STACK_MALFORMED_RESPONSE;
+            goto exit;
+        }
+
+        if (!OCRepPayloadGetPropString(payload, OC_RSRVD_MEMBER_ID, &midlist->array[i]))
+        {
+            OIC_LOG_V(ERROR, TAG, "Can't get: %s", OC_RSRVD_MEMBER_ID);
+            result = OC_STACK_MALFORMED_RESPONSE;
+            goto exit;
+        }
+        OCRepPayloadDestroy(heplerPayload[i]);
+    }
+
+    result = OC_STACK_OK;
+
+exit:
+    if (result != OC_STACK_OK)
+    {
+        clearStringArray(gidlist);
+        clearStringArray(midlist);
+
+        for (size_t k = i; k < gidlist->length; k++)
+        {
+            OCRepPayloadDestroy(heplerPayload[i]);
+        }
+    }
+    OICFree(heplerPayload);
+    return result;
+}
+
+/**
+ * ACL get invitation request received data handler
+ *
+ * @param[in] ctx       context
+ * @param[out] data     data required to external application
+ * @param[in] response  peer response
+ * @return  OCStackResult application result
+ */
+static OCStackResult handleAclGetInvitationResponse(void *ctx, void **data, OCClientResponse *response)
+{
+    OC_UNUSED(ctx);
+    OCStackResult result = OC_STACK_OK;
+
+    if (NULL == response->payload)
+    {
+        OIC_LOG(ERROR, TAG, "Receive NULL payload");
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    inviteResponse_t *answer = OICCalloc(1, sizeof(inviteResponse_t));
+    if (NULL == answer)
+    {
+        OIC_LOG(ERROR, TAG, "Can't allocate answer");
+        return OC_STACK_NO_MEMORY;
+    }
+
+    const OCRepPayload *payload = (const OCRepPayload *)response->payload;
+
+    result = parseInvitePayload(payload, OC_RSRVD_INVITE, &answer->invite);
+    if (result != OC_STACK_OK)
+    {
+        goto exit;
+    }
+
+    result = parseInvitePayload(payload, OC_RSRVD_INVITED, &answer->invited);
+    if (result != OC_STACK_OK)
+    {
+        goto exit;
+    }
+
+    *data = answer;
+
+exit:
+    if (result != OC_STACK_OK)
+    {
+        OICFree(answer);
+    }
+    return result;
+}
+
+/**
+ * ACL policy check request received data handler
+ *
+ * @param[in] ctx       context
+ * @param[out] data     data required to external application
+ * @param[in] response  peer response
+ * @return  OCStackResult application result
+ */
+static OCStackResult handleAclPolicyCheckResponse(void *ctx, void **data, OCClientResponse *response)
+{
+    OC_UNUSED(ctx);
+
+    if (NULL == response->payload)
+    {
+        OIC_LOG(ERROR, TAG, "Receive NULL payload");
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    char *gp = NULL;
+
+    if (!OCRepPayloadGetPropString((const OCRepPayload *)response->payload, OC_RSRVD_GROUP_PERMISSION, &gp))
+    {
+        OIC_LOG_V(ERROR, TAG, "Can't get: %s", OC_RSRVD_GROUP_PERMISSION);
+        return OC_STACK_MALFORMED_RESPONSE;
+    }
+
+    *data = gp;
+    return OC_STACK_OK;
+}
+
+OCStackResult OCCloudAclInviteUser(void* ctx,
+                                   const char *userId,
+                                   const stringArray_t *groupIds,
+                                   const stringArray_t *memberIds,
+                                   const OCDevAddr *endPoint,
+                                   OCCloudResponseCB callback)
+{
+    OCStackResult result = OC_STACK_ERROR;
+    char uri[MAX_URI_LENGTH] = { 0 };
+    size_t i = 0;
+
+    VERIFY_NON_NULL_RET(groupIds, TAG, "NULL input param", OC_STACK_INVALID_PARAM);
+    VERIFY_NON_NULL_RET(memberIds, TAG, "NULL input param", OC_STACK_INVALID_PARAM);
+
+    if (groupIds->length != memberIds->length)
+    {
+        OIC_LOG(ERROR, TAG, "members and groups lists should have the same length!!!");
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    snprintf(uri, MAX_URI_LENGTH, "%s%s:%d%s", DEFAULT_PREFIX,
+            endPoint->addr, endPoint->port, OC_RSRVD_ACL_INVITE_URL);
+
+    OCCallbackData cbData;
+    fillCallbackData(&cbData, ctx, callback, NULL, NULL);
+
+    OCRepPayload *payload = OCRepPayloadCreate();
+    if (!payload)
+    {
+        return OC_STACK_NO_MEMORY;
+    }
+
+    OCRepPayload **heplerPayload = OICCalloc(groupIds->length, sizeof(OCRepPayload *));
+
+    for (i = 0; i < groupIds->length; i++)
+    {
+        heplerPayload[i] = OCRepPayloadCreate();
+        if (!heplerPayload[i])
+        {
+            goto no_memory;
+        }
+        OCRepPayloadSetPropString(heplerPayload[i], OC_RSRVD_GROUP_ID, groupIds->array[i]);
+        OCRepPayloadSetPropString(heplerPayload[i], OC_RSRVD_MEMBER_ID, memberIds->array[i]);
+    }
+
+    //add next fields if they were filled
+    if (userId) OCRepPayloadSetPropString(payload, OC_RSRVD_USER_UUID, userId);
+
+    size_t dimensions[MAX_REP_ARRAY_DEPTH] = {groupIds->length, 0, 0};
+    OCRepPayloadSetPropObjectArray(payload, OC_RSRVD_INVITE,
+            (const struct OCRepPayload **)heplerPayload, dimensions);
+
+    return OCDoResource(NULL, OC_REST_POST, uri, NULL, (OCPayload *)payload,
+                        CT_ADAPTER_TCP, OC_LOW_QOS, &cbData, NULL, 0);
+no_memory:
+    OCRepPayloadDestroy(payload);
+    for (size_t k = 0; k < i; k++)
+    {
+        OCRepPayloadDestroy(heplerPayload[k]);
+    }
+    OCRepPayloadDestroy(*heplerPayload);
+    return result;
+}
+
+OCStackResult OCCloudAclGetInvitation(void* ctx,
+                                      const char *userId,
+                                      const OCDevAddr *endPoint,
+                                      OCCloudResponseCB callback)
+{
+    char uri[MAX_URI_LENGTH] = { 0 };
+
+    snprintf(uri, MAX_URI_LENGTH, "%s%s:%d%s", DEFAULT_PREFIX,
+            endPoint->addr, endPoint->port, OC_RSRVD_ACL_INVITE_URL);
+
+    if (userId)
+    {
+        size_t len = strlen(uri);
+        snprintf(uri + len, MAX_URI_LENGTH -len, "?%s=%s", OC_RSRVD_USER_UUID, userId);
+    }
+
+    OCCallbackData cbData;
+    fillCallbackData(&cbData, ctx, callback, handleAclGetInvitationResponse, NULL);
+
+    return OCDoResource(NULL, OC_REST_GET, uri, NULL, NULL,
+                        CT_ADAPTER_TCP, OC_LOW_QOS, &cbData, NULL, 0);
+}
+
+OCStackResult OCCloudAclDeleteInvitation(void* ctx,
+                                         const char *userId,
+                                         const char *groupId,
+                                         const OCDevAddr *endPoint,
+                                         OCCloudResponseCB callback)
+{
+    char uri[MAX_URI_LENGTH] = { 0 };
+
+    VERIFY_NON_NULL_RET(groupId, TAG, "NULL input param", OC_STACK_INVALID_PARAM);
+
+    snprintf(uri, MAX_URI_LENGTH, "%s%s:%d%s", DEFAULT_PREFIX,
+            endPoint->addr, endPoint->port, OC_RSRVD_ACL_INVITE_URL);
+
+    if (userId)
+    {
+        size_t len = strlen(uri);
+        snprintf(uri + len, MAX_URI_LENGTH - len, "?%s=%s", OC_RSRVD_USER_UUID, userId);
+    }
+
+    size_t len = strlen(uri);
+    snprintf(uri + len, MAX_URI_LENGTH - len, "%c%s=%s", userId?'&':'?', OC_RSRVD_GROUP_ID, groupId);
+
+    OCCallbackData cbData;
+    fillCallbackData(&cbData, ctx, callback, NULL, NULL);
+
+    return OCDoResource(NULL, OC_REST_DELETE, uri, NULL, NULL,
+                        CT_ADAPTER_TCP, OC_LOW_QOS, &cbData, NULL, 0);
+}
+
+OCStackResult OCCloudAclCancelInvitation(void* ctx,
+                                         const char *userId,
+                                         const char *groupId,
+                                         const char *memberId,
+                                         const OCDevAddr *endPoint,
+                                         OCCloudResponseCB callback)
+{
+    char uri[MAX_URI_LENGTH] = { 0 };
+    size_t len = 0 ;
+
+    VERIFY_NON_NULL_RET(groupId, TAG, "NULL input param", OC_STACK_INVALID_PARAM);
+    VERIFY_NON_NULL_RET(memberId, TAG, "NULL input param", OC_STACK_INVALID_PARAM);
+
+    snprintf(uri, MAX_URI_LENGTH, "%s%s:%d%s", DEFAULT_PREFIX,
+            endPoint->addr, endPoint->port, OC_RSRVD_ACL_INVITE_URL);
+
+    if (userId)
+    {
+        size_t len = strlen(uri);
+        snprintf(uri + len, MAX_URI_LENGTH - len, "?%s=%s", OC_RSRVD_USER_UUID, userId);
+    }
+
+    len = strlen(uri);
+    snprintf(uri + len, MAX_URI_LENGTH - len, "%c%s=%s", userId?'&':'?', OC_RSRVD_GROUP_ID, groupId);
+    len = strlen(uri);
+    snprintf(uri + len, MAX_URI_LENGTH - len, "&%s=%s", OC_RSRVD_MEMBER_ID, memberId);
+
+    OCCallbackData cbData;
+    fillCallbackData(&cbData, ctx, callback, NULL, NULL);
+
+    return OCDoResource(NULL, OC_REST_DELETE, uri, NULL, NULL,
+                        CT_ADAPTER_TCP, OC_LOW_QOS, &cbData, NULL, 0);
+}
+
+OCStackResult OCCloudAclPolicyCheck(void* ctx,
+                                    const char *subjectId,
+                                    const char *deviceId,
+                                    const char *method,
+                                    const char *user_uri,
+                                    const OCDevAddr *endPoint,
+                                    OCCloudResponseCB callback)
+{
+    char uri[MAX_URI_LENGTH] = { 0 };
+    size_t len = 0;
+
+    VERIFY_NON_NULL_RET(subjectId, TAG, "NULL input param", OC_STACK_INVALID_PARAM);
+    VERIFY_NON_NULL_RET(deviceId, TAG, "NULL input param", OC_STACK_INVALID_PARAM);
+    VERIFY_NON_NULL_RET(method, TAG, "NULL input param", OC_STACK_INVALID_PARAM);
+    VERIFY_NON_NULL_RET(user_uri, TAG, "NULL input param", OC_STACK_INVALID_PARAM);
+
+    snprintf(uri, MAX_URI_LENGTH, "%s%s:%d%s", DEFAULT_PREFIX,
+            endPoint->addr, endPoint->port, OC_RSRVD_ACL_VERIFY_URL);
+
+    len = strlen(uri);
+    snprintf(uri + len, MAX_URI_LENGTH - len, "?%s=%s", OC_RSRVD_SUBJECT_ID, subjectId);
+    len = strlen(uri);
+    snprintf(uri + len, MAX_URI_LENGTH - len, "&%s=%s", OC_RSRVD_DEVICE_ID, deviceId);
+    len = strlen(uri);
+    snprintf(uri + len, MAX_URI_LENGTH - len, "&%s=%s", OC_RSRVD_REQUEST_METHOD, method);
+    len = strlen(uri);
+    snprintf(uri + len, MAX_URI_LENGTH - len, "&%s=%s", OC_RSRVD_REQUEST_URI, user_uri);
+
+    OCCallbackData cbData;
+    fillCallbackData(&cbData, ctx, callback, handleAclPolicyCheckResponse, NULL);
+
+    return OCDoResource(NULL, OC_REST_GET, uri, NULL, NULL,
+                        CT_ADAPTER_TCP, OC_LOW_QOS, &cbData, NULL, 0);
+}
diff --git a/resource/csdk/security/provisioning/src/cloud/crl.c b/resource/csdk/security/provisioning/src/cloud/crl.c
new file mode 100644 (file)
index 0000000..088b1d5
--- /dev/null
@@ -0,0 +1,170 @@
+#include <string.h>
+#include <stdio.h>
+#include <stdlib.h>
+
+#include "utils.h"
+
+#include "logger.h"
+#include "ocstack.h"
+#include "ocpayload.h"
+#include "pmutility.h"
+#include "oic_malloc.h"
+#include "crlresource.h"
+#include "ocpayloadcbor.h"
+#include "payload_logging.h"
+#include "cacommonutil.h"
+
+#define TAG "CLOUD-CRL"
+
+/**
+ * CRL GET request received data handler
+ *
+ * @param[in] ctx       context
+ * @param[out] data     data required to external application
+ * @param[in] response  peer response
+ * @return  OCStackResult application result
+ */
+static OCStackResult handleCrlGetResponse(void *ctx, void **data, OCClientResponse *response)
+{
+    OCStackResult result = OC_STACK_OK;
+    OicSecCrl_t *crl = NULL;
+
+    OC_UNUSED(ctx);
+    OC_UNUSED(data);
+
+    if (NULL == response->payload)
+    {
+        OIC_LOG(ERROR, TAG, "Receive NULL payload\n");
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    OCPayloadType type = response->payload->type;
+
+    if (type != PAYLOAD_TYPE_SECURITY)
+    {
+        OIC_LOG(ERROR, TAG, "Receive NOT security payload, can't parse it!\n");
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    OCSecurityPayload *payload = (OCSecurityPayload *)response->payload;
+
+    result = CBORPayloadToCrl(payload->securityData, payload->payloadSize, &crl);
+    if (result != OC_STACK_OK)
+    {
+        OIC_LOG(ERROR, TAG, "Can't convert cbor to Crl");
+        goto exit;
+    }
+
+    result = UpdateCRLResource(crl);
+    if (result != OC_STACK_OK)
+    {
+        OIC_LOG(ERROR, TAG, "Can't update Crl resource");
+    }
+
+exit:
+    DeleteCrl(crl);
+    return result;
+}
+
+OCStackResult OCCloudGetCRL(void* ctx,
+                            const OCDevAddr *endPoint,
+                            OCCloudResponseCB callback)
+{
+    char uri[MAX_URI_LENGTH] = { 0 };
+    char *lastUpdate = NULL;
+
+    getLastUpdateFromDB(&lastUpdate);
+
+    snprintf(uri, MAX_URI_LENGTH, "%s%s:%d%s?%s=%s", DEFAULT_PREFIX,
+            endPoint->addr, endPoint->port,
+            OC_RSRVD_PROV_CRL_URL, OC_RSRVD_LAST_UPDATE, lastUpdate);
+
+    OICFree(lastUpdate);
+
+    OCCallbackData cbData;
+    fillCallbackData(&cbData, ctx, callback, handleCrlGetResponse, NULL);
+
+    return OCDoResource(NULL, OC_REST_GET, uri, NULL, NULL,
+                        CT_ADAPTER_TCP, OC_LOW_QOS, &cbData, NULL, 0);
+}
+
+OCStackResult OCCloudPostCRL(void* ctx,
+                             const char *thisUpdate,
+                             const char *nextUpdate,
+                             const OCByteString *crl,
+                             const stringArray_t *serialNumbers,
+                             const OCDevAddr *endPoint,
+                             OCCloudResponseCB callback)
+{
+    OCStackResult result = OC_STACK_ERROR;
+    char uri[MAX_URI_LENGTH] = { 0 };
+    OCRepPayload *payload = NULL;
+    OCSecurityPayload *secPayload = NULL;
+    uint8_t *cbor = NULL;
+    size_t cbor_len = 0;
+    OicSecKey_t crl1;
+
+    VERIFY_NON_NULL_RET(thisUpdate, TAG, "NULL input param", OC_STACK_INVALID_PARAM);
+    VERIFY_NON_NULL_RET(nextUpdate, TAG, "NULL input param", OC_STACK_INVALID_PARAM);
+
+    if (crl)
+    {
+        crl1.data = crl->bytes;
+        crl1.len  = crl->len;
+        crl1.encoding = OIC_ENCODING_DER;
+    }
+
+    snprintf(uri, MAX_URI_LENGTH, "%s%s:%d%s", DEFAULT_PREFIX,
+            endPoint->addr, endPoint->port, OC_RSRVD_PROV_CRL_URL);
+
+    OCCallbackData cbData;
+    fillCallbackData(&cbData, ctx, callback, NULL, NULL);
+
+    payload = OCRepPayloadCreate();
+    if (!payload)
+    {
+        OIC_LOG(ERROR, TAG, "Can't allocate payload");
+        goto exit;
+    }
+
+    OCRepPayloadSetPropString(payload, OC_RSRVD_THIS_UPDATE, thisUpdate);
+    OCRepPayloadSetPropString(payload, OC_RSRVD_NEXT_UPDATE, nextUpdate);
+
+    //add next fields if they were filled
+    if (serialNumbers)
+    {
+        size_t dimensions[MAX_REP_ARRAY_DEPTH] = {serialNumbers->length, 0 ,0};
+        OCRepPayloadSetStringArray(payload, OC_RSRVD_SERIAL_NUMBERS,
+                                   (const char**)serialNumbers->array, dimensions);
+
+    }
+    if (crl) OCRepPayloadSetPropPubDataType(payload, OC_RSRVD_CRL, &crl1);
+
+    OIC_LOG(DEBUG, TAG, "Next payload created:");
+    OIC_LOG_PAYLOAD(DEBUG, (OCPayload *)payload);
+
+    secPayload = OICCalloc(1, sizeof(OCSecurityPayload));
+    if (!secPayload)
+    {
+        OIC_LOG(ERROR, TAG, "Can't allocate secPayload");
+        goto exit;
+    }
+
+    result = OCConvertPayload((OCPayload *)payload, &cbor, &cbor_len);
+    if (result != OC_STACK_OK)
+    {
+        OIC_LOG(ERROR, TAG, "Can't convert OCPayload to cbor");
+        OICFree(secPayload);
+        goto exit;
+    }
+
+    secPayload->base.type = PAYLOAD_TYPE_SECURITY;
+    secPayload->securityData = cbor;
+    secPayload->payloadSize = cbor_len;
+
+    result = OCDoResource(NULL, OC_REST_POST, uri, NULL, (OCPayload *)secPayload,
+                        CT_ADAPTER_TCP, OC_LOW_QOS, &cbData, NULL, 0);
+exit:
+    OCPayloadDestroy((OCPayload *)payload);
+    return result;
+}
diff --git a/resource/csdk/security/provisioning/src/cloud/csr.c b/resource/csdk/security/provisioning/src/cloud/csr.c
new file mode 100644 (file)
index 0000000..f95328d
--- /dev/null
@@ -0,0 +1,491 @@
+#include "utils.h"
+
+#include "logger.h"
+#include <stddef.h>
+#include <string.h>
+#include "oic_malloc.h"
+#include "oic_string.h"
+#include "cacommonutil.h"
+
+#include "ocpayload.h"
+#include "payload_logging.h"
+#include "doxmresource.h"
+#include "pmutility.h"
+#include "secureresourceprovider.h"
+
+// headers required for mbed TLS
+#include "mbedtls/platform.h"
+#include "mbedtls/ssl.h"
+#include "mbedtls/entropy.h"
+#include "mbedtls/ctr_drbg.h"
+#include "mbedtls/pkcs12.h"
+#include "mbedtls/ssl_internal.h"
+#include "mbedtls/x509_csr.h"
+
+#ifndef NDEBUG
+#include "mbedtls/debug.h"
+#include "mbedtls/version.h"
+#endif
+
+#include <unistd.h>
+#include <fcntl.h>
+
+#define TAG "CLOUD-CSR"
+
+//TODO: is it required in CSR response?
+static OCByteString privateKey = {0, 0};
+
+#define MAX_URI_QUERY MAX_URI_LENGTH + MAX_QUERY_LENGTH
+
+#define MAX_STRING_LEN 254
+
+/**
+ * @def SEED
+ * @brief Seed for initialization RNG
+ */
+
+#define SEED "IOTIVITY_RND"
+
+typedef struct
+{
+    char *subject;
+    char *prKey;
+    size_t prKeyLen;
+    char *pubKey;
+    size_t pubKeyLen;
+} SignCred_t;
+
+/**
+ * Make CSR subject like:
+ * Subject: C=KR, O=Samsung, OU=OCF Device, CN=uuid:1234567890
+ * @param[in] subj              the subject
+ */
+static void CSRMakeSubject(char *subject, const char *countryCode, const char *organisation,
+                    const char *organizationalUnitName, const char *deviceId)
+{
+    OIC_LOG_V(DEBUG, TAG, "IN: %s", __func__);
+
+    if (!deviceId)
+    {
+        OIC_LOG_V(ERROR, TAG, "%s: The device id is NULL",__func__);
+        return;
+    }
+    snprintf(subject, MAX_STRING_LEN, "C=%s, O=%s, OU=%s, CN=uuid:%s", countryCode, organisation, organizationalUnitName, deviceId);
+
+    OIC_LOG_V(DEBUG, TAG, "OUT: %s", __func__);
+}
+/**
+ * Generates elliptic keypair.
+ *
+ * @param[out]  pk    mbedtls public key container
+ *
+ * @return  0 on success or -1 on error
+ */
+static int ecdsaGenKeypair(mbedtls_pk_context * pk)
+{
+    OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
+    mbedtls_entropy_context entropy;
+    mbedtls_ctr_drbg_context ctr_drbg;
+
+    VERIFY_NON_NULL_RET(pk, TAG, "Param pk is NULL", -1);
+
+    // Entropy seeding
+#ifdef __unix__
+    unsigned char seed[sizeof(SEED)] = {0};
+    int urandomFd = -2;
+    urandomFd = open("/dev/urandom", O_RDONLY);
+    if(urandomFd == -1)
+    {
+        OIC_LOG(ERROR, TAG, "Fails open /dev/urandom!");
+        OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
+        return -1;
+    }
+    if(0 > read(urandomFd, seed, sizeof(seed)))
+    {
+        OIC_LOG(ERROR, TAG, "Fails read from /dev/urandom!");
+        close(urandomFd);
+        OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
+        return -1;
+    }
+    close(urandomFd);
+
+#else
+    unsigned char * seed = (unsigned char*) SEED;
+#endif
+    // Initialize and seed DRBG context
+    mbedtls_ctr_drbg_init(&ctr_drbg);
+    mbedtls_entropy_init(&entropy);
+    if (0 != mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func,
+                                   &entropy, seed, sizeof(SEED)))
+    {
+        OIC_LOG(ERROR, TAG, "Seed initialization failed!");
+        OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
+        return -1;
+    }
+    mbedtls_ctr_drbg_set_prediction_resistance(&ctr_drbg, MBEDTLS_CTR_DRBG_PR_OFF);
+    // Initialize l context
+    mbedtls_pk_init(pk);
+    if (0 > mbedtls_pk_setup(pk, mbedtls_pk_info_from_type(MBEDTLS_PK_ECKEY)))
+    {
+        OIC_LOG(ERROR, TAG, "mbedtls_pk_info_from_type error");
+        OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
+        return -1;
+    }
+    if (0 > mbedtls_ecp_group_load(&mbedtls_pk_ec(*pk)->grp, MBEDTLS_ECP_DP_SECP256R1))
+    {
+        OIC_LOG(ERROR, TAG, "mbedtls_ecp_group_load error");
+        OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
+        return -1;
+    }
+    if (0 > mbedtls_ecp_gen_keypair(&mbedtls_pk_ec(*pk)->grp,
+                                    &mbedtls_pk_ec(*pk)->d,
+                                    &mbedtls_pk_ec(*pk)->Q,
+                                    mbedtls_ctr_drbg_random, &ctr_drbg))
+    {
+        OIC_LOG(ERROR, TAG, "mbedtls_ecp_gen_keypair error");
+        OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
+        return -1;
+    }
+
+    OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
+    return 0;
+}
+
+
+
+/**
+ * Generates keypair and certificate signing request.
+ *
+ * @param[in]  subjectName    CSR Subject names should contain
+ * a comma-separated list of OID types and values:
+ * e.g. "C=UA,O=ABC,CN=uuid:32323232-3232-3232-3232-323232323232"
+ * @param[out] prKey          private key in DER
+ * @param[out] prKeyLen       private key buffer length
+ * @param[out] pubKey         public key in DER
+ * @param[out] pubKeyLen      public key buffer length
+ * @param[out] CSR            certificate signing request in DER
+ * @param[out] CSRLen         certificate signing request buffer length
+ *
+ * @return  0 on success or -1 on error
+ */
+static int GenerateCSR(char *subject, OCByteString *csr)
+{
+    OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
+    VERIFY_NON_NULL_RET(subject, TAG, "Param subject is NULL", -1);
+    VERIFY_NON_NULL_RET(csr, TAG, "Param csr is NULL", -1);
+
+    int ret = 0;
+    int bufsize = 1024;
+    unsigned char * buf = NULL;
+    mbedtls_entropy_context entropy;
+    mbedtls_ctr_drbg_context ctr_drbg;
+    mbedtls_pk_context * key = NULL;
+    mbedtls_x509write_csr req;
+
+    // Initialize keypair context
+    key = (mbedtls_pk_context *)OICMalloc(sizeof(mbedtls_pk_context));
+    if (NULL == key)
+    {
+        OIC_LOG_V(ERROR, TAG, "OICMalloc returned NULL on key allocation");
+        OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
+        return -1;
+    }
+    // Generate keypair
+    if (0 > ecdsaGenKeypair(key))
+    {
+        OIC_LOG(ERROR, TAG, "ecdsaGenKeypair error");
+        OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
+        return -1;
+    }
+
+    // Initialize CSR context
+    mbedtls_x509write_csr_init(&req);
+    // Set up MD algorithm, key and subject to CSR
+    mbedtls_x509write_csr_set_md_alg(&req, MBEDTLS_MD_SHA256);
+    mbedtls_x509write_csr_set_key(&req, key);
+    if (0 > mbedtls_x509write_csr_set_subject_name(&req, subject))
+    {
+        OIC_LOG(ERROR, TAG, "mbedtls_x509write_csr_set_subject_name error");
+        OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
+        return -1;
+    }
+
+    // Entropy seeding
+#ifdef __unix__
+    unsigned char seed[sizeof(SEED)] = {0};
+    int urandomFd = -2;
+    urandomFd = open("/dev/urandom", O_RDONLY);
+    if(urandomFd == -1)
+    {
+        OIC_LOG(ERROR, TAG, "Fails open /dev/urandom!");
+        OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
+        return -1;
+    }
+    if(0 > read(urandomFd, seed, sizeof(seed)))
+    {
+        OIC_LOG(ERROR, TAG, "Fails read from /dev/urandom!");
+        close(urandomFd);
+        OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
+        return -1;
+    }
+    close(urandomFd);
+
+#else
+    unsigned char * seed = (unsigned char *) SEED;
+#endif
+    // Initialize and seed DRBG context
+    mbedtls_ctr_drbg_init(&ctr_drbg);
+    mbedtls_entropy_init(&entropy);
+    if (0 != mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func,
+                                   &entropy, seed, sizeof(SEED)))
+    {
+        OIC_LOG(ERROR, TAG, "Seed initialization failed!");
+        OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
+        return -1;
+    }
+    mbedtls_ctr_drbg_set_prediction_resistance(&ctr_drbg, MBEDTLS_CTR_DRBG_PR_OFF);
+
+    // Create CSR
+    buf = (unsigned char *)OICMalloc(bufsize * sizeof(unsigned char));
+    if (NULL == buf)
+    {
+        OIC_LOG(ERROR, TAG, "OICMalloc returned NULL on buf allocation");
+        OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
+        return -1;
+    }
+    ret = mbedtls_x509write_csr_der(&req, buf, bufsize,
+                                    mbedtls_ctr_drbg_random, &ctr_drbg);
+    if (ret < 0)
+    {
+        OIC_LOG(ERROR, TAG, "mbedtls_x509write_csr_der error");
+        OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
+        return -1;
+    }
+
+    // CSR to output
+    csr->bytes = (uint8_t *)OICMalloc(ret * sizeof(uint8_t));
+    if (NULL == csr->bytes)
+    {
+        OIC_LOG(ERROR, TAG, "OICMalloc returned NULL on csr allocation");
+        OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
+        return -1;
+    }
+    memcpy(csr->bytes, buf + bufsize - ret, ret * sizeof(uint8_t));
+    csr->len = ret;
+    // Private key to output
+    ret = mbedtls_pk_write_key_der(key, buf, bufsize);
+    if (ret < 0)
+    {
+        OIC_LOG(ERROR, TAG, "mbedtls_pk_write_key_der error");
+        OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
+        return -1;
+    }
+    privateKey.bytes = (uint8_t *)OICMalloc(ret * sizeof(char));
+    if (NULL == privateKey.bytes)
+    {
+        OIC_LOG(ERROR, TAG, "OICMalloc returned NULL on privateKey.bytes allocation");
+        OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
+        return -1;
+    }
+    memcpy(privateKey.bytes, buf + bufsize - ret, ret * sizeof(uint8_t));
+    privateKey.len = ret;
+    // Public key to output
+    ret = mbedtls_pk_write_pubkey_der(key, buf, bufsize);
+    if (ret < 0)
+    {
+        OIC_LOG(ERROR, TAG, "mbedtls_pk_write_pubkey_der error");
+        OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
+        return -1;
+    }
+    //leave this, may be public key will be required in future
+    OCByteString publicKey;
+    publicKey.bytes = (uint8_t *)OICMalloc(ret * sizeof(char));
+    if (NULL == publicKey.bytes)
+    {
+        OIC_LOG(ERROR, TAG, "OICMalloc returned NULL on pubKey allocation");
+        OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
+        return -1;
+    }
+    memcpy(publicKey.bytes, buf + bufsize - ret, ret * sizeof(uint8_t));
+    publicKey.len = ret;
+    OICFree(publicKey.bytes);
+
+    mbedtls_entropy_free(&entropy);
+    mbedtls_ctr_drbg_free(&ctr_drbg);
+    mbedtls_x509write_csr_free(&req);
+    OICFree(key);
+
+    OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
+    return 0;
+}
+
+/**
+ * Cloud CSR Sign response handler
+
+ * @param[in] ctx       context
+ * @param[out] data     data required to external application
+ * @param[in] response  peer response
+ * @return  OCStackResult application result
+ */
+static OCStackResult HandleCertificateIssueRequest(void *ctx, void **data, OCClientResponse *response)
+{
+    OCStackResult result = OC_STACK_OK;
+    OIC_LOG_V(DEBUG, TAG, "IN: %s", __func__);
+
+    OC_UNUSED(ctx);
+    OC_UNUSED(data);
+
+    if (!response)
+    {
+        OIC_LOG_V(ERROR, TAG, "%s: Client response is null",__func__);
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    if (response->result < 4 && response->payload)
+    {
+        OIC_LOG_V(ERROR, TAG, "CSR sign error: result: %d, payload null: %s",
+                  response->result, response->payload ? "no" : "yes");
+        OIC_LOG_PAYLOAD(DEBUG, response->payload);
+        return OC_STACK_ERROR;
+    }
+
+    char *deviceId = 0;
+
+    if (!OCRepPayloadGetPropString((OCRepPayload *)response->payload,
+                                   OC_RSRVD_DEVICE_ID, &deviceId))
+    {
+        OIC_LOG(ERROR, TAG, "Can't get: Device Id");
+        result = OC_STACK_ERROR;
+    }
+
+    OicSecKey_t cert;
+    if (!OCRepPayloadGetPropPubDataType((OCRepPayload *)response->payload,
+                                   OC_RSRVD_CERT, &cert))
+    {
+        OIC_LOG_V(ERROR, TAG, "Can't get: %s", OC_RSRVD_CERT);
+        result = OC_STACK_ERROR;
+    }
+    else
+    {
+        OicSecKey_t key =
+        {
+            privateKey.bytes,
+            privateKey.len,
+            OIC_ENCODING_DER
+        };
+
+        OicSecCert_t cert1 =
+        {
+            cert.data,
+            cert.len,
+        };
+
+        uint16_t credId;
+        result = SRPSaveOwnCertChain(&cert1, &key, &credId);
+        if (result != OC_STACK_OK)
+        {
+            OIC_LOG(ERROR, TAG, "Cann't add cert");
+        }
+    }
+
+    //get cacert
+    OicSecKey_t caCert;
+    if (!OCRepPayloadGetPropPubDataType((OCRepPayload *)response->payload,
+                                   OC_RSRVD_CACERT, &caCert))
+    {
+        OIC_LOG_V(ERROR, TAG, "Cann't get: %s", OC_RSRVD_CACERT);
+        result = OC_STACK_ERROR;
+    }
+    else
+    {
+        uint16_t credId;
+        result = SRPSaveTrustCertChain(caCert.data, caCert.len, caCert.encoding, &credId);
+        if (result != OC_STACK_OK)
+        {
+            OIC_LOG(ERROR, TAG, "Can't insert CA cert");
+        }
+    }
+
+    OICFree(privateKey.bytes);
+    privateKey.bytes = NULL;
+    privateKey.len   = 0;
+
+    OIC_LOG_V(DEBUG, TAG, "OUT: %s", __func__);
+
+    return result;
+}
+
+/**
+ * Certificate-Issue request function
+ *
+ * @param[in] endPoint          cloud host and port
+ * @return  OCStackResult application result
+ */
+OCStackResult OCCloudCertificateIssueRequest(void* ctx,
+                                             const OCDevAddr *endPoint,
+                                             OCCloudResponseCB callback)
+{
+    OCStackResult ret = OC_STACK_OK;
+
+    OIC_LOG_V(DEBUG, TAG, "IN: %s", __func__);
+
+    if (NULL == endPoint)
+    {
+        OIC_LOG(ERROR, TAG, "Input parameter endpoint is NULL");
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    char *deviceId = getDeviceId();
+
+    char subject[MAX_STRING_LEN] = { 0 };
+    CSRMakeSubject(subject, "KR", "Samsung", "OCF Device", deviceId);
+
+    OIC_LOG_V(DEBUG, TAG, "Certificate Request subject: %s", subject);
+
+    OCByteString request;
+    if (0 != GenerateCSR(subject, &request))
+    {
+        OIC_LOG(ERROR, TAG, "Cann't get the sertificate request");
+        ret = OC_STACK_ERROR;
+        goto exit;
+    }
+    OIC_LOG(DEBUG, TAG, "Certificate Request:");
+    OIC_LOG_BUFFER(DEBUG, TAG, request.bytes, request.len);
+
+    OIC_LOG(DEBUG, TAG, "Private Key:");
+    OIC_LOG_BUFFER(DEBUG, TAG, privateKey.bytes, privateKey.len);
+
+    OCRepPayload* payload = OCRepPayloadCreate();
+    if (!payload)
+    {
+        OIC_LOG(ERROR, TAG, "Failed to memory allocation");
+        ret = OC_STACK_ERROR;
+        goto exit;
+    }
+
+    OCRepPayloadSetPropString(payload, OC_RSRVD_DEVICE_ID, deviceId);
+
+    OicSecKey_t csr = {.data = request.bytes, .len = request.len, .encoding = OIC_ENCODING_DER};
+
+    OCRepPayloadSetPropPubDataType(payload, OC_RSRVD_CSR, &csr);
+
+    OIC_LOG_PAYLOAD(DEBUG, (OCPayload *)payload);
+
+    char uri[MAX_URI_QUERY] = { 0 };
+    snprintf(uri, MAX_URI_QUERY, DEFAULT_QUERY,
+             endPoint->addr, endPoint->port,
+             OC_RSRVD_PROV_CERT_URI);
+
+    OCCallbackData cbData;
+    fillCallbackData(&cbData, ctx, callback, HandleCertificateIssueRequest, NULL);
+
+    ret = OCDoResource(NULL, OC_REST_POST, uri, NULL,
+                       (OCPayload *)payload,
+                       CT_ADAPTER_TCP,
+                       OC_LOW_QOS, &cbData, NULL, 0);
+
+    OIC_LOG_V(DEBUG, TAG, "OUT: %s", __func__);
+exit:
+    OICFree(request.bytes);
+    return ret;
+}
diff --git a/resource/csdk/security/provisioning/src/cloud/utils.c b/resource/csdk/security/provisioning/src/cloud/utils.c
new file mode 100644 (file)
index 0000000..2b376a7
--- /dev/null
@@ -0,0 +1,163 @@
+#include "utils.h"
+
+#include "logger.h"
+#include "payload_logging.h"
+#include "oic_malloc.h"
+#include "doxmresource.h"
+#include "srmutility.h"
+#include "pmutility.h"
+
+#define TAG "CLOUD-UTILS"
+
+typedef struct {
+    void *ctx;
+    OCCloudResponseCB cb;
+    UserFunctionCB fn;
+    void *params;
+}ContextInfo_t;
+
+char *DEFAULT_QUERY  = COAP_TCP_QUERY;
+char *DEFAULT_PREFIX = COAP_TCP_PREFIX;
+
+/**
+ * This function sets required CoAP prefix depending on
+ * secure or non-secure connection
+ *
+ * @param[in] secure   secure flag
+ */
+void setCoapPrefix(bool secure)
+{
+    if (secure)
+    {
+        DEFAULT_QUERY  = COAPS_TCP_QUERY;
+        DEFAULT_PREFIX = COAPS_TCP_PREFIX;
+    }
+    else
+    {
+        DEFAULT_QUERY  = COAP_TCP_QUERY;
+        DEFAULT_PREFIX = COAP_TCP_PREFIX;
+    }
+}
+
+/**
+ * This hepler function handles response from each request
+ * During execution it calls proper callbacks
+ *
+ * @param[in] ctx             context
+ * @param[in] handle          handle
+ * @param[in] clientResponse  response from peer
+ */
+static OCStackApplicationResult handleResponse(void *ctx,
+                                              OCDoHandle handle,
+                                              OCClientResponse *clientResponse)
+{
+    OC_UNUSED(handle);
+
+    if (NULL == clientResponse)
+    {
+        OIC_LOG_V(ERROR, TAG, "Received null response from client");
+        return OC_STACK_DELETE_TRANSACTION;
+    }
+
+    OIC_LOG_V(DEBUG, TAG, "Received callback with response code: %d", clientResponse->result);
+
+    if (clientResponse->payload)
+    {
+        OIC_LOG(DEBUG, TAG, "Payload received:");
+        OIC_LOG_PAYLOAD(DEBUG, clientResponse->payload);
+    }
+
+    if (ctx)
+    {
+        OCStackResult result = clientResponse->result;
+        void *data = NULL;
+
+        ContextInfo_t *info = (ContextInfo_t *)ctx;
+
+        if (info->fn)
+        {
+            result = ((UserFunctionCB)info->fn)(info->params, &data, clientResponse);
+        }
+
+        if (info->cb)
+        {
+            ((OCCloudResponseCB)info->cb)(info->ctx, result, data);
+        }
+    }
+
+    return OC_STACK_DELETE_TRANSACTION;
+}
+
+static void deleteContextInfo(void *info)
+{
+    OICFree(info);
+}
+
+void fillCallbackData(OCCallbackData *cbData, void *ctx, OCCloudResponseCB cb,
+                                              UserFunctionCB fn, void *params)
+{
+    memset(cbData, 0, sizeof(OCCallbackData));
+
+    ContextInfo_t *info = OICCalloc(1, sizeof(ContextInfo_t));
+    if (!info)
+    {
+        OIC_LOG(ERROR, TAG, "Can't allocate memory for info");
+        return;
+    }
+
+    info->ctx = ctx;
+    info->cb  = cb;
+    info->fn  = fn;
+    info->params = params;
+
+    cbData->cb = handleResponse;
+    cbData->cd = deleteContextInfo;
+    cbData->context = info;
+}
+
+char * getDeviceId()
+{
+    char *deviceId = NULL;
+    OicUuid_t uuid;
+
+    OIC_LOG_V(DEBUG, TAG, "IN: %s", __func__);
+
+    memset(&uuid, 0, sizeof(uuid));
+    if (OC_STACK_OK != GetDoxmDeviceID(&uuid))
+    {
+        OIC_LOG(ERROR, TAG, "Cann't get the device id(GetDoxmDeviceID)");
+        goto exit;
+    }
+
+    if (OC_STACK_OK != ConvertUuidToStr(&uuid, &deviceId))
+    {
+        OIC_LOG(ERROR, TAG, "Cann't get the device id(ConvertUuidToStr)");
+        goto exit;
+    }
+
+    OIC_LOG_V(DEBUG, TAG, "device Id: %s", deviceId);
+exit:
+    OIC_LOG_V(DEBUG, TAG, "OUT: %s", __func__);
+    return deviceId;
+}
+
+/**
+ * Clear previously filled array of strings
+ *
+ * @param[out] list           array of strings structure to clear
+ * @param[in] count           elements count
+ */
+void clearStringArray(stringArray_t *list)
+{
+    if (!list || !list->array)
+    {
+        return;
+    }
+
+    for (size_t i = 0; i < list->length; i++)
+    {
+        OICFree(list->array[i]);
+    }
+    OICFree(list->array);
+}
+
index f679388..ee4c607 100755 (executable)
@@ -21,7 +21,8 @@
 #define _POSIX_C_SOURCE 200112L
 #endif
 
-#if HAVE_UNISTD_H
+#include "iotivity_config.h"
+#ifdef HAVE_UNISTD_H
 #include <unistd.h>
 #endif
 #ifdef HAVE_STRING_H
index 0b14334..8bcfebd 100644 (file)
@@ -17,6 +17,7 @@
  * limitations under the License.
  *
  * *****************************************************************/
+#include "iotivity_config.h"
 #include <stdio.h>
 #include <string.h>
 #include <stdint.h>
@@ -472,7 +473,8 @@ OCStackResult SRPProvisionCRL(void *ctx, const OCProvisionDev_t *selectedDeviceI
     }
 
     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
-    OCStackResult res = CrlToCBORPayload(crl, &secPayload->securityData, &secPayload->payloadSize);
+    OCStackResult res;
+    res = CrlToCBORPayload(crl, &secPayload->securityData, &secPayload->payloadSize, NULL);
     if((OC_STACK_OK != res) && (NULL == secPayload->securityData))
     {
         OICFree(secPayload);
@@ -772,6 +774,60 @@ OCStackResult SRPSaveTrustCertChain(uint8_t *trustCertChain, size_t chainSize,
 
     return res;
 }
+
+
+OCStackResult SRPSaveOwnCertChain(OicSecCert_t * cert, OicSecKey_t * key, uint16_t *credId)
+{
+    OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
+    VERIFY_NON_NULL(TAG, cert, ERROR,  OC_STACK_INVALID_PARAM);
+    VERIFY_NON_NULL(TAG, cert->data, ERROR,  OC_STACK_INVALID_PARAM);
+    VERIFY_NON_NULL(TAG, key, ERROR,  OC_STACK_INVALID_PARAM);
+    VERIFY_NON_NULL(TAG, key->data, ERROR,  OC_STACK_INVALID_PARAM);
+    VERIFY_NON_NULL(TAG, credId, ERROR,  OC_STACK_INVALID_PARAM);
+
+    OCStackResult res = OC_STACK_ERROR;
+
+    OicSecCred_t *cred = (OicSecCred_t *)OICCalloc(1, sizeof(*cred));
+    VERIFY_NON_NULL(TAG, cred, ERROR, OC_STACK_NO_MEMORY);
+
+    OIC_LOG_V(DEBUG, TAG, "IN: %s", __func__);
+
+    if (OC_STACK_OK != GetDoxmDeviceID(&cred->subject))
+    {
+        OIC_LOG(ERROR, TAG, "Cann't get the device id(GetDoxmDeviceID)");
+    }
+
+    cred->credUsage= (char *)OICCalloc(1, strlen(PRIMARY_CERT)+1 );
+    VERIFY_NON_NULL(TAG, cred->credUsage, ERROR, OC_STACK_NO_MEMORY);
+    OICStrcpy(cred->credUsage, strlen(PRIMARY_CERT) + 1, PRIMARY_CERT) ;
+
+    cred->credType = SIGNED_ASYMMETRIC_KEY;
+
+    OicSecCert_t *publicData = &cred->publicData;
+    publicData->data = (uint8_t *)OICCalloc(1, cert->len);
+    VERIFY_NON_NULL(TAG, publicData->data, ERROR, OC_STACK_NO_MEMORY);
+    memcpy(publicData->data, cert->data, cert->len);
+    publicData->len = cert->len;
+
+    OicSecKey_t *privateData = &cred->privateData;
+    privateData->data = (uint8_t *)OICCalloc(1, key->len);
+    VERIFY_NON_NULL(TAG, privateData->data, ERROR, OC_STACK_NO_MEMORY);
+    memcpy(privateData->data, key->data, key->len);
+    privateData->len = key->len;
+    privateData->encoding = key->encoding;
+
+    res = AddCredential(cred);
+    if(res != OC_STACK_OK)
+    {
+        DeleteCredList(cred);
+        return res;
+    }
+    *credId = cred->credId;
+
+    OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
+
+    return res;
+}
 #endif // __WITH_X509__ || __WITH_TLS__
 
 OCStackResult SRPProvisionCredentials(void *ctx, OicSecCredType_t type, size_t keySize,
index b1d9412..653df64 100644 (file)
@@ -30,6 +30,14 @@ target_os = sptest_env.get('TARGET_OS')
 ######################################################################
 # Build flags
 ######################################################################
+with_upstream_libcoap = sptest_env.get('WITH_UPSTREAM_LIBCOAP')
+if with_upstream_libcoap == '1':
+       # For bring up purposes only, we manually copy the forked version to where the unforked version is downloaded.
+       sptest_env.AppendUnique(CPPPATH = ['#extlibs/libcoap/libcoap/include'])
+else:
+       # For bring up purposes only, the forked version will live here.
+       sptest_env.AppendUnique(CPPPATH = ['../../../connectivity/lib/libcoap-4.1.1/include'])
+
 sptest_env.PrependUnique(CPPPATH = [
                '../include',
                '../../include',
@@ -49,7 +57,6 @@ sptest_env.PrependUnique(CPPPATH = [
                '../../../connectivity/inc',
                '../../../connectivity/inc/pkix',
                '../../../connectivity/common/inc',
-               '../../../connectivity/lib/libcoap-4.1.1',
                '../../../connectivity/api',
                '../../../../../extlibs/tinydtls'
                ])
@@ -77,7 +84,6 @@ if not sptest_env.get('RELEASE'):
        sptest_env.AppendUnique(CPPDEFINES = ['TB_LOG'])
 
 if target_os in ['msys_nt', 'windows']:
-    sptest_env.AppendUnique(LINKFLAGS = ['/subsystem:CONSOLE'])
     sptest_env.AppendUnique(LIBS = ['ws2_32',
                                     'advapi32',
                                     'iphlpapi'])
index 92c67b7..14338f2 100644 (file)
@@ -17,6 +17,7 @@
  * limitations under the License.
  *
  * *****************************************************************/
+#include "iotivity_config.h"
 #include "gtest/gtest.h"
 #include "provisioningdatabasemanager.h"
 
index 3aaefeb..1d6cfd9 100644 (file)
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
+#include "iotivity_config.h"
 #ifdef HAVE_STRING_H
 #include <string.h>
-#elif HAVE_STRINGS_H
+#elif defined(HAVE_STRINGS_H)
 #include <strings.h>
 #endif
 #include <stdlib.h>
@@ -41,6 +42,7 @@
 #include "resourcemanager.h"
 #include "srmutility.h"
 #include "psinterface.h"
+#include "ocpayloadcbor.h"
 
 #include "security_internals.h"
 
@@ -635,6 +637,312 @@ exit:
 
 // This function converts CBOR format to ACL data.
 // Caller needs to invoke 'free' when done using
+// It parses { "aclist" : [ { ... } ] } instead of { "aclist" : { "aces" : [ ] } }
+OicSecAcl_t* CBORPayloadToAcl2(const uint8_t *cborPayload, const size_t size)
+{
+    if (NULL == cborPayload || 0 == size)
+    {
+        return NULL;
+    }
+    OCStackResult ret = OC_STACK_ERROR;
+    CborValue aclCbor = { .parser = NULL };
+    CborParser parser = { .end = NULL };
+    CborError cborFindResult = CborNoError;
+    cbor_parser_init(cborPayload, size, 0, &parser, &aclCbor);
+
+    OicSecAcl_t *acl = (OicSecAcl_t *) OICCalloc(1, sizeof(OicSecAcl_t));
+
+    // Enter ACL Map
+    CborValue aclMap = { .parser = NULL, .ptr = NULL, .remaining = 0, .extra = 0, .type = 0, .flags = 0 };
+    cborFindResult = cbor_value_enter_container(&aclCbor, &aclMap);
+    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering ACL Map.");
+
+    while (cbor_value_is_valid(&aclMap))
+    {
+        char* tagName = NULL;
+        size_t len = 0;
+        CborType type = cbor_value_get_type(&aclMap);
+        if (type == CborTextStringType)
+        {
+            cborFindResult = cbor_value_dup_text_string(&aclMap, &tagName, &len, NULL);
+            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Name in ACL Map.");
+            cborFindResult = cbor_value_advance(&aclMap);
+            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing Value in ACL Map.");
+        }
+        if(tagName)
+        {
+            if (strcmp(tagName, OIC_JSON_ACLIST_NAME)  == 0)
+            {
+                // Enter ACES Array
+                CborValue acesArray = { .parser = NULL, .ptr = NULL, .remaining = 0, .extra = 0, .type = 0, .flags = 0 };
+                cborFindResult = cbor_value_enter_container(&aclMap, &acesArray);
+                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering ACES Array.");
+
+                int acesCount = 0;
+                while (cbor_value_is_valid(&acesArray))
+                {
+                    acesCount++;
+                    CborValue aceMap = { .parser = NULL, .ptr = NULL, .remaining = 0, .extra = 0, .type = 0, .flags = 0 };
+                    cborFindResult = cbor_value_enter_container(&acesArray, &aceMap);
+                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering ACE Map.");
+
+                    OicSecAce_t *ace = NULL;
+                    ace = (OicSecAce_t *) OICCalloc(1, sizeof(OicSecAce_t));
+                    VERIFY_NON_NULL(TAG, ace, ERROR);
+                    LL_APPEND(acl->aces, ace);
+
+                    VERIFY_NON_NULL(TAG, acl, ERROR);
+
+                    while (cbor_value_is_valid(&aceMap))
+                    {
+                        char* name = NULL;
+                        size_t len = 0;
+                        CborType type = cbor_value_get_type(&aceMap);
+                        if (type == CborTextStringType)
+                        {
+                            cborFindResult = cbor_value_dup_text_string(&aceMap, &name, &len, NULL);
+                            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Name in ACE Map.");
+                            cborFindResult = cbor_value_advance(&aceMap);
+                            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing Value in ACE Map.");
+                        }
+                        if (name)
+                        {
+                            // Subject -- Mandatory
+                            if (strcmp(name, OIC_JSON_SUBJECTID_NAME)  == 0)
+                            {
+                                char *subject = NULL;
+                                cborFindResult = cbor_value_dup_text_string(&aceMap, &subject, &len, NULL);
+                                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding subject Value.");
+                                if(strcmp(subject, WILDCARD_RESOURCE_URI) == 0)
+                                {
+                                    ace->subjectuuid.id[0] = '*';
+                                }
+                                else
+                                {
+                                    OIC_LOG_V(DEBUG, TAG, "Converting subjectuuid = %s to uuid...", subject);
+                                    ret = ConvertStrToUuid(subject, &ace->subjectuuid);
+                                    VERIFY_SUCCESS(TAG, ret == OC_STACK_OK, ERROR);
+                                }
+                                OICFree(subject);
+                            }
+
+                            // Resources -- Mandatory
+                            if (strcmp(name, OIC_JSON_RESOURCES_NAME) == 0)
+                            {
+                                CborValue resources = { .parser = NULL };
+                                cborFindResult = cbor_value_enter_container(&aceMap, &resources);
+                                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering a Resource Array.");
+
+                                while (cbor_value_is_valid(&resources))
+                                {
+                                    // rMap
+                                    CborValue rMap = { .parser = NULL  };
+                                    cborFindResult = cbor_value_enter_container(&resources, &rMap);
+                                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering Resource Map");
+
+                                    OicSecRsrc_t* rsrc = (OicSecRsrc_t*)OICCalloc(1, sizeof(OicSecRsrc_t));
+                                    VERIFY_NON_NULL(TAG, rsrc, ERROR);
+                                    LL_APPEND(ace->resources, rsrc);
+
+                                    while(cbor_value_is_valid(&rMap))
+                                    {
+                                        char *rMapName = NULL;
+                                        size_t rMapNameLen = 0;
+                                        cborFindResult = cbor_value_dup_text_string(&rMap, &rMapName, &rMapNameLen, NULL);
+                                        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding RMap Data Name Tag.");
+                                        cborFindResult = cbor_value_advance(&rMap);
+                                        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding RMap Data Value.");
+
+                                        // "href"
+                                        if (0 == strcmp(OIC_JSON_HREF_NAME, rMapName))
+                                        {
+                                            cborFindResult = cbor_value_dup_text_string(&rMap, &rsrc->href, &len, NULL);
+                                            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Href Value.");
+                                        }
+
+                                        // "rt"
+                                        if (0 == strcmp(OIC_JSON_RT_NAME, rMapName) && cbor_value_is_array(&rMap))
+                                        {
+                                            cbor_value_get_array_length(&rMap, &rsrc->typeLen);
+                                            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding RT array length.");
+                                            VERIFY_SUCCESS(TAG, (0 != rsrc->typeLen), ERROR);
+
+                                            rsrc->types = (char**)OICCalloc(rsrc->typeLen, sizeof(char*));
+                                            VERIFY_NON_NULL(TAG, rsrc->types, ERROR);
+
+                                            CborValue resourceTypes;
+                                            cborFindResult = cbor_value_enter_container(&rMap, &resourceTypes);
+                                            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering RT Array.");
+
+                                            for(size_t i = 0; cbor_value_is_valid(&resourceTypes) && cbor_value_is_text_string(&resourceTypes); i++)
+                                            {
+                                                size_t readLen = 0;
+                                                cborFindResult = cbor_value_dup_text_string(&resourceTypes, &(rsrc->types[i]), &readLen, NULL);
+                                                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding resource type.");
+                                                cborFindResult = cbor_value_advance(&resourceTypes);
+                                                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing resource type.");
+                                            }
+                                        }
+
+                                        // "if"
+                                        if (0 == strcmp(OIC_JSON_IF_NAME, rMapName) && cbor_value_is_array(&rMap))
+                                        {
+                                            cbor_value_get_array_length(&rMap, &rsrc->interfaceLen);
+                                            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding IF array length.");
+                                            VERIFY_SUCCESS(TAG, (0 != rsrc->interfaceLen), ERROR);
+
+                                            rsrc->interfaces = (char**)OICCalloc(rsrc->interfaceLen, sizeof(char*));
+                                            VERIFY_NON_NULL(TAG, rsrc->interfaces, ERROR);
+
+                                            CborValue interfaces;
+                                            cborFindResult = cbor_value_enter_container(&rMap, &interfaces);
+                                            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering IF Array.");
+
+                                            for(size_t i = 0; cbor_value_is_valid(&interfaces) && cbor_value_is_text_string(&interfaces); i++)
+                                            {
+                                                size_t readLen = 0;
+                                                cborFindResult = cbor_value_dup_text_string(&interfaces, &(rsrc->interfaces[i]), &readLen, NULL);
+                                                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding IF type.");
+                                                cborFindResult = cbor_value_advance(&interfaces);
+                                                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing IF type.");
+                                            }
+                                        }
+
+                                        // "rel"
+                                        if (0 == strcmp(OIC_JSON_REL_NAME, rMapName))
+                                        {
+                                            cborFindResult = cbor_value_dup_text_string(&rMap, &rsrc->rel, &len, NULL);
+                                            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding REL Value.");
+                                        }
+
+                                        if (cbor_value_is_valid(&rMap))
+                                        {
+                                            cborFindResult = cbor_value_advance(&rMap);
+                                            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing Rlist Map.");
+                                        }
+                                        OICFree(rMapName);
+                                    }
+
+                                    if (cbor_value_is_valid(&resources))
+                                    {
+                                        cborFindResult = cbor_value_advance(&resources);
+                                        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing Resource Array.");
+                                    }
+                                }
+                            }
+
+                            // Permissions -- Mandatory
+                            if (strcmp(name, OIC_JSON_PERMISSION_NAME) == 0)
+                            {
+                                uint64_t tmp64;
+                                cborFindResult = cbor_value_get_uint64(&aceMap, &tmp64);
+                                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding a PERM Value.");
+                                ace->permission = (uint16_t)tmp64;
+                            }
+
+                            // TODO: Need to verfication for validity
+                            // Validity -- Not mandatory
+                            if(strcmp(name, OIC_JSON_VALIDITY_NAME) == 0)
+                            {
+                                CborValue validitiesMap = {.parser = NULL};
+                                size_t validitySize = 0;
+
+                                cborFindResult = cbor_value_get_array_length(&aceMap, &validitySize);
+                                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding a Validity Array Length.");
+
+                                cborFindResult = cbor_value_enter_container(&aceMap, &validitiesMap);
+                                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding a validity Array Map.");
+
+                                while(cbor_value_is_valid(&validitiesMap))
+                                {
+                                    OicSecValidity_t* validity = (OicSecValidity_t*)OICCalloc(1, sizeof(OicSecValidity_t));
+                                    VERIFY_NON_NULL(TAG, validity, ERROR);
+                                    LL_APPEND(ace->validities, validity);
+
+                                    CborValue validityMap  = {.parser = NULL};
+                                    //period (string)
+                                    cborFindResult = cbor_value_enter_container(&validitiesMap, &validityMap);
+                                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding a validity Map.");
+
+                                    size_t len = 0;
+                                    cborFindResult =cbor_value_dup_text_string(&validityMap, &validity->period, &len, NULL);
+                                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding a Period value.");
+
+                                    //recurrence (string array)
+                                    CborValue recurrenceMap  = {.parser = NULL};
+                                    cborFindResult = cbor_value_enter_container(&validityMap, &recurrenceMap);
+                                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding a recurrence array.");
+
+                                    cborFindResult = cbor_value_get_array_length(&recurrenceMap, &validity->recurrenceLen);
+                                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Adding Recurrence Array.");
+
+                                    validity->recurrences = (char**)OICCalloc(validity->recurrenceLen, sizeof(char*));
+                                    VERIFY_NON_NULL(TAG, validity->recurrences, ERROR);
+
+                                    for(size_t i = 0; cbor_value_is_text_string(&recurrenceMap) && i < validity->recurrenceLen; i++)
+                                    {
+                                        cborFindResult = cbor_value_dup_text_string(&recurrenceMap, &validity->recurrences[i], &len, NULL);
+                                        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding a recurrence Value.");
+
+                                        cborFindResult = cbor_value_advance(&recurrenceMap);
+                                        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing a recurrences Array.");
+                                    }
+
+                                    cborFindResult = cbor_value_advance(&validitiesMap);
+                                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing a validities Array.");
+                                }
+                            }
+                            OICFree(name);
+                        }
+
+                        if (type != CborMapType && cbor_value_is_valid(&aceMap))
+                        {
+                            cborFindResult = cbor_value_advance(&aceMap);
+                            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing the Array.");
+                        }
+                    }
+
+                    if (cbor_value_is_valid(&acesArray))
+                    {
+                        cborFindResult = cbor_value_advance(&acesArray);
+                        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing ACL Array.");
+                    }
+                }
+            }
+
+            //rownerID -- Mandatory
+            if (strcmp(tagName, OIC_JSON_ROWNERID_NAME)  == 0)
+            {
+                char *stRowner = NULL;
+                cborFindResult = cbor_value_dup_text_string(&aclMap, &stRowner, &len, NULL);
+                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Rownerid Value.");
+                OIC_LOG_V(DEBUG, TAG, "Converting rownerid = %s to uuid...", stRowner);
+                ret = ConvertStrToUuid(stRowner, &acl->rownerID);
+                VERIFY_SUCCESS(TAG, ret == OC_STACK_OK, ERROR);
+                OICFree(stRowner);
+            }
+            OICFree(tagName);
+        }
+        if (cbor_value_is_valid(&aclMap))
+        {
+            cborFindResult = cbor_value_advance(&aclMap);
+            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing ACL Map.");
+        }
+    }
+
+exit:
+    if (cborFindResult != CborNoError)
+    {
+        OIC_LOG(ERROR, TAG, "Failed to CBORPayloadToAcl");
+        DeleteACLList(acl);
+        acl = NULL;
+    }
+
+    return acl;
+}
+
+// This function converts CBOR format to ACL data.
+// Caller needs to invoke 'free' when done using
 // note: This function is used in unit test hence not declared static,
 OicSecAcl_t* CBORPayloadToAcl(const uint8_t *cborPayload, const size_t size)
 {
@@ -1430,7 +1738,6 @@ static OCEntityHandlerResult HandleACLPostRequest(const OCEntityHandlerRequest *
     if (payload)
     {
         OicSecAcl_t *newAcl = NULL;
-        OicSecAcl_t newAceList;
         OIC_LOG(DEBUG, TAG, "ACL payload from POST request << ");
         OIC_LOG_BUFFER(DEBUG, TAG, payload, size);
 
@@ -1442,7 +1749,6 @@ static OCEntityHandlerResult HandleACLPostRequest(const OCEntityHandlerRequest *
             OicSecAce_t* newAce = NULL;
             OicSecAce_t* tempAce1 = NULL;
             OicSecAce_t* tempAce2 = NULL;
-            newAceList.aces = NULL;
 
             LL_FOREACH_SAFE(newAcl->aces, newAce, tempAce1)
             {
@@ -1881,37 +2187,42 @@ const OicSecAce_t* GetACLResourceData(const OicUuid_t* subjectId, OicSecAce_t **
     return NULL;
 }
 
-OCStackResult InstallNewACL(const uint8_t *cborPayload, const size_t size)
+OCStackResult InstallNewACL2(const OicSecAcl_t* acl)
 {
     OCStackResult ret = OC_STACK_ERROR;
 
-    // Convert CBOR format to ACL data. This will also validate the ACL data received.
-    OicSecAcl_t* newAcl = CBORPayloadToAcl(cborPayload, size);
+    if (!acl)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
 
-    if (newAcl)
+    // Append the new ACL to existing ACL
+    OicSecAce_t* newAce = NULL;
+    LL_FOREACH(acl->aces, newAce)
     {
-        // Append the new ACL to existing ACL
-        OicSecAce_t* newAce = NULL;
-        LL_FOREACH(newAcl->aces, newAce)
-        {
-            LL_APPEND(gAcl->aces, newAce);
-        }
+        LL_APPEND(gAcl->aces, newAce);
+    }
 
-        size_t size = 0;
-        uint8_t *payload = NULL;
-        if (OC_STACK_OK == AclToCBORPayload(gAcl, &payload, &size))
-        {
-            if (UpdateSecureResourceInPS(OIC_JSON_ACL_NAME, payload, size) == OC_STACK_OK)
-            {
-                ret = OC_STACK_OK;
-            }
-            OICFree(payload);
-        }
+    size_t size = 0;
+    uint8_t *payload = NULL;
+    ret = AclToCBORPayload(gAcl, &payload, &size);
+    if (OC_STACK_OK == ret)
+    {
+        ret = UpdateSecureResourceInPS(OIC_JSON_ACL_NAME, payload, size);
+        OICFree(payload);
     }
 
     return ret;
 }
 
+OCStackResult InstallNewACL(const uint8_t *cborPayload, const size_t size)
+{
+    // Convert CBOR format to ACL data. This will also validate the ACL data received.
+    OicSecAcl_t* newAcl = CBORPayloadToAcl(cborPayload, size);
+
+    return InstallNewACL2(newAcl);
+}
+
 /**
  * This function generates default ACE for security resource in case of owned status.
  *
index c208d3f..e348969 100644 (file)
@@ -322,12 +322,9 @@ exit:
 OCStackResult UpdateAmsMgrContext(PEContext_t *context, const CAEndpoint_t *endpoint,
                         const CARequestInfo_t *requestInfo)
 {
-    OCStackResult ret = OC_STACK_ERROR;
-
-    if (!context->amsMgrContext)
-    {
-        goto exit;
-    }
+    OCStackResult ret = OC_STACK_INVALID_PARAM;
+    VERIFY_NON_NULL(TAG, context->amsMgrContext, ERROR);
+    ret = OC_STACK_ERROR;
 
     //The AmsMgr context endpoint and requestInfo will be free from ,
     //AmsMgrAclReqCallback function
index 2e2bba5..4dc8699 100644 (file)
@@ -20,6 +20,7 @@
 
 #define __STDC_LIMIT_MACROS
 
+#include "iotivity_config.h"
 #include <stdlib.h>
 #ifdef HAVE_STRING_H
 #include <string.h>
@@ -28,6 +29,7 @@
 #include <strings.h>
 #endif
 #include <stdint.h>
+#include <stdbool.h>
 
 #include "cainterface.h"
 #include "payload_logging.h"
 #include "psinterface.h"
 #include "pinoxmcommon.h"
 
+#ifdef __unix__
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <unistd.h>
+#endif
+
 #ifdef __WITH_DTLS__
 #include "global.h"
 #endif
 
 #define TAG  "SRM-CREDL"
 
+/** Max credential types number used for TLS */
+#define MAX_TYPE 2
 /** Default cbor payload size. This value is increased in case of CborErrorOutOfMemory.
  * The value of payload size is increased until reaching belox max cbor size. */
 static const uint16_t CBOR_SIZE = 2048;
@@ -118,6 +129,34 @@ void DeleteCredList(OicSecCred_t* cred)
     }
 }
 
+size_t GetCredKeyDataSize(const OicSecCred_t* cred)
+{
+    size_t size = 0;
+    if (cred)
+    {
+        OicSecCred_t *credPtr = NULL, *credTmp = NULL;
+        LL_FOREACH_SAFE((OicSecCred_t*)cred, credPtr, credTmp)
+        {
+            if (credPtr->privateData.data && 0 < credPtr->privateData.len)
+            {
+                size += credPtr->privateData.len;
+            }
+#if defined(__WITH_X509__) || defined(__WITH_TLS__)
+            if (credPtr->publicData.data && 0 < credPtr->publicData.len)
+            {
+                size += credPtr->publicData.len;
+            }
+            if (credPtr->optionalData.data && 0 < credPtr->optionalData.len)
+            {
+                size += credPtr->optionalData.len;
+            }
+#endif
+        }
+    }
+    OIC_LOG_V(DEBUG, TAG, "Cred Key Data Size : %d\n", size);
+    return size;
+}
+
 static size_t OicSecCredCount(const OicSecCred_t *secCred)
 {
     size_t size = 0;
@@ -261,8 +300,8 @@ OCStackResult CredToCBORPayload(const OicSecCred_t *credS, uint8_t **cborPayload
             cborEncoderResult = cbor_encode_text_string(&publicMap, OIC_JSON_ENCODING_NAME,
                 strlen(OIC_JSON_ENCODING_NAME));
             VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Public Encoding Tag.");
-            cborEncoderResult = cbor_encode_text_string(&publicMap, OIC_SEC_ENCODING_RAW,
-                strlen(OIC_SEC_ENCODING_RAW));
+            cborEncoderResult = cbor_encode_text_string(&publicMap, OIC_SEC_ENCODING_DER,
+                strlen(OIC_SEC_ENCODING_DER));
             VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Public Encoding Value.");
 
             cborEncoderResult = cbor_encoder_close_container(&credMap, &publicMap);
@@ -413,6 +452,22 @@ OCStackResult CredToCBORPayload(const OicSecCred_t *credS, uint8_t **cborPayload
                     cred->privateData.len);
                 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Priv Value.");
             }
+            else if(OIC_ENCODING_DER == cred->privateData.encoding)
+            {
+                cborEncoderResult = cbor_encode_text_string(&privateMap, OIC_JSON_ENCODING_NAME,
+                    strlen(OIC_JSON_ENCODING_NAME));
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Private Encoding Tag.");
+                cborEncoderResult = cbor_encode_text_string(&privateMap, OIC_SEC_ENCODING_DER,
+                    strlen(OIC_SEC_ENCODING_DER));
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Private Encoding Value.");
+
+                cborEncoderResult = cbor_encode_text_string(&privateMap, OIC_JSON_DATA_NAME,
+                    strlen(OIC_JSON_DATA_NAME));
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Priv Tag.");
+                cborEncoderResult = cbor_encode_byte_string(&privateMap, cred->privateData.data,
+                    cred->privateData.len);
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Priv Value.");
+            }
             else
             {
                 OIC_LOG(ERROR, TAG, "Unknow encoding type for private data.");
@@ -993,7 +1048,9 @@ static bool UpdatePersistentStorage(const OicSecCred_t *cred)
     if (cred)
     {
         uint8_t *payload = NULL;
-        size_t size = 0;
+        // This added '256' is arbitrary value that is added to cover the name of the resource, map addition and ending
+        size_t size = GetCredKeyDataSize(cred);
+        size += (256 * OicSecCredCount(cred));
         int secureFlag = 0;
         OCStackResult res = CredToCBORPayload(cred, &payload, &size, secureFlag);
         if ((OC_STACK_OK == res) && payload)
@@ -1419,6 +1476,11 @@ static OCEntityHandlerResult HandleGetRequest (const OCEntityHandlerRequest * eh
     int secureFlag = 1;
 
     const OicSecCred_t *cred = gCred;
+
+    size_t credCnt = 0;
+    // This added '256' is arbitrary value that is added to cover the name of the resource, map addition and ending
+    size = GetCredKeyDataSize(cred);
+    size += (256 * OicSecCredCount(cred));
     OCStackResult res = CredToCBORPayload(cred, &payload, &size, secureFlag);
 
     // A device should always have a default cred. Therefore, payload should never be NULL.
@@ -1864,6 +1926,10 @@ OCStackResult SetCredRownerId(const OicUuid_t* newROwner)
         memcpy(prevId.id, gCred->rownerID.id, sizeof(prevId.id));
         memcpy(gCred->rownerID.id, newROwner->id, sizeof(newROwner->id));
 
+        size_t credCnt = 0;
+        // This added '256' is arbitrary value that is added to cover the name of the resource, map addition and ending
+        size = GetCredKeyDataSize(gCred);
+        size += (256 * OicSecCredCount(gCred));
         ret = CredToCBORPayload(gCred, &cborPayload, &size, secureFlag);
         VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
 
@@ -1895,14 +1961,19 @@ OCStackResult GetCredRownerId(OicUuid_t *rowneruuid)
 #ifdef __WITH_TLS__
 void GetDerCaCert(ByteArray * crt)
 {
+    if (NULL == crt)
+    {
+        return;
+    }
     uint8_t *data = NULL;
+    crt->len = 0;
     OCStackResult ret = OC_STACK_ERROR;
     OicSecCred_t * cred;
     OicSecCred_t * temp = NULL;
-    OIC_LOG(DEBUG, TAG, "IN GetDerCaCert");
+    OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
     LL_FOREACH(gCred, temp)
     {
-        if (0==memcmp((temp->credUsage), TRUST_CA, sizeof(TRUST_CA)))
+        if (SIGNED_ASYMMETRIC_KEY == temp->credType && 0 == memcmp((temp->credUsage), TRUST_CA, sizeof(TRUST_CA)))
         {
             OIC_LOG_V(DEBUG, TAG, "len: %d, crt len: %d", temp->optionalData.len, crt->len);
             if(OIC_ENCODING_BASE64 == temp->optionalData.encoding)
@@ -1930,33 +2001,115 @@ void GetDerCaCert(ByteArray * crt)
             OIC_LOG_V(DEBUG, TAG, "Trust CA Found!! %d", crt->len);
         }
     }
-    if(!crt->len) OIC_LOG(DEBUG, TAG, "Trust CA Not Found!!");
+    if(0 == crt->len)
+    {
+        OIC_LOG(DEBUG, TAG, "Trust CA Not Found!!");
+    }
+    OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
     return;
 }
 
-
-void GetDerKey(ByteArray * key)
+void GetDerOwnCert(ByteArray * crt)
 {
-    // TODO Add implementation
-    key->data = NULL;
-    key->len = 0;
+    if (NULL == crt)
+    {
+        return;
+    }
+    crt->len = 0;
+    uint8_t *data = NULL;
+    OicSecCred_t * temp = NULL;
+    OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
+    LL_FOREACH(gCred, temp)
+    {
+        if (SIGNED_ASYMMETRIC_KEY == temp->credType && 0 == memcmp((temp->credUsage), PRIMARY_CERT, sizeof(PRIMARY_CERT)))
+        {
+            OIC_LOG_V(DEBUG, TAG, "len: %d, crt len: %d", temp->publicData.len, crt->len);
+            crt->data = OICRealloc(crt->data, crt->len + temp->publicData.len);
+            memcpy(crt->data + crt->len, temp->publicData.data, temp->publicData.len);
+            crt->len += temp->publicData.len;
+
+            OIC_LOG_V(DEBUG, TAG, "Trust CA Found!! %d", crt->len);
+        }
+    }
+    if(0 == crt->len)
+    {
+        OIC_LOG(DEBUG, TAG, "Trust CA Not Found!!");
+    }
+    OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
     return;
 }
 
-void GetDerOwnCert(ByteArray * cert)
+void GetDerKey(ByteArray * key)
 {
-    // TODO Add implementation
-    cert->data = NULL;
-    cert->len = 0;
-    return;
+    if (NULL == key)
+    {
+        return;
+    }
+
+    uint8_t *data = NULL;
+    OicSecCred_t * temp = NULL;
+    key->len = 0;
+    OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
+    LL_FOREACH(gCred, temp)
+    {
+        if (SIGNED_ASYMMETRIC_KEY == temp->credType && 0 == memcmp((temp->credUsage), PRIMARY_CERT, sizeof(PRIMARY_CERT)))
+        {
+            OIC_LOG_V(DEBUG, TAG, "len: %d, key len: %d", temp->privateData.len, key->len);
+            key->data = OICRealloc(key->data, key->len + temp->privateData.len);
+            memcpy(key->data + key->len, temp->privateData.data, temp->privateData.len);
+            key->len += temp->privateData.len;
+
+            OIC_LOG_V(DEBUG, TAG, "Key Found!! %d", key->len);
+        }
+    }
+    if(0 == key->len) 
+    {
+        OIC_LOG(DEBUG, TAG, "Key Not Found!!");
+    }
+    OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
 }
-void GetPkixInfo(PkiInfo_t * inf)
+
+void InitCipherSuiteList(bool * list)
 {
     OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
-    GetDerOwnCert(&inf->crt);
-    GetDerKey(&inf->key);
-    GetDerCaCert(&inf->ca);
+    if (NULL == list)
+    {
+        OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
+        OIC_LOG(DEBUG, TAG, "NULL list param");
+        return;
+    }
+    OicSecCred_t * temp = NULL;
+    LL_FOREACH(gCred, temp)
+    {
+        switch (temp->credType)
+        {
+            case SYMMETRIC_PAIR_WISE_KEY:
+            {
+                list[0] = true;
+                OIC_LOG(DEBUG, TAG, "SYMMETRIC_PAIR_WISE_KEY found");
+                break;
+            }
+            case SIGNED_ASYMMETRIC_KEY:
+            {
+                list[1] = true;
+                OIC_LOG(DEBUG, TAG, "SIGNED_ASYMMETRIC_KEY found");
+                break;
+            }
+            case SYMMETRIC_GROUP_KEY:
+            case ASYMMETRIC_KEY:
+            case PIN_PASSWORD:
+            case ASYMMETRIC_ENCRYPTION_KEY:
+            {
+                OIC_LOG(WARNING, TAG, "Unsupported credential type for TLS.");
+                break;
+            }
+            default:
+            {
+                OIC_LOG(WARNING, TAG, "Unknow credential type for TLS.");
+                break;
+            }
+        }
+    }
     OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
 }
-
 #endif
index a8b4fd8..6b1aaff 100644 (file)
 #include "doxmresource.h"
 #include "ocpayload.h"
 #include "oic_malloc.h"
+#include "oic_string.h"
 #include "crlresource.h"
 #include "crl.h"
+#include "ocpayloadcbor.h"
+#include "base64.h"
+#include <time.h>
 
 #define TAG  "SRM-CRL"
 
@@ -42,7 +46,9 @@
 #define OIC_CBOR_CRL_DATA           "CRLData"
 #define CRL_DEFAULT_CRL_ID          (1)
 #define CRL_DEFAULT_THIS_UPDATE     "150101000000Z"
+#define CRL_DEFAULT_LAST_UPDATE     "20150701000000"
 #define CRL_DEFAULT_CRL_DATA        "-"
+#define CRL_MAP_SIZE                (3)
 
 static OCResourceHandle     gCrlHandle  = NULL;
 static OicSecCrl_t         *gCrl        = NULL;
@@ -54,10 +60,7 @@ static const uint16_t CBOR_SIZE = 1024;
 // Max cbor size payload.
 static const uint16_t CBOR_MAX_SIZE = 4400;
 
-// PSTAT Map size - Number of mandatory items
-static const uint8_t CRL_MAP_SIZE = 3;
-
-void DeleteCrlBinData(OicSecCrl_t *crl)
+void DeleteCrl(OicSecCrl_t *crl)
 {
     if (crl)
     {
@@ -72,7 +75,213 @@ void DeleteCrlBinData(OicSecCrl_t *crl)
     }
 }
 
-OCStackResult CrlToCBORPayload(const OicSecCrl_t *crl, uint8_t **payload, size_t *size)
+static void printCrl(const OicSecCrl_t *crl)
+{
+    OIC_LOG(DEBUG, TAG, "Crl object contain:");
+    OIC_LOG_V(DEBUG, TAG, "id = %d", crl->CrlId);
+    OIC_LOG_V(DEBUG, TAG, "this update = %s", crl->ThisUpdate.data);
+
+    OIC_LOG(DEBUG, TAG, "crl:");
+    OIC_LOG_V(DEBUG, TAG, "encoding = %d", crl->CrlData.encoding);
+    OIC_LOG_V(DEBUG, TAG, "data (length = %zu):", crl->CrlData.len);
+    OIC_LOG_BUFFER(DEBUG, TAG, crl->CrlData.data, crl->CrlData.len);
+}
+
+static bool copyByteArray(const uint8_t *in, size_t in_len, uint8_t **out, size_t *out_len)
+{
+    OICFree(*out);
+    uint8_t *tmp = OICMalloc(in_len);
+    if (!tmp)
+    {
+        return false;
+    }
+    memcpy(tmp, in, in_len);
+    *out = tmp;
+    *out_len = in_len;
+    return true;
+}
+
+static bool copyCrl(const OicSecCrl_t *in, OicSecCrl_t *out)
+{
+    bool result = false;
+
+    if (!in || !out)
+    {
+        OIC_LOG(ERROR, TAG, "in or out crl is NULL");
+        return false;
+    }
+
+    out->CrlId = in->CrlId;
+
+    result = copyByteArray(in->ThisUpdate.data, in->ThisUpdate.len, &out->ThisUpdate.data, &out->ThisUpdate.len);
+    if (!result)
+    {
+        OIC_LOG(ERROR, TAG, "Can't allocate memory for ThisUpdate");
+        return false;
+    }
+
+    result = copyByteArray(in->CrlData.data, in->CrlData.len, &out->CrlData.data, &out->CrlData.len);
+    if (!result)
+    {
+        OIC_LOG(ERROR, TAG, "Can't allocate memory for CrlData");
+        return false;
+    }
+
+    return result;
+}
+
+static CborError setPubDataType(CborEncoder *out, const char *name, const OicSecKey_t *value)
+{
+    if (!out || !name || !value)
+    {
+        OIC_LOG_V(ERROR, TAG, "%s: null input params", __func__);
+        return CborErrorInternalError;
+    }
+
+    CborEncoder map;
+
+    const char *encoding = NULL;
+    bool binary_field = false;
+
+    size_t mapSize = 0;
+
+    mapSize++;
+    switch(value->encoding)
+    {
+        case OIC_ENCODING_RAW:
+            binary_field = true;
+            encoding = OIC_SEC_ENCODING_RAW;
+            break;
+        case OIC_ENCODING_BASE64:
+            encoding = OIC_SEC_ENCODING_BASE64;
+            break;
+        case OIC_ENCODING_DER:
+            binary_field = true;
+            encoding = OIC_SEC_ENCODING_DER;
+            break;
+        case OIC_ENCODING_PEM:
+            encoding = OIC_SEC_ENCODING_PEM;
+            break;
+        default:
+            OIC_LOG(ERROR, TAG, "Received UNKNOWN encoding, exit!");
+            return CborErrorInternalError;
+    }
+
+    if (value->data)
+    {
+        mapSize++;
+    }
+
+    CborError result = CborNoError;
+    result = cbor_encode_text_string(out, name, strlen(name));
+    VERIFY_CBOR_SUCCESS(TAG, result, "Failed Adding name Tag.");
+
+    result = cbor_encoder_create_map(out, &map, mapSize);
+    VERIFY_CBOR_SUCCESS(TAG, result, "Failed creating name map");
+
+    if (encoding)
+    {
+        result = cbor_encode_text_string(&map, OIC_JSON_ENCODING_NAME,
+                                         strlen(OIC_JSON_ENCODING_NAME));
+        VERIFY_CBOR_SUCCESS(TAG, result, "Failed to add encoding tag.")
+        result = cbor_encode_text_string(&map, encoding, strlen(encoding));
+        VERIFY_CBOR_SUCCESS(TAG, result, "Failed to add encoding value.");
+    };
+
+    if (value->data)
+    {
+        result = cbor_encode_text_string(&map, OIC_JSON_DATA_NAME, strlen(OIC_JSON_DATA_NAME));
+        VERIFY_CBOR_SUCCESS(TAG, result, "Failed to add data tag.");
+        if (binary_field)
+        {
+            result = cbor_encode_byte_string(&map, value->data, value->len);
+        }
+        else
+        {
+            result = cbor_encode_text_string(&map, (const char *)value->data, value->len);
+        }
+        VERIFY_CBOR_SUCCESS(TAG, result, "Failed to add data value.");
+    }
+
+    result = cbor_encoder_close_container(out, &map);
+    VERIFY_CBOR_SUCCESS(TAG, result, "Failed Closing PrivateData Map.");
+
+exit:
+    return result;
+}
+
+static CborError getPubDataType(CborValue *in, const char *name, OicSecKey_t *value)
+{
+    if (!in || !name || !value)
+    {
+        OIC_LOG_V(ERROR, TAG, "%s: null input params", __func__);
+        return CborErrorInternalError;
+    }
+
+    CborError result = CborNoError;
+    char *encoding = NULL;
+
+    CborValue crlNode = { .parser = NULL };
+    result = cbor_value_map_find_value(in, name, &crlNode);
+    if (CborNoError == result && cbor_value_is_map(&crlNode))
+    {
+        CborValue crlMap = { .parser = NULL };
+        result = cbor_value_enter_container(&crlNode, &crlMap);
+
+        while(cbor_value_is_valid(&crlMap) && cbor_value_is_text_string(&crlMap))
+        {
+            char *property = NULL;
+            size_t length = 0;
+            result = cbor_value_dup_text_string(&crlMap, &property, &length, NULL);
+            VERIFY_CBOR_SUCCESS(TAG, result, "Failed Get first crl ojbject tag.");
+            result = cbor_value_advance(&crlMap);
+            VERIFY_CBOR_SUCCESS(TAG, result, "Failed to advance crlMap");
+
+            if (0 == strcmp(OIC_JSON_DATA_NAME, property))
+            {
+                if (cbor_value_is_byte_string(&crlMap))
+                {
+                    result = cbor_value_dup_byte_string(&crlMap, &value->data, &value->len, NULL);
+                }
+                else if(cbor_value_is_text_string(&crlMap))
+                {
+                    char *buffer = NULL;
+                    result = cbor_value_dup_text_string(&crlMap, &buffer, &value->len, NULL);
+                    value->data = (uint8_t *)buffer;
+                }
+                else
+                {
+                    result = CborErrorUnknownType;
+                    OIC_LOG(ERROR, TAG, "Unknown type for crl->data.");
+                }
+                VERIFY_CBOR_SUCCESS(TAG, result, "Failed to read crl->data");
+            }
+            else if (0 == strcmp(OIC_JSON_ENCODING_NAME, property))
+            {
+                size_t encoding_len = 0;
+                result = cbor_value_dup_text_string(&crlMap, &encoding, &encoding_len, NULL);
+                VERIFY_CBOR_SUCCESS(TAG, result, "Failed to read crl->encdoing");
+            }
+            OICFree(property);
+        }
+    }
+    VERIFY_CBOR_SUCCESS(TAG, result, "Failed to find root node");
+
+    if (encoding)
+    {
+        OicEncodingType_t type = OIC_ENCODING_UNKNOW;
+        if (0 == strcmp(encoding, OIC_SEC_ENCODING_BASE64)) type = OIC_ENCODING_BASE64;
+        else if (0 == strcmp(encoding, OIC_SEC_ENCODING_DER)) type = OIC_ENCODING_DER;
+        else if (0 == strcmp(encoding, OIC_SEC_ENCODING_PEM)) type = OIC_ENCODING_PEM;
+        else if (0 == strcmp(encoding, OIC_SEC_ENCODING_RAW)) type = OIC_ENCODING_RAW;
+
+        value->encoding = type;
+    }
+exit:
+    return result;
+}
+
+OCStackResult CrlToCBORPayload(const OicSecCrl_t *crl, uint8_t **payload, size_t *size, char *lastUpdate)
 {
     if (NULL == crl || NULL == payload || NULL != *payload || NULL == size)
     {
@@ -88,6 +297,14 @@ OCStackResult CrlToCBORPayload(const OicSecCrl_t *crl, uint8_t **payload, size_t
     *payload = NULL;
     *size = 0;
 
+    size_t mapSize = CRL_MAP_SIZE;
+    if (lastUpdate)
+    {
+        mapSize++;
+    }
+
+    printCrl(crl);
+
     OCStackResult ret = OC_STACK_ERROR;
 
     CborEncoder encoder;
@@ -99,31 +316,37 @@ OCStackResult CrlToCBORPayload(const OicSecCrl_t *crl, uint8_t **payload, size_t
     VERIFY_NON_NULL(TAG, outPayload, ERROR);
     cbor_encoder_init(&encoder, outPayload, cborLen, 0);
 
-    cborEncoderResult = cbor_encoder_create_map(&encoder, &crlMap, CRL_MAP_SIZE);
+    cborEncoderResult = cbor_encoder_create_map(&encoder, &crlMap, mapSize);
     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to create CRL Map");
 
     //CRLId -- Mandatory
-    cborEncoderResult = cbor_encode_text_string(&crlMap, OIC_CBOR_CRL_ID,
-        strlen(OIC_CBOR_CRL_ID));
+    cborEncoderResult = cbor_encode_text_string(&crlMap, OC_RSRVD_CRL_ID,
+        strlen(OC_RSRVD_CRL_ID));
     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to add CRL ID");
     cborEncoderResult = cbor_encode_int(&crlMap, crl->CrlId);
     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to add CRL Id value");
 
     //ThisUpdate -- Mandatory
-    cborEncoderResult = cbor_encode_text_string(&crlMap, OIC_CBOR_CRL_THIS_UPDATE,
-        strlen(OIC_CBOR_CRL_THIS_UPDATE));
+    cborEncoderResult = cbor_encode_text_string(&crlMap, OC_RSRVD_THIS_UPDATE,
+        strlen(OC_RSRVD_THIS_UPDATE));
     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to add Crl update");
-    cborEncoderResult = cbor_encode_byte_string(&crlMap, crl->ThisUpdate.data,
+    cborEncoderResult = cbor_encode_text_string(&crlMap, (const char *)crl->ThisUpdate.data,
                                                 crl->ThisUpdate.len);
     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to add Crl Update value");
 
     //CRLData -- Mandatory
-    cborEncoderResult = cbor_encode_text_string(&crlMap, OIC_CBOR_CRL_DATA,
-        strlen(OIC_CBOR_CRL_DATA));
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to add Crl data name");
-    cborEncoderResult = cbor_encode_byte_string(&crlMap, crl->CrlData.data,
-                                                crl->CrlData.len);
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to add Crl data value");
+    cborEncoderResult = setPubDataType(&crlMap, OC_RSRVD_CRL, &crl->CrlData);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to add CRLData object");
+
+    //lastUpdate - internal field
+    if (lastUpdate)
+    {
+        cborEncoderResult = cbor_encode_text_string(&crlMap, OC_RSRVD_LAST_UPDATE,
+            strlen(OC_RSRVD_LAST_UPDATE));
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to add last Update tag");
+        cborEncoderResult = cbor_encode_text_string(&crlMap, lastUpdate, strlen(lastUpdate));
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to add last Update value");
+    }
 
     cborEncoderResult = cbor_encoder_close_container(&encoder, &crlMap);
     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to add close Crl map");
@@ -140,7 +363,7 @@ exit:
         // Since the allocated initial memory failed, double the memory.
         cborLen += encoder.ptr - encoder.end;
         cborEncoderResult = CborNoError;
-        ret = CrlToCBORPayload(crl, payload, &cborLen);
+        ret = CrlToCBORPayload(crl, payload, &cborLen, lastUpdate);
     }
 
     if ((CborNoError != cborEncoderResult) || (OC_STACK_OK != ret))
@@ -164,7 +387,7 @@ OCStackResult CBORPayloadToCrl(const uint8_t *cborPayload, const size_t size,
     }
 
     OCStackResult ret = OC_STACK_ERROR;
-    *secCrl = NULL;
+    OicSecCrl_t *crl = NULL;
 
     CborValue crlCbor = {.parser = NULL};
     CborParser parser = {.end = NULL};
@@ -172,15 +395,13 @@ OCStackResult CBORPayloadToCrl(const uint8_t *cborPayload, const size_t size,
 
     cbor_parser_init(cborPayload, size, 0, &parser, &crlCbor);
     CborValue crlMap = { .parser = NULL};
-    OicSecCrl_t *crl = NULL;
-    size_t outLen = 0;
     cborFindResult = cbor_value_enter_container(&crlCbor, &crlMap);
     VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to enter Crl map");
 
     crl = (OicSecCrl_t *)OICCalloc(1, sizeof(OicSecCrl_t));
     VERIFY_NON_NULL(TAG, crl, ERROR);
 
-    cborFindResult = cbor_value_map_find_value(&crlCbor, OIC_CBOR_CRL_ID, &crlMap);
+    cborFindResult = cbor_value_map_find_value(&crlCbor, OC_RSRVD_CRL_ID, &crlMap);
     if (CborNoError == cborFindResult && cbor_value_is_integer(&crlMap))
     {
         int CrlId;
@@ -190,84 +411,75 @@ OCStackResult CBORPayloadToCrl(const uint8_t *cborPayload, const size_t size,
         crl->CrlId = (uint16_t)CrlId;
     }
 
-    cborFindResult = cbor_value_map_find_value(&crlCbor, OIC_CBOR_CRL_THIS_UPDATE, &crlMap);
-    if (CborNoError == cborFindResult && cbor_value_is_byte_string(&crlMap))
-    {
-        cborFindResult = cbor_value_dup_byte_string(&crlMap,
-            &crl->ThisUpdate.data, &crl->ThisUpdate.len, NULL);
-        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing Byte Array.");
-    }
-    cborFindResult = cbor_value_map_find_value(&crlCbor, OIC_CBOR_CRL_DATA, &crlMap);
-    if (CborNoError == cborFindResult && cbor_value_is_byte_string(&crlMap))
+    cborFindResult = cbor_value_map_find_value(&crlCbor, OC_RSRVD_THIS_UPDATE, &crlMap);
+    if (CborNoError == cborFindResult && cbor_value_is_text_string(&crlMap))
     {
-        cborFindResult = cbor_value_dup_byte_string(&crlMap,
-                         &crl->CrlData.data, &crl->CrlData.len, NULL);
+        cborFindResult = cbor_value_dup_text_string(&crlMap,
+                (char **)&crl->ThisUpdate.data, &crl->ThisUpdate.len, NULL);
         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing Byte Array.");
     }
 
+    cborFindResult = getPubDataType(&crlCbor, OC_RSRVD_CRL, &crl->CrlData);
+    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to read CRL.");
+
+    printCrl(crl);
+
     *secCrl = crl;
     ret = OC_STACK_OK;
 exit:
     if (CborNoError != cborFindResult)
     {
         // PUT/POST CBOR may not have mandatory values set default values.
-        if (gCrl)
-        {
-            OIC_LOG (DEBUG, TAG, "Set default values");
-            crl->CrlId = gCrl->CrlId;
-            if (crl->ThisUpdate.data)
-            {
-                OICFree(crl->ThisUpdate.data);
-            }
-            outLen = gCrl->ThisUpdate.len;
-            crl->ThisUpdate.data = (uint8_t*) OICMalloc(outLen);
-            if (crl->ThisUpdate.data)
-            {
-                memcpy(crl->ThisUpdate.data, gCrl->ThisUpdate.data, outLen);
-                crl->ThisUpdate.len = outLen;
-            }
-            else
-            {
-                crl->ThisUpdate.len = 0;
-                OIC_LOG(ERROR, TAG, "Set default failed");
-            }
-            if (crl->CrlData.data)
-            {
-                OICFree(crl->CrlData.data);
-            }
-            outLen = gCrl->CrlData.len;
-            crl->CrlData.data = (uint8_t*) OICMalloc(outLen);
-            if (crl->CrlData.data && gCrl->CrlData.data)
-            {
-                memcpy(crl->CrlData.data, gCrl->CrlData.data, outLen);
-                crl->CrlData.len = outLen;
-            }
-            else
-            {
-                crl->CrlData.len = 0;
-                OIC_LOG (ERROR, TAG, "Set default failed");
-            }
+        OIC_LOG (DEBUG, TAG, "Set default values");
 
+        if (copyCrl(gCrl, crl))
+        {
             *secCrl = crl;
             ret = OC_STACK_OK;
         }
         else
         {
-            OIC_LOG (ERROR, TAG, "CBORPayloadToCrl failed");
-            DeleteCrlBinData(crl);
+            DeleteCrl(crl);
             crl = NULL;
             ret = OC_STACK_ERROR;
+            OIC_LOG (ERROR, TAG, "Can't set default crl");
         }
     }
     return ret;
 }
 
-OCStackResult UpdateCRLResource(const OicSecCrl_t *crl)
+static void getCurrentUTCTime(char *out, size_t len)
 {
+    //TODO: how to implement it in cross-platform way?
+    time_t rawtime;
+    struct tm * timeinfo;
+
+    time ( &rawtime );
+    timeinfo = localtime ( &rawtime );
+
+    snprintf(out, len, "%04d%02d%02d%02d%02d%02d",
+            timeinfo->tm_year + 1900, timeinfo->tm_mon + 1, timeinfo->tm_mday,
+            timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec);
+}
+
+OCStackResult UpdateCRLResource(OicSecCrl_t *crl)
+{
+    static uint16_t crlid = 0;
     uint8_t *payload = NULL;
     size_t size = 0;
 
-    OCStackResult res = CrlToCBORPayload((OicSecCrl_t *) crl, &payload, &size);
+    crl->CrlId = crlid++;
+
+    if (!copyCrl(crl, gCrl))
+    {
+        OIC_LOG(ERROR, TAG, "Can't update global crl");
+        return OC_STACK_ERROR;
+    }
+
+    char currentTime[32] = {0};
+    getCurrentUTCTime(currentTime, sizeof(currentTime));
+
+    OCStackResult res = CrlToCBORPayload((const OicSecCrl_t *) crl, &payload, &size, currentTime);
     if (OC_STACK_OK != res)
     {
         return res;
@@ -285,31 +497,16 @@ static OCEntityHandlerResult HandleCRLPostRequest(const OCEntityHandlerRequest *
 
     if (payload)
     {
-        OIC_LOG(INFO, TAG, "UpdateSVRDB...");
+        OIC_LOG(INFO, TAG, "Update SVR DB...");
         CBORPayloadToCrl(payload, size, &crl);
         VERIFY_NON_NULL(TAG, crl, ERROR);
 
-        gCrl->CrlId = crl->CrlId;
-
-        OICFree(gCrl->ThisUpdate.data);
-        gCrl->ThisUpdate.data = NULL;
-        gCrl->ThisUpdate.data = OICMalloc(crl->ThisUpdate.len);
-        VERIFY_NON_NULL(TAG, gCrl->ThisUpdate.data, ERROR);
-        memcpy(gCrl->ThisUpdate.data, crl->ThisUpdate.data, crl->ThisUpdate.len);
-        gCrl->ThisUpdate.len = crl->ThisUpdate.len;
-
-        OICFree(gCrl->CrlData.data);
-        gCrl->CrlData.data = OICMalloc(crl->CrlData.len);
-        VERIFY_NON_NULL(TAG, gCrl->CrlData.data, ERROR);
-        memcpy(gCrl->CrlData.data, crl->CrlData.data, crl->CrlData.len);
-        gCrl->CrlData.len = crl->CrlData.len;
-
-        if (OC_STACK_OK == UpdateSecureResourceInPS(OIC_CBOR_CRL_NAME, payload, size))
+        if (OC_STACK_OK == UpdateCRLResource(crl))
         {
             ehRet = OC_EH_RESOURCE_CREATED;
         }
 
-        DeleteCrlBinData(crl);
+        DeleteCrl(crl);
     }
 
 exit:
@@ -399,28 +596,23 @@ static OicSecCrl_t *GetCrlDefault()
     {
         return NULL;
     }
+
     defaultCrl->CrlId = CRL_DEFAULT_CRL_ID;
 
-    defaultCrl->CrlData.len = strlen(CRL_DEFAULT_CRL_DATA);
-    defaultCrl->CrlData.data = (uint8_t*) OICMalloc(defaultCrl->CrlData.len);
-    if (defaultCrl->CrlData.data)
-    {
-        memcpy(defaultCrl->CrlData.data, CRL_DEFAULT_CRL_DATA, defaultCrl->CrlData.len);
-    }
-    else
-    {
-        defaultCrl->CrlData.len = 0;
-    }
+    bool result1 = copyByteArray((const uint8_t *)CRL_DEFAULT_CRL_DATA,
+                                 strlen(CRL_DEFAULT_CRL_DATA),
+                                 &defaultCrl->CrlData.data,
+                                 &defaultCrl->CrlData.len);
 
-    defaultCrl->ThisUpdate.len = strlen(CRL_DEFAULT_THIS_UPDATE);
-    defaultCrl->ThisUpdate.data = (uint8_t*) OICMalloc(defaultCrl->ThisUpdate.len);
-    if (defaultCrl->ThisUpdate.data)
-    {
-        memcpy(defaultCrl->ThisUpdate.data, CRL_DEFAULT_THIS_UPDATE, defaultCrl->ThisUpdate.len);
-    }
-    else
+    bool result2 = copyByteArray((const uint8_t *)CRL_DEFAULT_THIS_UPDATE,
+                                 strlen(CRL_DEFAULT_THIS_UPDATE),
+                                 &defaultCrl->ThisUpdate.data,
+                                 &defaultCrl->ThisUpdate.len);
+
+    if (!result1 || !result2)
     {
-        defaultCrl->ThisUpdate.len = 0;
+        DeleteCrl(defaultCrl);
+        return NULL;
     }
 
     return defaultCrl;
@@ -473,7 +665,7 @@ OCStackResult DeInitCRLResource()
 {
     OCStackResult result = OCDeleteResource(gCrlHandle);
     gCrlHandle = NULL;
-    DeleteCrlBinData(gCrl);
+    DeleteCrl(gCrl);
     gCrl = NULL;
     return result;
 }
@@ -505,6 +697,53 @@ OicSecCrl_t *GetCRLResource()
     return crl;
 }
 
+OCStackResult getLastUpdateFromDB(char **lastUpdate)
+{
+    OCStackResult result = OC_STACK_OK;
+
+    OCPayload *payload = NULL;
+    uint8_t *data = NULL;
+    size_t size = 0;
+
+    if (!lastUpdate)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    result = GetSecureVirtualDatabaseFromPS(OIC_CBOR_CRL_NAME, &data, &size);
+    if (result != OC_STACK_OK)
+    {
+        OIC_LOG(ERROR, TAG, "Can't get crl data from database");
+        goto exit;
+    }
+
+    result = OCParsePayload(&payload, PAYLOAD_TYPE_REPRESENTATION, data, size);
+    if (result != OC_STACK_OK)
+    {
+        OIC_LOG(ERROR, TAG, "Can't parse cbor data from DB");
+        goto exit;
+    }
+
+    if (!OCRepPayloadGetPropString((const OCRepPayload*)payload, OC_RSRVD_LAST_UPDATE, lastUpdate))
+    {
+        OIC_LOG_V(ERROR, TAG, "Can't get: %s", OC_RSRVD_LAST_UPDATE);
+        result = OC_STACK_ERROR;
+    }
+
+exit:
+    if (result != OC_STACK_OK)
+    {
+        OIC_LOG(DEBUG, TAG, "Assume you are first time get Crl, and it can be absent in database");
+        OIC_LOG_V(DEBUG, TAG, "Return default last update time %s", CRL_DEFAULT_LAST_UPDATE);
+
+        *lastUpdate = OICStrdup(CRL_DEFAULT_LAST_UPDATE);
+        result = OC_STACK_OK;
+    }
+    OCPayloadDestroy((OCPayload *)payload);
+
+    return result;
+}
+
 uint8_t *GetCrl()
 {
     uint8_t *data = NULL;
@@ -518,22 +757,63 @@ uint8_t *GetCrl()
     return NULL;
 }
 
-void  GetDerCrl(ByteArray* crlArray)
+void GetDerCrl(ByteArray* out)
 {
-    if(NULL == crlArray)
+    if(NULL == out)
+    {
+        return;
+    }
+
+    OicSecCrl_t *crlRes = GetCRLResource();
+
+    if(NULL == crlRes)
     {
         return;
     }
-    OicSecCrl_t * crlRes = GetCRLResource();
-    if (NULL != crlArray->data && NULL != crlRes
-        && NULL !=crlRes->CrlData.data && crlRes->CrlData.len <= crlArray->len)
+
+    OicSecKey_t *crl = &crlRes->CrlData;
+
+    if (OIC_ENCODING_BASE64 == crl->encoding)
+    {
+        size_t outSize = B64DECODE_OUT_SAFESIZE((crl->len + 1));
+        uint8_t *out = OICCalloc(1, outSize);
+        if (!out)
+        {
+            OIC_LOG(ERROR, TAG, "Can't allocate memory for base64 str");
+            return;
+        }
+        uint32_t len = 0;
+
+        if(B64_OK == b64Decode((char*)crl->data, crl->len, out, outSize, &len))
+        {
+            memcpy(crl->data, out, len);
+            crl->len = (size_t)len;
+
+            OIC_LOG (ERROR, TAG, "Crl successfully decoded to base64.");
+        }
+        else
+        {
+            OIC_LOG (ERROR, TAG, "Base64 decoding failed.");
+        }
+    }
+
+    out->len = 0;
+
+#ifdef __WITH_X509__
+    char *str = "Not enough space in out buffer to store crl!";
+    if (out->data && crl->data && crl->len <= out->len)
+#else
+    char *str = "Can't allocate memory for out->data";
+    out->data = OICMalloc(crl->len);
+    if (out->data)
+#endif
     {
-        memcpy(crlArray->data, crlRes->CrlData.data, crlRes->CrlData.len);
-        crlArray->len = crlRes->CrlData.len;
+        memcpy(out->data, crl->data, crl->len);
+        out->len = crl->len;
     }
     else
     {
-        crlArray->len = 0;
+        OIC_LOG_V(ERROR, TAG, "%s", str);
     }
-    DeleteCrlBinData(crlRes);
+    DeleteCrl(crlRes);
 }
index e7ef882..4bac266 100644 (file)
@@ -20,6 +20,7 @@
 #ifndef _POSIX_C_SOURCE\r
 #define _POSIX_C_SOURCE 200112L\r
 #endif\r
+#include "iotivity_config.h"\r
 #ifdef HAVE_UNISTD_H\r
 #include <unistd.h>\r
 #endif\r
@@ -253,8 +254,14 @@ bool DPGenerateQuery(bool isSecure,
 \r
     switch(connType & CT_MASK_ADAPTER)\r
     {\r
+// @todo: Remove this ifdef. On Arduino, CT_ADAPTER_TCP resolves to the same value\r
+// as CT_ADAPTER_IP, resulting in a compiler error.\r
+#ifdef WITH_TCP\r
+#ifndef WITH_ARDUINO\r
         case CT_ADAPTER_TCP:\r
             prefix = (isSecure == true) ? QPREFIX_COAPS_TCP : QPREFIX_COAP_TCP;\r
+#endif\r
+#endif\r
         case CT_ADAPTER_IP:\r
             switch(connType & CT_MASK_FLAGS & ~CT_FLAG_SECURE)\r
             {\r
index 9aac585..75a726c 100644 (file)
 // limitations under the License.
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#include "iotivity_config.h"
 #include <stdlib.h>
 #include <string.h>
 
-#if HAVE_STRINGS_H
+#ifdef HAVE_STRINGS_H
 #include <strings.h>
 #endif
 
@@ -59,9 +60,6 @@ static const uint16_t CBOR_SIZE = 512;
 /** Max cbor size payload. */
 static const uint16_t CBOR_MAX_SIZE = 4400;
 
-/** DOXM Map size - Number of mandatory items. */
-static const uint8_t DOXM_MAP_SIZE = 9;
-
 static OicSecDoxm_t        *gDoxm = NULL;
 static OCResourceHandle    gDoxmHandle = NULL;
 
@@ -130,21 +128,12 @@ OCStackResult DoxmToCBORPayload(const OicSecDoxm_t *doxm, uint8_t **payload, siz
     char* strUuid = NULL;
 
     int64_t cborEncoderResult = CborNoError;
-    uint8_t mapSize = DOXM_MAP_SIZE;
-    if (doxm->oxmTypeLen > 0)
-    {
-        mapSize++;
-    }
-    if (doxm->oxmLen > 0)
-    {
-        mapSize++;
-    }
 
     uint8_t *outPayload = (uint8_t *)OICCalloc(1, cborLen);
     VERIFY_NON_NULL(TAG, outPayload, ERROR);
     cbor_encoder_init(&encoder, outPayload, cborLen, 0);
 
-    cborEncoderResult = cbor_encoder_create_map(&encoder, &doxmMap, mapSize);
+    cborEncoderResult = cbor_encoder_create_map(&encoder, &doxmMap, CborIndefiniteLength);
     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Doxm Map.");
 
     //OxmType -- Not Mandatory
@@ -1205,6 +1194,61 @@ OCStackResult GetDoxmDeviceID(OicUuid_t *deviceID)
     return OC_STACK_ERROR;
 }
 
+OCStackResult SetDoxmDeviceID(const OicUuid_t *deviceID)
+{
+    bool isPT = false;
+
+    if(NULL == deviceID)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+    if(NULL == gDoxm)
+    {
+        OIC_LOG(ERROR, TAG, "Doxm resource is not initialized.");
+        return OC_STACK_NO_RESOURCE;
+    }
+
+    //Check the device's OTM state
+
+#ifdef __WITH_DTLS__}
+    //for normal device.
+    if(true == gDoxm->owned)
+    {
+        OIC_LOG(ERROR, TAG, "This device owned by owner's device.");
+        OIC_LOG(ERROR, TAG, "Device UUID cannot be changed to guarantee the reliability of the connection.");
+        return OC_STACK_ERROR;
+    }
+#endif //__WITH_DTLS
+
+    //Save the previous UUID
+    OicUuid_t tempUuid;
+    memcpy(tempUuid.id, gDoxm->deviceID.id, sizeof(tempUuid.id));
+
+    //Change the UUID
+    memcpy(gDoxm->deviceID.id, deviceID->id, sizeof(deviceID->id));
+    if(isPT)
+    {
+        memcpy(gDoxm->owner.id, deviceID->id, sizeof(deviceID->id));
+        memcpy(gDoxm->rownerID.id, deviceID->id, sizeof(deviceID->id));
+    }
+
+    //Update PS
+    if(!UpdatePersistentStorage(gDoxm))
+    {
+        //revert UUID in case of update error
+        memcpy(gDoxm->deviceID.id, tempUuid.id, sizeof(tempUuid.id));
+        if(isPT)
+        {
+            memcpy(gDoxm->owner.id, tempUuid.id, sizeof(tempUuid.id));
+            memcpy(gDoxm->rownerID.id, tempUuid.id, sizeof(tempUuid.id));
+        }
+
+        OIC_LOG(ERROR, TAG, "Failed to update persistent storage");
+        return OC_STACK_ERROR;
+    }
+    return OC_STACK_OK;
+}
+
 OCStackResult GetDoxmDevOwnerId(OicUuid_t *devownerid)
 {
     OCStackResult retVal = OC_STACK_ERROR;
index 820021a..534dcea 100644 (file)
@@ -18,6 +18,7 @@
  *
  * *****************************************************************/
 
+#include "iotivity_config.h"
 #include <stdlib.h>
 #include <string.h>
 #include "ocstack.h"
index dc16f4b..acb44f1 100644 (file)
@@ -22,6 +22,7 @@
 #if !defined(WITH_ARDUINO)
 
 #define _XOPEN_SOURCE  //Needed by strptime
+#include "iotivity_config.h"
 #include <string.h>
 #include "iotvticalendar.h"
 #include "oic_string.h"
index 84bbf48..b216e62 100644 (file)
@@ -18,6 +18,7 @@
  *
  * *****************************************************************/
 
+#include "iotivity_config.h"
 #include <stdlib.h>
 #include <string.h>
 #include "ocstack.h"
diff --git a/resource/csdk/security/src/pkix_interface.c b/resource/csdk/security/src/pkix_interface.c
new file mode 100644 (file)
index 0000000..8949aa6
--- /dev/null
@@ -0,0 +1,36 @@
+//******************************************************************
+//
+// Copyright 2016 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#include "pkix_interface.h"
+#include "credresource.h"
+#include "crlresource.h"
+#include "logger.h"
+
+#define TAG "SRM-PKIX-INTERFACE"
+
+void GetPkixInfo(PkiInfo_t * inf)
+{
+    OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
+    GetDerOwnCert(&inf->crt);
+    GetDerKey(&inf->key);
+    GetDerCaCert(&inf->ca);
+    GetDerCrl(&inf->crl);
+    OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
+}
index d660058..bb5fab1 100644 (file)
@@ -183,6 +183,7 @@ OCStackResult UpdateSecureResourceInPS(const char *rsrcName, const uint8_t *psPa
     uint8_t *credCbor = NULL;
     uint8_t *pconfCbor = NULL;
     uint8_t *resetPfCbor = NULL;
+    uint8_t *crlCbor = NULL;
 
     int64_t cborEncoderResult = CborNoError;
     OCStackResult ret = GetSecureVirtualDatabaseFromPS(NULL, &dbData, &dbSize);
@@ -196,6 +197,7 @@ OCStackResult UpdateSecureResourceInPS(const char *rsrcName, const uint8_t *psPa
         size_t credCborLen = 0;
         size_t pconfCborLen = 0;
         size_t resetPfCborLen = 0;
+        size_t crlCborLen = 0;
 
         // Gets each secure virtual resource from persistent storage
         // this local scoping intended, for destroying large cbor instances after use
@@ -254,13 +256,26 @@ OCStackResult UpdateSecureResourceInPS(const char *rsrcName, const uint8_t *psPa
                 cborFindResult = cbor_value_dup_byte_string(&curVal, &resetPfCbor, &resetPfCborLen, NULL);
                 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Reset Profile Name Value.");
             }
+            int64_t cborFindCrlResult = cbor_value_map_find_value(&cbor, OIC_JSON_CRL_NAME, &curVal);
+            if (CborNoError == cborFindCrlResult && cbor_value_is_byte_string(&curVal))
+            {
+                cborFindCrlResult = cbor_value_dup_byte_string(&curVal, &crlCbor, &crlCborLen, NULL);
+                if (CborNoError != cborFindCrlResult && CborErrorOutOfMemory != cborFindCrlResult)
+                {
+                    OIC_LOG(ERROR, TAG, "Failed Finding optional CRL Name Value.");
+                }
+                else
+                {
+                    OIC_LOG(INFO, TAG, "Successfully Finding optional CRL Name Value.");
+                }
+            }
         }
 
         // Updates the added |psPayload| with the existing secure virtual resource(s)
         // this local scoping intended, for destroying large cbor instances after use
         {
             size_t size = aclCborLen + pstatCborLen + doxmCborLen + amaclCborLen
-                        + svcCborLen + credCborLen + pconfCborLen + resetPfCborLen
+                        + svcCborLen + credCborLen + pconfCborLen + resetPfCborLen + crlCborLen
                         + psSize + 255;
             // This added '255' is arbitrary value that is added to cover the name of the resource, map addition and ending
 
@@ -335,6 +350,13 @@ OCStackResult UpdateSecureResourceInPS(const char *rsrcName, const uint8_t *psPa
                 cborEncoderResult |= cbor_encode_byte_string(&secRsrc, resetPfCbor, resetPfCborLen);
                 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Reset Profile Value.");
             }
+            if (strcmp(OIC_JSON_CRL_NAME, rsrcName) && crlCborLen)
+            {
+                cborEncoderResult |= cbor_encode_text_string(&secRsrc, OIC_JSON_CRL_NAME, strlen(OIC_JSON_CRL_NAME));
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Crl Name.");
+                cborEncoderResult |= cbor_encode_byte_string(&secRsrc, crlCbor, crlCborLen);
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Crl Value.");
+            }
 
             cborEncoderResult |= cbor_encoder_close_container(&encoder, &secRsrc);
             VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Array.");
@@ -405,6 +427,7 @@ exit:
     OICFree(credCbor);
     OICFree(pconfCbor);
     OICFree(resetPfCbor);
+    OICFree(crlCbor);
     return ret;
 }
 
index 198b62a..f4b6ecf 100644 (file)
@@ -40,9 +40,9 @@
 
 #define TAG "SRM-RM"
 
-#ifdef __WITH_X509__
+#if defined(__WITH_X509__) || defined(__WITH_TLS__)
 #include "crlresource.h"
-#endif // __WITH_X509__
+#endif // __WITH_X509__ || __WITH_TLS__
 
 OCStackResult SendSRMResponse(const OCEntityHandlerRequest *ehRequest,
         OCEntityHandlerResult ehRet, uint8_t *cborPayload, size_t size)
@@ -92,12 +92,12 @@ OCStackResult InitSecureResources( )
     {
         ret = InitCredResource();
     }
-#ifdef __WITH_X509__
+#if defined(__WITH_X509__) || defined(__WITH_TLS__)
     if(OC_STACK_OK == ret)
     {
         ret = InitCRLResource();
     }
-#endif // __WITH_X509__
+#endif // __WITH_X509__ || __WITH_TLS__
     if(OC_STACK_OK == ret)
     {
         ret = InitSVCResource();
@@ -134,9 +134,9 @@ OCStackResult DestroySecureResources( )
     DeInitCredResource();
     DeInitDoxmResource();
     DeInitPstatResource();
-#ifdef __WITH_X509__
+#if defined(__WITH_X509__) || defined(__WITH_TLS__)
     DeInitCRLResource();
-#endif // __WITH_X509__
+#endif // __WITH_X509__ || __WITH_TLS__
     DeInitSVCResource();
     DeInitAmaclResource();
 //#ifdef DIRECT_PAIRING
index c39d463..f9644d4 100644 (file)
@@ -32,7 +32,9 @@
 #include "securevirtualresourcetypes.h"
 #include "secureresourcemanager.h"
 #include "srmresourcestrings.h"
-
+#ifdef __WITH_TLS__
+#include "pkix_interface.h"
+#endif //__WITH_TLS__
 #define TAG  "SRM"
 
 #ifdef __WITH_X509__
@@ -325,12 +327,13 @@ OCStackResult SRMInitSecureResources()
     }
 #endif
 #ifdef __WITH_TLS__
-    if(CA_STATUS_OK != CAregisterTlsCredentialsHandler(GetDtlsPskCredentials))
+    if (CA_STATUS_OK != CAregisterTlsCredentialsHandler(GetDtlsPskCredentials))
     {
         OIC_LOG(ERROR, TAG, "Failed to revert TLS credential handler.");
         ret = OC_STACK_ERROR;
     }
     CAregisterPkixInfoHandler(GetPkixInfo);
+    CAregisterGetCredentialTypesHandler(InitCipherSuiteList);
 #endif
 #if defined(__WITH_X509__)
     CARegisterDTLSX509CredentialsHandler(GetDtlsX509Credentials);
@@ -373,6 +376,7 @@ bool SRMIsSecurityResourceURI(const char* uri)
         OIC_RSRC_PCONF_URI,
         OIC_RSRC_DPAIRING_URI,
         OIC_RSRC_VER_URI,
+        OC_RSRVD_PROV_CRL_URL
     };
 
     // Remove query from Uri for resource string comparison
index c05e529..4dcea24 100644 (file)
@@ -147,6 +147,7 @@ const char * OIC_JSON_SEC_V_NAME = "secv";
 const char * OIC_JSON_EMPTY_STRING = "";
 
 const char * TRUST_CA = "trust_ca";
+const char * PRIMARY_CERT = "primary_cert";
 
 OicUuid_t WILDCARD_SUBJECT_ID = {"*"};
 OicUuid_t WILDCARD_SUBJECT_B64_ID = { .id = {'2', '2', '2', '2', '2', '2', '2', '2',
index 96afacc..78725a7 100644 (file)
  *
  * *****************************************************************/
 
+#include "iotivity_config.h"
 #include <stdlib.h>
 #include <string.h>
 
-#if HAVE_STRINGS_H
+#ifdef HAVE_STRINGS_H
 #include <strings.h>
 #endif
 
index 6c3c995..871e7a9 100644 (file)
@@ -26,6 +26,14 @@ src_dir = tools_env.get('SRC_DIR')
 ######################################################################
 # Build flags
 ######################################################################
+with_upstream_libcoap = tools_env.get('WITH_UPSTREAM_LIBCOAP')
+if with_upstream_libcoap == '1':
+    # For bring up purposes only, we manually copy the forked version to where the unforked version is downloaded.
+    tools_env.AppendUnique(CPPPATH = ['#extlibs/libcoap/libcoap/include'])
+else:
+    # For bring up purposes only, the forked version will live here.
+    tools_env.AppendUnique(CPPPATH = ['../../connectivity/lib/libcoap-4.1.1/include'])
+
 tools_env.PrependUnique(CPPPATH = ['../../../../extlibs/cjson',
                                   '../../stack/include',
                                   '../../stack/include/internal',
@@ -34,13 +42,11 @@ tools_env.PrependUnique(CPPPATH = ['../../../../extlibs/cjson',
                                   '../../connectivity/api',
                                   '../../connectivity/inc/pkix',
                                   '../include',
-                                  '../include/internal',
-                                  '../../connectivity/lib/libcoap-4.1.1',
-
+                                  '../include/internal'
                                   ])
 tools_env.AppendUnique(CXXFLAGS = ['-O2', '-g', '-Wall', '-Wextra', '-std=c++0x'])
-tools_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
-tools_env.AppendUnique(RPATH = [env.get('BUILD_DIR')])
+tools_env.AppendUnique(LIBPATH = [tools_env.get('BUILD_DIR')])
+tools_env.AppendUnique(RPATH = [tools_env.get('BUILD_DIR')])
 tools_env.PrependUnique(LIBS = ['oc', 'octbstack'])
 
 ######################################################################
index 3e4c594..b67de92 100644 (file)
@@ -30,13 +30,20 @@ target_os = srmtest_env.get('TARGET_OS')
 ######################################################################
 # Build flags
 ######################################################################
+with_upstream_libcoap = srmtest_env.get('WITH_UPSTREAM_LIBCOAP')
+if with_upstream_libcoap == '1':
+       # For bring up purposes only, we manually copy the forked version to where the unforked version is downloaded.
+       srmtest_env.AppendUnique(CPPPATH = ['#extlibs/libcoap/libcoap/include'])
+else:
+       # For bring up purposes only, the forked version will live here.
+       srmtest_env.AppendUnique(CPPPATH = ['../../connectivity/lib/libcoap-4.1.1/include'])
+
 srmtest_env.PrependUnique(CPPPATH = [
                '../../../c_common/oic_malloc/include',
                '../../connectivity/inc',
                '../../connectivity/inc/pkix',
                '../../connectivity/api',
                '../../connectivity/external/inc',
-               '../../connectivity/lib/libcoap-4.1.1',
                '../include/internal',
                '../../logger/include',
                '../../stack/include',
@@ -64,7 +71,6 @@ if srmtest_env.get('LOGGING') == '1':
        srmtest_env.AppendUnique(CPPDEFINES = ['TB_LOG'])
 
 if target_os == 'windows':
-       srmtest_env.AppendUnique(LINKFLAGS = ['/subsystem:CONSOLE'])
        srmtest_env.AppendUnique(LIBS = ['advapi32', 'kernel32', 'ws2_32', 'iphlpapi'])
 else:
        # TODO: Implement feature check.
index dbf4cb8..c20e297 100644 (file)
@@ -19,7 +19,7 @@
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
 #include "gtest/gtest.h"
-#include "utlist.h"
+#include <coap/utlist.h>
 #include <sys/stat.h>
 #include "ocstack.h"
 #include "psinterface.h"
index 90f189d..df46f27 100644 (file)
@@ -18,6 +18,7 @@
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
+#include "iotivity_config.h"
 #ifdef HAVE_UNISTD_H
 #include <unistd.h>
 #endif
index 2917709..9a38f48 100644 (file)
@@ -18,6 +18,7 @@
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
+#include "iotivity_config.h"
 #include "gtest/gtest.h"
 #ifdef HAVE_PWD_H
 #include <pwd.h>
index a8de15f..c093284 100644 (file)
@@ -136,33 +136,6 @@ typedef struct
 } OCServerProtocolRequest;
 
 /**
- * This structure will be created in occoap and passed up the stack on the client side.
- */
-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").*/
-    char * fullUri;
-
-    /** This is the relative Uri of the resource. (ex. "/a/led").*/
-    char * rcvdUri;
-
-    /** This is the received payload.*/
-    char * bufRes;
-
-    /** This is the token received OTA.*/
-    CAToken_t rcvdToken;
-
-    /** this structure will be passed to client.*/
-    OCClientResponse * clientResponse;
-} OCResponse;
-
-/**
  * This typedef is to represent our Server Instance identification.
  */
 typedef uint8_t ServerID[16];
index a301830..7a7c4a0 100644 (file)
 #include <inttypes.h>
 #include "octypes.h"
 
+#ifdef __WITH_TLS__
+#include "securevirtualresourcetypes.h"
+#endif
+
 #ifdef __cplusplus
 extern "C"
 {
@@ -137,6 +141,12 @@ bool OCRepPayloadSetPropObject(OCRepPayload* payload, const char* name, const OC
 bool OCRepPayloadSetPropObjectAsOwner(OCRepPayload* payload, const char* name, OCRepPayload* value);
 bool OCRepPayloadGetPropObject(const OCRepPayload* payload, const char* name, OCRepPayload** value);
 
+#ifdef __WITH_TLS__
+bool OCRepPayloadSetPropPubDataType(OCRepPayload *payload, const char *name, const OicSecKey_t *value);
+bool OCRepPayloadSetPropPubDataTypeAsOwner(OCRepPayload *payload, const char *name, const OicSecKey_t *value);
+bool OCRepPayloadGetPropPubDataType(const OCRepPayload *payload, const char *name, OicSecKey_t *value);
+#endif
+
 /**
  * This function allocates memory for the byte string array and sets it in the payload.
  *
@@ -274,6 +284,14 @@ OCStringLL* OCCreateOCStringLL(const char* text);
  **/
 char* OCCreateString(const OCStringLL* ll);
 
+/**
+ * This function copies contents (and allocates if necessary)
+ * @param dest existing bytestring (or null to allocate here)
+ * @param source existing bytestring
+ * @return true of success false on any errors
+ **/
+bool OCByteStringCopy(OCByteString *dest, const OCByteString *source);
+
 #ifdef __cplusplus
 }
 #endif
index f168df2..ad06006 100644 (file)
@@ -558,6 +558,15 @@ const OCDPDev_t* OCGetDirectPairedDevices();
 OCStackResult OCDoDirectPairing(void *ctx, OCDPDev_t* peer, OCPrm_t pmSel, char *pinNumber,
                                 OCDirectPairingCB resultCallback);
 
+#ifdef WITH_CHPROXY
+/**
+ * This function sets uri being used for proxy.
+ *
+ * @param uri            NULL terminated resource uri for CoAP-HTTP Proxy.
+ */
+OCStackResult OCSetProxyURI(const char *uri);
+#endif
+
 #if defined(RD_CLIENT) || defined(RD_SERVER)
 /**
  * This function binds an resource unique id to the resource.
index 96afa7a..8eed88d 100644 (file)
  * Maximum length of the URI supported by client/server while processing
  * REST requests/responses.
  */
+#ifdef ARDUINO
+#define MAX_URI_LENGTH (64)
+#else
 #define MAX_URI_LENGTH (256)
+#endif
 
 /**
  * Maximum length of the query supported by client/server while processing
  * REST requests/responses.
  */
+#ifdef ARDUINO
+#define MAX_QUERY_LENGTH (64)
+#else
 #define MAX_QUERY_LENGTH (256)
+#endif
 
 /**
  * Maximum length of the Manufacturer name supported by the server
  *  Maximum number of vendor specific header options an application can set or receive
  *  in PDU
  */
-#define MAX_HEADER_OPTIONS (100)
+#ifdef ARDUINO
+#define MAX_HEADER_OPTIONS (2)
+#else
+#define MAX_HEADER_OPTIONS (50)
+#endif
 
 /**
  *  Maximum Length of the vendor specific header option
  */
+#ifdef ARDUINO
 #define MAX_HEADER_OPTION_DATA_LENGTH (20)
+#else
+#define MAX_HEADER_OPTION_DATA_LENGTH (1024)
+#endif
 
 /**
  * Sets the time to live (TTL) for response callback(s).
index 2ae83e4..7fd01d8 100644 (file)
@@ -28,7 +28,7 @@
 #ifndef OCTYPES_H_
 #define OCTYPES_H_
 
-#include "platform_features.h"
+#include "iotivity_config.h"
 #include "ocstackconfig.h"
 #include <stdbool.h>
 #include <stdint.h>
@@ -329,6 +329,12 @@ extern "C" {
 /** RD Discovery bias factor type. */
 #define OC_RSRVD_RD_DISCOVERY_SEL        "sel"
 
+/** Resource URI used to discover Proxy */
+#define OC_RSRVD_PROXY_URI "/oic/chp"
+
+/** Resource URI used to discover Proxy */
+#define OC_RSRVD_PROXY_OPTION_ID 35
+
 /** Base URI. */
 #define OC_RSRVD_BASE_URI                "baseURI"
 
@@ -421,15 +427,124 @@ extern "C" {
 /** Defines private. */
 #define OC_RSRVD_PRIVATE                   "Private"
 
-/** Defines options. */
+/** Defines invite. */
 #define OC_RSRVD_INVITE                    "invite"
 
-/** Defines options. */
-#define OC_RSRVD_OPTIONS                   "options"
-
 /** To represent grant type with refresh token. */
 #define OC_RSRVD_GRANT_TYPE_REFRESH_TOKEN  "refresh_token"
 
+/** Cloud CRL */
+#define OC_RSRVD_PROV_CRL_URL              "/oic/credprov/crl"
+
+#define OC_RSRVD_LAST_UPDATE              "lu"
+
+#define OC_RSRVD_THIS_UPDATE              "tu"
+
+#define OC_RSRVD_NEXT_UPDATE              "nu"
+
+#define OC_RSRVD_SERIAL_NUMBERS           "rcsn"
+
+#define OC_RSRVD_CRL                      "crl"
+
+#define OC_RSRVD_CRL_ID                   "crlid"
+
+/** Cloud ACL */
+#define OC_RSRVD_GROUP_URL                "/oic/group"
+
+#define OC_RSRVD_ACL_GROUP_URL            "/oic/acl/group"
+
+#define OC_RSRVD_ACL_INVITE_URL           "/oic/acl/invite"
+
+#define OC_RSRVD_ACL_VERIFY_URL           "/oic/acl/verify"
+
+#define OC_RSRVD_ACL_ID_URL               "/oic/acl/id"
+
+#define OC_RSRVD_MEMBER_ID                "mid"
+
+#define OC_RSRVD_GROUP_ID                 "gid"
+
+#define OC_RSRVD_OWNER_ID                 "oid"
+
+#define OC_RSRVD_ACL_ID                   "aclid"
+
+#define OC_RSRVD_ACE_ID                   "aceid"
+
+#define OC_RSRVD_DEVICE_ID                "di"
+
+#define OC_RSRVD_SUBJECT_ID               "sid"
+
+#define OC_RSRVD_REQUEST_METHOD           "rm"
+
+#define OC_RSRVD_REQUEST_URI              "uri"
+
+#define OC_RSRVD_GROUP_MASTER_ID          "gmid"
+
+#define OC_RSRVD_GROUP_TYPE               "gtype"
+
+#define OC_RSRVD_SUBJECT_TYPE             "stype"
+
+#define OC_RSRVD_GROUP_ID_LIST            "gidlist"
+
+#define OC_RSRVD_MEMBER_ID_LIST           "midlist"
+
+#define OC_RSRVD_DEVICE_ID_LIST           "dilist"
+
+#define OC_RSRVD_ACCESS_CONTROL_LIST      "aclist"
+
+#define OC_RSRVD_RESOURCES                "resources"
+
+#define OC_RSRVD_VALIDITY                 "validity"
+
+#define OC_RSRVD_PERIOD                   "period"
+
+#define OC_RSRVD_RECURRENCE               "recurrence"
+
+#define OC_RSRVD_INVITE                   "invite"
+
+#define OC_RSRVD_INVITED                  "invited"
+
+#define OC_RSRVD_ENCODING                 "encoding"
+
+#define OC_OIC_SEC                        "oic.sec"
+
+#define OC_RSRVD_BASE64                   "base64"
+
+#define OC_RSRVD_DER                      "der"
+
+#define OC_RSRVD_PEM                      "pem"
+
+#define OC_RSRVD_RAW                      "raw"
+
+#define OC_RSRVD_UNKNOWN                  "unknown"
+
+#define OC_RSRVD_DATA                     "data"
+
+#define OC_RSRVD_RESOURCE_OWNER_UUID      "rowneruuid"
+
+#define OC_RSRVD_SUBJECT_UUID             "subjectuuid"
+
+#define OC_RSRVD_PERMISSION_MASK          "permission"
+
+#define OC_RSRVD_GROUP_PERMISSION         "gp"
+
+#define OC_RSRVD_GROUP_ACL                "gacl"
+
+/** Certificete Sign Request */
+#define OC_RSRVD_PROV_CERT_URI            "/oic/credprov/cert"
+
+#define OC_RSRVD_CSR                      "csr"
+
+#define OC_RSRVD_CERT                     "cert"
+
+#define OC_RSRVD_CACERT                   "certchain"
+
+#define OC_RSRVD_TOKEN_TYPE               "tokentype"
+
+#define OC_RSRVD_EXPIRES_IN               "expiresin"
+
+#define OC_RSRVD_REDIRECT_URI             "redirecturi"
+
+#define OC_RSRVD_CERTIFICATE              "certificate"
 /**
  * Mark a parameter as unused. Used to prevent unused variable compiler warnings.
  * Used in three cases:
@@ -700,6 +815,7 @@ typedef enum
 typedef enum
 {
     OC_FORMAT_CBOR,
+    OC_FORMAT_JSON,
     OC_FORMAT_UNDEFINED,
     OC_FORMAT_UNSUPPORTED,
 } OCPayloadFormat;
@@ -960,21 +1076,25 @@ typedef enum
 {
     OC_EH_OK = 0,
     OC_EH_ERROR,
-    OC_EH_RESOURCE_CREATED, // 2.01
-    OC_EH_RESOURCE_DELETED, // 2.02
-    OC_EH_SLOW, // 2.05
-    OC_EH_FORBIDDEN, // 4.03
-    OC_EH_RESOURCE_NOT_FOUND, // 4.04
-    OC_EH_VALID,   // 2.03
-    OC_EH_CHANGED, // 2.04
-    OC_EH_CONTENT, // 2.05
-    OC_EH_BAD_REQ, // 4.00
-    OC_EH_UNAUTHORIZED_REQ, // 4.01
-    OC_EH_BAD_OPT, // 4.02
-    OC_EH_METHOD_NOT_ALLOWED, // 4.05
-    OC_EH_NOT_ACCEPTABLE, // 4.06
-    OC_EH_INTERNAL_SERVER_ERROR, // 5.00
-    OC_EH_RETRANSMIT_TIMEOUT // 5.04
+    OC_EH_SLOW,
+    OC_EH_RESOURCE_CREATED = 201,
+    OC_EH_RESOURCE_DELETED = 202,
+    OC_EH_VALID = 203,
+    OC_EH_CHANGED = 204,
+    OC_EH_CONTENT = 205,
+    OC_EH_BAD_REQ = 400,
+    OC_EH_UNAUTHORIZED_REQ = 401,
+    OC_EH_BAD_OPT = 402,
+    OC_EH_FORBIDDEN = 403,
+    OC_EH_RESOURCE_NOT_FOUND = 404,
+    OC_EH_METHOD_NOT_ALLOWED = 405,
+    OC_EH_NOT_ACCEPTABLE = 406,
+    OC_EH_TOO_LARGE = 413,
+    OC_EH_UNSUPPORTED_MEDIA_TYPE = 415,
+    OC_EH_INTERNAL_SERVER_ERROR = 500,
+    OC_EH_BAD_GATEWAY = 502,
+    OC_EH_SERVICE_UNAVAILABLE = 503,
+    OC_EH_RETRANSMIT_TIMEOUT = 504
 } OCEntityHandlerResult;
 
 /**
@@ -1116,7 +1236,7 @@ typedef enum
     /** The payload is an OCPresencePayload */
     PAYLOAD_TYPE_PRESENCE,
     /** The payload is an OCRDPayload */
-    PAYLOAD_TYPE_RD
+    PAYLOAD_TYPE_RD,
 } OCPayloadType;
 
 /**
@@ -1645,7 +1765,7 @@ typedef OCEntityHandlerResult (*OCDeviceEntityHandler)
  *
  * @param[OUT] ctx - user context returned in the callback.
  * @param[OUT] peer - pairing device info.
- * @param[OUT} result - It's returned with 'OC_STACK_XXX'. It will return 'OC_STACK_OK'
+ * @param[OUT] result - It's returned with 'OC_STACK_XXX'. It will return 'OC_STACK_OK'
  *                                   if D2D pairing is success without error
  */
 typedef void (*OCDirectPairingCB)(void *ctx, OCDPDev_t *peer, OCStackResult result);
index 5f722f4..5f3a8c1 100644 (file)
@@ -35,6 +35,7 @@
 #include <inttypes.h>
 #include "rdpayload.h"
 #include "oic_malloc.h"
+#include "ocpayload.h"
 
 #ifdef __cplusplus
 extern "C"
@@ -137,119 +138,116 @@ INLINE_API void OCLinksLog(const LogLevel level, const OCLinksPayload *links)
     }
 }
 #endif
-INLINE_API void OCPayloadLogRep(LogLevel level, OCRepPayload* payload)
+
+//forward declaration required because function below is recursive
+INLINE_API void OCPayloadLogRep(LogLevel level, OCRepPayload* payload);
+
+INLINE_API void OCPayloadLogRepValues(LogLevel level, OCRepPayloadValue* val)
 {
-    OIC_LOG(level, (PL_TAG), "Payload Type: Representation");
-    OCRepPayload* rep = payload;
-    int i = 1;
-    while(rep)
+    while(val)
     {
-        OIC_LOG_V(level, PL_TAG, "\tResource #%d", i);
-        OIC_LOG_V(level, PL_TAG, "\tURI:%s", rep->uri);
-        OIC_LOG(level, PL_TAG, "\tResource Types:");
-        OCStringLL* strll =  rep->types;
-        while(strll)
-        {
-            OIC_LOG_V(level, PL_TAG, "\t\t%s", strll->value);
-            strll = strll->next;
-        }
-        OIC_LOG(level, PL_TAG, "\tInterfaces:");
-        strll =  rep->interfaces;
-        while(strll)
+        switch(val->type)
         {
-            OIC_LOG_V(level, PL_TAG, "\t\t%s", strll->value);
-            strll = strll->next;
-        }
+            case OCREP_PROP_NULL:
+                OIC_LOG_V(level, PL_TAG, "%s: NULL", val->name);
+                break;
+            case OCREP_PROP_INT:
+                OIC_LOG_V(level, PL_TAG, "%s(int):%zd", val->name, val->i);
+                break;
+            case OCREP_PROP_DOUBLE:
+                OIC_LOG_V(level, PL_TAG, "%s(double):%f", val->name, val->d);
+                break;
+            case OCREP_PROP_BOOL:
+                OIC_LOG_V(level, PL_TAG, "%s(bool):%s", val->name, val->b ? "true" : "false");
+                break;
+            case OCREP_PROP_STRING:
+                OIC_LOG_V(level, PL_TAG, "%s(string):%s", val->name, val->str);
+                break;
+            case OCREP_PROP_BYTE_STRING:
+                OIC_LOG_V(level, PL_TAG, "%s(binary):", val->name);
+                OIC_LOG_BUFFER(level, PL_TAG, val->ocByteStr.bytes, val->ocByteStr.len);
+                break;
+            case OCREP_PROP_OBJECT:
+                OIC_LOG_V(level, PL_TAG, "%s(OCRep):%s", val->name, val->obj->uri);
+                OCPayloadLogRep(level, val->obj);
+                break;
+            case OCREP_PROP_ARRAY:
+            {
+                size_t len = calcDimTotal(val->arr.dimensions);
 
-        // TODO Finish Logging: Values
-        OCRepPayloadValue* val = rep->values;
+                OIC_LOG_V(level, PL_TAG, "%s(array): length = %zu", val->name, len);
 
-        OIC_LOG(level, PL_TAG, "\tValues:");
+                for (size_t i = 0; i < len; i++)
+                {
+                    OIC_LOG_V(level, PL_TAG, "%s[%zu]:", val->name, i);
+                    char *indent = (char *)"\t\t";
 
-        while(val)
-        {
-            switch(val->type)
-            {
-                case OCREP_PROP_NULL:
-                    OIC_LOG_V(level, PL_TAG, "\t\t%s: NULL", val->name);
-                    break;
-                case OCREP_PROP_INT:
-                    OIC_LOG_V(level, PL_TAG, "\t\t%s(int):%zd", val->name, val->i);
-                    break;
-                case OCREP_PROP_DOUBLE:
-                    OIC_LOG_V(level, PL_TAG, "\t\t%s(double):%f", val->name, val->d);
-                    break;
-                case OCREP_PROP_BOOL:
-                    OIC_LOG_V(level, PL_TAG, "\t\t%s(bool):%s", val->name, val->b ? "true" : "false");
-                    break;
-                case OCREP_PROP_STRING:
-                    OIC_LOG_V(level, PL_TAG, "\t\t%s(string):%s", val->name, val->str);
-                    break;
-                case OCREP_PROP_BYTE_STRING:
-                    OIC_LOG_V(level, PL_TAG, "\t\t%s(binary):", val->name);
-                    OIC_LOG_BUFFER(level, PL_TAG, val->ocByteStr.bytes, val->ocByteStr.len);
-                    break;
-                case OCREP_PROP_OBJECT:
-                    // Note: Only prints the URI (if available), to print further, you'll
-                    // need to dig into the object better!
-                    OIC_LOG_V(level, PL_TAG, "\t\t%s(OCRep):%s", val->name, val->obj->uri);
-                    break;
-                case OCREP_PROP_ARRAY:
                     switch(val->arr.type)
                     {
                         case OCREP_PROP_INT:
-                            OIC_LOG_V(level, PL_TAG, "\t\t%s(int array):%zu x %zu x %zu",
-                                    val->name,
-                                    val->arr.dimensions[0], val->arr.dimensions[1],
-                                    val->arr.dimensions[2]);
+                            OIC_LOG_V(level, PL_TAG, "%s%zd", indent, val->arr.iArray[i]);
                             break;
                         case OCREP_PROP_DOUBLE:
-                            OIC_LOG_V(level, PL_TAG, "\t\t%s(double array):%zu x %zu x %zu",
-                                    val->name,
-                                    val->arr.dimensions[0], val->arr.dimensions[1],
-                                    val->arr.dimensions[2]);
+                            OIC_LOG_V(level, PL_TAG, "%s%f", indent, val->arr.dArray[i]);
                             break;
                         case OCREP_PROP_BOOL:
-                            OIC_LOG_V(level, PL_TAG, "\t\t%s(bool array):%zu x %zu x %zu",
-                                    val->name,
-                                    val->arr.dimensions[0], val->arr.dimensions[1],
-                                    val->arr.dimensions[2]);
+                            OIC_LOG_V(level, PL_TAG, "%s%s", indent, val->arr.bArray[i] ? "true" : "false");
                             break;
                         case OCREP_PROP_STRING:
-                            OIC_LOG_V(level, PL_TAG, "\t\t%s(string array):%zu x %zu x %zu",
-                                    val->name,
-                                    val->arr.dimensions[0], val->arr.dimensions[1],
-                                    val->arr.dimensions[2]);
+                            OIC_LOG_V(level, PL_TAG, "%s%s", indent, val->arr.strArray[i]);
                             break;
                         case OCREP_PROP_BYTE_STRING:
-                            OIC_LOG_V(level, PL_TAG, "\t\t%s(byte array):%zu x %zu x %zu",
-                                    val->name,
-                                    val->arr.dimensions[0], val->arr.dimensions[1],
-                                    val->arr.dimensions[2]);
+                        {
+                            OCByteString* data = &val->arr.ocByteStrArray[i];
+                            OIC_LOG_V(level, PL_TAG, "%s binary string, it's len = %zu, bytes:", indent, data->len);
+                            OIC_LOG_BUFFER(level, PL_TAG, data->bytes, data->len);
+                        }
                             break;
                         case OCREP_PROP_OBJECT:
-                            OIC_LOG_V(level, PL_TAG, "\t\t%s(OCRep array):%zu x %zu x %zu",
-                                    val->name,
-                                    val->arr.dimensions[0], val->arr.dimensions[1],
-                                    val->arr.dimensions[2]);
+                            OCPayloadLogRep(level, val->arr.objArray[i]);
                             break;
+                        case OCREP_PROP_ARRAY: //Seems as nested arrays doesn't not supported in API
                         default:
-                            OIC_LOG_V(ERROR, PL_TAG, "\t\t%s <-- Unknown/unsupported array type!",
+                            OIC_LOG_V(ERROR, PL_TAG, "%s <-- Unknown/unsupported array type!",
                                     val->name);
                             break;
                     }
-                    break;
-                default:
-                    OIC_LOG_V(ERROR, PL_TAG, "\t\t%s <-- Unknown type!", val->name);
-                    break;
+                }
+                break;
             }
-            val = val -> next;
+            default:
+                OIC_LOG_V(ERROR, PL_TAG, "%s <-- Unknown type!", val->name);
+                break;
+        }
+        val = val -> next;
+    }
+}
+
+INLINE_API void OCPayloadLogRep(LogLevel level, OCRepPayload* payload)
+{
+    OCRepPayload* rep = payload;
+    int i = 1;
+    while(rep)
+    {
+        OCStringLL* strll =  rep->types;
+        while(strll)
+        {
+            strll = strll->next;
+        }
+        strll =  rep->interfaces;
+        while(strll)
+        {
+            strll = strll->next;
         }
 
+        // TODO Finish Logging: Values
+        OCRepPayloadValue* val = rep->values;
+
+        OCPayloadLogRepValues(level, val);
+
         ++i;
         rep = rep->next;
     }
-
 }
 
 INLINE_API void OCPayloadLogDiscovery(LogLevel level, OCDiscoveryPayload* payload)
@@ -401,7 +399,7 @@ INLINE_API void OCPayloadLogSecurity(LogLevel level, OCSecurityPayload* payload)
     {
         // Add a zero-character string terminator.
         char *securityData = (char *)OICMalloc(payloadSize + 1);
-        
+
         if (securityData)
         {
             memcpy(securityData, payload->securityData, payloadSize);
index bfa9bda..9b52f2d 100644 (file)
@@ -26,13 +26,20 @@ with_ra = samples_env.get ('WITH_RA')
 ######################################################################
 # Build flags
 ######################################################################
+with_upstream_libcoap = samples_env.get('WITH_UPSTREAM_LIBCOAP')
+if with_upstream_libcoap == '1':
+       # For bring up purposes only, we manually copy the forked version to where the unforked version is downloaded.
+       samples_env.AppendUnique(CPPPATH = ['#extlibs/libcoap/libcoap/include'])
+else:
+       # For bring up purposes only, the forked version will live here.
+       samples_env.AppendUnique(CPPPATH = ['../../../../../connectivity/lib/libcoap-4.1.1/include'])
+
 samples_env.PrependUnique(CPPPATH = [
                '../../../../logger/include',
                '../../../../stack/include',
                '../../../../../../extlibs/cjson',
                '../../../../../../extlibs/boost/boost',
                '../../../../../oc_logger/include',
-               '../../../../../connectivity/lib/libcoap-4.1.1'
                ])
 
 compiler = samples_env.get('CXX')
index fe7c8ae..f71ce90 100644 (file)
@@ -18,6 +18,7 @@
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
+#include "iotivity_config.h"
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
@@ -37,7 +38,6 @@
 #include "ocpayload.h"
 #include "payload_logging.h"
 #include "common.h"
-#include "platform_features.h"
 
 #ifdef ROUTING_GATEWAY
 /**
@@ -66,6 +66,10 @@ static OCDevAddr serverAddr;
 static char discoveryAddr[100];
 static std::string coapServerResource = "/a/light";
 
+// Following resource is used to verify coap-http proxy
+static std::string coapProxyResource = OC_RSRVD_PROXY_URI;
+static std::string httpResource;    // Will be taken as user input
+
 #ifdef WITH_PRESENCE
 // The handle for observe registration
 OCDoHandle gPresenceHandle;
@@ -105,7 +109,7 @@ OCPayload* putPayload()
 
 static void PrintUsage()
 {
-    OIC_LOG(INFO, TAG, "Usage : occlient -u <0|1> -t <1..17> -c <0|1>");
+    OIC_LOG(INFO, TAG, "Usage : occlient -u <0|1> -t <1..21> -c <0|1>");
     OIC_LOG(INFO, TAG, "-u <0|1> : Perform multicast/unicast discovery of resources");
     OIC_LOG(INFO, TAG, "-c 0 : Use Default connectivity(IP)");
     OIC_LOG(INFO, TAG, "-c 1 : IP Connectivity Type");
@@ -140,6 +144,7 @@ static void PrintUsage()
             "add  vendor specific header options");
     OIC_LOG(INFO, TAG, "-t 19 :  Discover Platform");
     OIC_LOG(INFO, TAG, "-t 20 :  Discover Devices");
+    OIC_LOG(INFO, TAG, "-t 21 -p \"http_uri\":  Discover Proxy and Initiate Nonconfirmable Get Request");
 }
 
 OCStackResult InvokeOCDoResource(std::ostringstream &query,
@@ -158,7 +163,8 @@ OCStackResult InvokeOCDoResource(std::ostringstream &query,
     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
     cbData.cd = NULL;
 
-    ret = OCDoResource(&handle, method, query.str().c_str(), remoteAddr,
+    const char *uri = query.str().length() ? query.str().c_str() : NULL;
+    ret = OCDoResource(&handle, method, uri, remoteAddr,
                        (method == OC_REST_PUT) ? putPayload() : NULL,
                        (ConnType), qos, &cbData, options, numOptions);
 
@@ -403,9 +409,12 @@ OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle /*handle*/,
 
         OCResourcePayload *resource = (OCResourcePayload*) payload->resources;
         int found = 0;
+
+        std::string resourceToFind = (TestCase == TEST_PROXY_GET_REQ_NON) ?
+                                            coapProxyResource : coapServerResource;
         while (resource)
         {
-            if(resource->uri && strcmp(resource->uri, coapServerResource.c_str()) == 0)
+            if(resource->uri && strcmp(resource->uri, resourceToFind.c_str()) == 0)
             {
                 found = 1;
                 break;
@@ -415,7 +424,7 @@ OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle /*handle*/,
 
         if(!found)
         {
-            OIC_LOG_V (INFO, TAG, "No /a/light in payload");
+            OIC_LOG_V (INFO, TAG, "No %s in payload", resourceToFind.c_str());
             return OC_STACK_KEEP_TRANSACTION;
         }
 
@@ -455,6 +464,9 @@ OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle /*handle*/,
             case TEST_OBS_REQ_CON:
                 InitObserveRequest(OC_HIGH_QOS);
                 break;
+            case TEST_PROXY_GET_REQ_NON:
+                InitProxyGetRequest(OC_LOW_QOS);
+                break;
 #ifdef WITH_PRESENCE
             case TEST_OBS_PRESENCE:
             case TEST_OBS_PRESENCE_WITH_FILTER:
@@ -561,10 +573,7 @@ int InitPresence()
     {
         if (result == OC_STACK_OK)
         {
-            std::ostringstream multicastPresenceQuery;
-            multicastPresenceQuery.str("");
-            multicastPresenceQuery << "coap://" << OC_MULTICAST_PREFIX << OC_RSRVD_PRESENCE_URI;
-            result = InvokeOCDoResource(multicastPresenceQuery, &serverAddr, OC_REST_PRESENCE, OC_LOW_QOS,
+            result = InvokeOCDoResource(query, NULL, OC_REST_PRESENCE, OC_LOW_QOS,
                     presenceCB, NULL, 0);
         }
     }
@@ -691,7 +700,27 @@ int InitDeleteRequest(OCQualityOfService qos)
     return result;
 }
 
-int InitGetRequest(OCQualityOfService qos, uint8_t withVendorSpecificHeaderOptions, bool getWithQuery)
+int InitProxyGetRequest(OCQualityOfService qos)
+{
+    OIC_LOG(INFO, TAG, "InitProxyGetRequest");
+    OCHeaderOption option;
+    memset(&option, 0, sizeof(option));
+
+    option.protocolID = OC_COAP_ID;
+    option.optionID = OC_RSRVD_PROXY_OPTION_ID;
+    memcpy(option.optionData, (uint8_t *)httpResource.c_str(), httpResource.length());
+    option.optionLength = httpResource.length();
+
+    std::ostringstream query;
+    // A request with proxy uri shall not have resource uri
+    // query << coapProxyResource;
+
+    return (InvokeOCDoResource(query, &serverAddr, OC_REST_GET,
+                (qos == OC_HIGH_QOS) ? OC_HIGH_QOS : OC_LOW_QOS, getReqCB, &option, 1));
+}
+
+int InitGetRequest(OCQualityOfService qos, uint8_t withVendorSpecificHeaderOptions,
+                   bool getWithQuery)
 {
 
     OCHeaderOption options[MAX_HEADER_OPTIONS];
@@ -809,7 +838,7 @@ int main(int argc, char* argv[])
 {
     int opt;
 
-    while ((opt = getopt(argc, argv, "u:t:c:")) != -1)
+    while ((opt = getopt(argc, argv, "u:t:c:p:")) != -1)
     {
         switch(opt)
         {
@@ -822,6 +851,12 @@ int main(int argc, char* argv[])
             case 'c':
                 Connectivity = atoi(optarg);
                 break;
+            case 'p':
+                if(optarg)
+                {
+                    httpResource = optarg;
+                }
+                break;
             default:
                 PrintUsage();
                 return -1;
@@ -830,7 +865,8 @@ int main(int argc, char* argv[])
 
     if ((UnicastDiscovery != 0 && UnicastDiscovery != 1) ||
             (TestCase < TEST_DISCOVER_REQ || TestCase >= MAX_TESTS) ||
-            (Connectivity < CT_ADAPTER_DEFAULT || Connectivity >= MAX_CT))
+            (Connectivity < CT_ADAPTER_DEFAULT || Connectivity >= MAX_CT) ||
+            (TestCase == TEST_PROXY_GET_REQ_NON && httpResource.length() == 0) )
     {
         PrintUsage();
         return -1;
index 2ed2e3d..caa0ec9 100644 (file)
@@ -63,6 +63,7 @@ typedef enum {
     TEST_GET_REQ_NON_WITH_VENDOR_HEADER_OPTIONS,
     TEST_DISCOVER_PLATFORM_REQ,
     TEST_DISCOVER_DEV_REQ,
+    TEST_PROXY_GET_REQ_NON,
     MAX_TESTS
 } CLIENT_TEST;
 
@@ -94,9 +95,6 @@ std::string getIPAddrTBServer(OCClientResponse * clientResponse);
 /* Get the port number the server is listening on */
 std::string getPortTBServer(OCClientResponse * clientResponse);
 
-/* Returns the query string for GET and PUT operations */
-std::string getQueryStrForGetPut(OCClientResponse * clientResponse);
-
 /* Following are initialization functions for GET, Observe, PUT
  * POST, Delete & Discovery operations
  */
@@ -110,11 +108,7 @@ int InitGetRequest(OCQualityOfService qos);
 int InitDeviceDiscovery(OCQualityOfService qos);
 int InitPlatformDiscovery(OCQualityOfService qos);
 int InitDiscovery(OCQualityOfService qos);
-
-/* Function to retrieve ip address, port no. of the server
- *  and query for the operations to be performed.
- */
-void parseClientResponse(OCClientResponse * clientResponse);
+int InitProxyGetRequest(OCQualityOfService qos);
 
 /* Call delete operation on already deleted resource */
 void* RequestDeleteDeathResourceTask(void* myqos);
index 988ce35..a37f64a 100644 (file)
@@ -17,6 +17,7 @@
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
+#include "iotivity_config.h"
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
index 375b169..5e576b4 100644 (file)
@@ -18,6 +18,7 @@
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
+#include "iotivity_config.h"
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
index d15fdd4..aa45b6c 100644 (file)
@@ -18,6 +18,7 @@
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
+#include "iotivity_config.h"
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
index 970565a..68c592f 100644 (file)
@@ -19,6 +19,7 @@
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
 
+#include "iotivity_config.h"
 #include <stdio.h>
 #include <string.h>
 #include <string>
@@ -41,7 +42,6 @@
 #include "ocpayload.h"
 #include "ocserver.h"
 #include "common.h"
-#include "platform_features.h"
 
 //string length of "/a/light/" + std::numeric_limits<int>::digits10 + '\0'"
 // 9 + 9 + 1 = 19
index 84d902c..e5726c4 100644 (file)
@@ -18,6 +18,7 @@
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
+#include "iotivity_config.h"
 #include <stdio.h>
 #include <string.h>
 #include <stdlib.h>
index b5408d0..ed18975 100644 (file)
@@ -19,6 +19,7 @@
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
 
+#include "iotivity_config.h"
 #include <stdio.h>
 #include <string.h>
 #include <string>
@@ -38,7 +39,6 @@
 #include <getopt.h>
 #include "ocpayload.h"
 #include "common.h"
-#include "platform_features.h"
 
 #define TAG PCF("ocservercontainer")
 
index 5f0ba4b..997b789 100644 (file)
@@ -18,6 +18,7 @@
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
+#include "iotivity_config.h"
 #include <stdio.h>
 #include <string.h>
 #include <stdlib.h>
index 4d0fdf0..e7262a8 100644 (file)
@@ -1,5 +1,5 @@
 
-
+#include "iotivity_config.h"
 #include <stdio.h>
 #include <string.h>
 #include <stdlib.h>
@@ -13,7 +13,6 @@
 #ifdef HAVE_PTHREAD_H
 #include <pthread.h>
 #endif
-#include "platform_features.h"
 #include "ocstack.h"
 #include "logger.h"
 #include "common.h"
index 714d075..5e8ca99 100644 (file)
@@ -18,6 +18,7 @@
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
+#include "iotivity_config.h"
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
@@ -35,7 +36,6 @@
 #include <iostream>
 #include <sstream>
 #include <getopt.h>
-#include "platform_features.h"
 #include "ocstack.h"
 #include "logger.h"
 #include "occlientbasicops.h"
index af344d3..5ae096b 100644 (file)
@@ -18,6 +18,7 @@
 //\r
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
 \r
+#include "iotivity_config.h"\r
 #include <stdio.h>\r
 #include <stdlib.h>\r
 #include <string.h>\r
@@ -37,7 +38,6 @@
 #undef ERROR\r
 #endif\r
 #endif // defined(HAVE_WINDOWS_H)\r
-#include "platform_features.h"\r
 #include "ocstack.h"\r
 #include "logger.h"\r
 #include "ocpayload.h"\r
index 9d83669..61db06a 100644 (file)
@@ -18,6 +18,7 @@
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
+#include "iotivity_config.h"
 #include <stdio.h>
 #include <string.h>
 #include <stdlib.h>
@@ -31,7 +32,6 @@
 #ifdef HAVE_PTHREAD_H
 #include <pthread.h>
 #endif
-#include "platform_features.h"
 #include "ocstack.h"
 #include "logger.h"
 #include "ocpayload.h"
index f48fcb0..532eb20 100644 (file)
@@ -56,6 +56,7 @@ help_vars.Add(ListVariable('TARGET_TRANSPORT', 'Target transport', 'ALL', ['ALL'
 help_vars.Add(EnumVariable('TARGET_ARCH', 'Target architecture', default_arch, os_arch_map[target_os]))
 help_vars.Add(EnumVariable('SECURED', 'Build with DTLS', '0', allowed_values=('0', '1')))
 help_vars.Add(EnumVariable('ROUTING', 'Enable routing', 'EP', allowed_values=('GW', 'EP')))
+help_vars.Add(BoolVariable('WITH_PROXY', 'CoAP-HTTP Proxy', False)) # set to 'no', 'false' or 0 for debug
 
 ######################################################################
 # Platform(build target) specific options: SDK/NDK & toolchain
@@ -177,6 +178,8 @@ if env.get('ROUTING') == 'GW':
 elif env.get('ROUTING') == 'EP':
        env.AppendUnique(CPPDEFINES = ['ROUTING_EP'])
 env.AppendUnique(CPPDEFINES = ['__TIZEN__'])
+if env.get('WITH_PROXY'):
+       env.AppendUnique(CPPDEFINES = ['WITH_CHPROXY'])
 
 Export('env')
 
index 9aabba5..832acf1 100644 (file)
@@ -3,7 +3,7 @@
 %{!?VERBOSE: %define VERBOSE 1}
 
 Name: com-oic-ri-sample
-Version:    1.1.1
+Version:    1.2.0
 Release:    0
 Summary: Tizen adapter interfacesample application
 URL: http://slp-source.sec.samsung.net
@@ -31,7 +31,7 @@ OIC RIsample application
 %build
 
 scons TARGET_OS=tizen -c
-scons VERBOSE=%{VERBOSE} TARGET_OS=tizen TARGET_TRANSPORT=%{TARGET_TRANSPORT} SECURED=%{SECURED} RELEASE=%{RELEASE} ROUTING=%{ROUTING}
+scons TARGET_OS=tizen TARGET_TRANSPORT=%{TARGET_TRANSPORT} SECURED=%{SECURED} RELEASE=%{RELEASE} ROUTING=%{ROUTING} WITH_TCP=%{WITH_TCP} WITH_PROXY=%{WITH_PROXY} 
 
 %install
 
index f4e7e59..9ec20c5 100644 (file)
@@ -37,6 +37,9 @@ if routing == 'GW':
 elif routing == 'EP':
        env.AppendUnique(CPPDEFINES = ['ROUTING_EP'])
 
+if env.get('WITH_PROXY'):
+       env.AppendUnique(CPPDEFINES = ['WITH_CHPROXY'])
+       
 env.Append(LIBS=[
   'm', 'pthread', 'rt', 'dl', 'stdc++', 'gobject-2.0', 'gio-2.0', 'glib-2.0', 'capi-network-wifi', 'dlog', 'capi-network-bluetooth', 'connectivity_abstraction', 'coap', 'octbstack', 'ocsrm', 'c_common'
 ])
@@ -68,6 +71,11 @@ else:
        else:
                env.AppendUnique(CPPDEFINES = ['NO_IP_ADAPTER'])
 
+       if env.get('WITH_TCP'):
+               env.AppendUnique(CPPDEFINES = ['TCP_ADAPTER', 'WITH_TCP'])
+       else:
+               env.AppendUnique(CPPDEFINES = ['NO_TCP_ADAPTER'])
+
 #ri_sample_src = [sample_dir + '/occlient.cpp']
 
 #print " ri sample src %s" % ri_sample_src
index 1e3722a..3f4efc8 100644 (file)
@@ -13,13 +13,22 @@ release_mode = env.get('RELEASE')
 secured = env.get('SECURED')
 logging = env.get('LOGGING')
 routing = env.get('ROUTING')
+with_proxy = env.get('WITH_PROXY')
+with_tcp = env.get('WITH_TCP')
+
+with_upstream_libcoap = env.get('WITH_UPSTREAM_LIBCOAP')
+if with_upstream_libcoap == '1':
+       # For bring up purposes only, we manually copy the forked version to where the unforked version is downloaded.
+       env.AppendUnique(CPPPATH = ['#extlibs/libcoap/libcoap/include'])
+else:
+       # For bring up purposes only, the forked version will live here.
+       env.AppendUnique(CPPPATH = ['../../../../connectivity/lib/libcoap-4.1.1'])
 
 env.PrependUnique(CPPPATH = [
                '../../../../logger/include',
                '../../../../stack/include',
                '../../../../../../extlibs/cjson',
-               '../../../../../oc_logger/include',
-               '../../../../../connectivity/lib/libcoap-4.1.1'
+               '../../../../../oc_logger/include'
                ])
 
 env.AppendUnique(CPPDEFINES = ['TB_LOG'])
@@ -29,11 +38,14 @@ elif routing == 'EP':
        env.AppendUnique(CPPDEFINES = ['ROUTING_EP'])
 env.AppendUnique(CPPDEFINES = ['__TIZEN__'])
 
+if env.get('WITH_PROXY'):
+       env.AppendUnique(CPPDEFINES = ['WITH_CHPROXY'])
+
 print "Given Transport is %s" % transport
 print "Given OS is %s" % target_os
 
 if target_os == 'tizen':
-       command = "sh resource/csdk/stack/samples/tizen/build/gbsbuild.sh %s %s %s %s %s %s" % (transport, secured, buildsample, release_mode, logging, routing)
+       command = "sh resource/csdk/stack/samples/tizen/build/gbsbuild.sh %s %s %s %s %s %s %s %s" % (transport, secured, buildsample, release_mode, logging, routing, with_tcp, with_proxy)
        print "Created Command is %s" % command
        gbs_script = env.Command('gbs_build', None, command)
        AlwaysBuild ('gbs_script')
\ No newline at end of file
index b4906c9..72aa019 100644 (file)
@@ -26,6 +26,12 @@ export LOGGING=$5
 echo $6
 export ROUTING=$6
 
+echo $7
+export WITH_TCP=$7
+
+echo $8
+export WITH_PROXY=$8
+
 echo $TARGET_TRANSPORT
 echo $BUILD_SAMPLE
 
@@ -42,10 +48,13 @@ mkdir ./tmp/extlibs/
 mkdir ./tmp/packaging
 cp -LR ./extlibs/tinycbor $sourcedir/tmp/extlibs
 rm -rf $sourcedir/tmp/extlibs/tinycbor/tinycbor/.git
+cp -Rf ./extlibs/mbedtls $sourcedir/tmp/extlibs
+rm -rf $sourcedir/tmp/extlibs/mbedtls/mbedtls/.git
 cp -R ./extlibs/cjson $sourcedir/tmp/extlibs
 cp -R ./extlibs/tinydtls $sourcedir/tmp/extlibs
 cp -R ./extlibs/timer $sourcedir/tmp/extlibs
 cp -R ./extlibs/rapidxml $sourcedir/tmp/extlibs
+cp -R ./extlibs/libcoap $sourcedir/tmp/extlibs
 cp -LR ./extlibs/sqlite3 $sourcedir/tmp/extlibs
 cp -R ./resource/csdk/stack/samples/tizen/build/packaging/*.spec $sourcedir/tmp/packaging
 cp -R ./resource $sourcedir/tmp/
@@ -89,7 +98,7 @@ if [ ! -d .git ]; then
 fi
 
 echo "Calling core gbs build command"
-gbscommand="gbs build -A armv7l -B ~/GBS-ROOT-RI-OIC --include-all --repository ./ --define 'TARGET_TRANSPORT $1' --define 'SECURED $2' --define 'RELEASE $4' --define 'LOGGING $5' --define 'ROUTING $6'"
+gbscommand="gbs build -A armv7l -B ~/GBS-ROOT-RI-OIC --include-all --repository ./ --define 'TARGET_TRANSPORT $1' --define 'SECURED $2' --define 'RELEASE $4' --define 'LOGGING $5' --define 'ROUTING $6' --define 'WITH_TCP $7' --define 'WITH_PROXY $8'"
 echo $gbscommand
 if eval $gbscommand; then
    echo "Core build is successful"
@@ -112,7 +121,7 @@ if echo $BUILD_SAMPLE|grep -qi '^ON$'; then
       git commit -m "Initial commit"
    fi
    echo "Calling sample gbs build command"
-   gbscommand="gbs build -A armv7l -B ~/GBS-ROOT-RI-OIC --include-all --repository ./ --define 'TARGET_TRANSPORT $1' --define 'SECURED $2' --define 'RELEASE $4' --define 'LOGGING $5' --define 'ROUTING $6'"
+   gbscommand="gbs build -A armv7l -B ~/GBS-ROOT-RI-OIC --include-all --repository ./ --define 'TARGET_TRANSPORT $1' --define 'SECURED $2' --define 'RELEASE $4' --define 'LOGGING $5' --define 'ROUTING $6' --define 'WITH_TCP $7' --define 'WITH_PROXY $8'"
    echo $gbscommand
    if eval $gbscommand; then
       echo "Sample build is successful"
index 4802499..0171d1a 100644 (file)
@@ -5,7 +5,7 @@
 %{!?VERBOSE: %define VERBOSE 1}
 
 Name: com-oic-ri
-Version:    1.1.1
+Version:    1.2.0
 Release:    0
 Summary: Tizen oicri application
 URL: http://slp-source.sec.samsung.net
@@ -37,7 +37,7 @@ SLP oicri application
 echo %{ROOTDIR}
 
 scons TARGET_OS=tizen -c
-scons VERBOSE=%{VERBOSE} TARGET_OS=tizen TARGET_TRANSPORT=%{TARGET_TRANSPORT} SECURED=%{SECURED} RELEASE=%{RELEASE} LOGGING=%{LOGGING} ROUTING=%{ROUTING}
+scons TARGET_OS=tizen TARGET_TRANSPORT=%{TARGET_TRANSPORT} SECURED=%{SECURED} RELEASE=%{RELEASE} LOGGING=%{LOGGING} ROUTING=%{ROUTING} WITH_TCP=%{WITH_TCP} WITH_PROXY=%{WITH_PROXY}
 
 %install
 mkdir -p %{DEST_INC_DIR}
@@ -47,7 +47,7 @@ cp -f %{ROOTDIR}/resource/csdk/liboctbstack.so %{buildroot}/%{_libdir}
 cp -f %{ROOTDIR}/resource/c_common/libc_common.a %{buildroot}/%{_libdir}
 cp -f %{ROOTDIR}/resource/csdk/security/libocsrm.a %{buildroot}/%{_libdir}
 cp -f %{ROOTDIR}/resource/csdk/connectivity/src/libconnectivity_abstraction.so %{buildroot}/%{_libdir}
-cp -f %{ROOTDIR}/resource/csdk/connectivity/lib/libcoap-4.1.1/libcoap.a %{buildroot}/%{_libdir}
+cp -f %{ROOTDIR}/extlibs/libcoap/libcoap.a %{buildroot}/%{_libdir}
 cp /usr/lib/libuuid.so.1 %{buildroot}%{_libdir}
 if echo %{SECURED}|grep -qi '1'; then
        cp -f %{ROOTDIR}/out/tizen/*/*/extlibs/tinydtls/libtinydtls.a %{buildroot}/%{_libdir}
@@ -67,6 +67,7 @@ cp resource/oc_logger/include/targets/oc_ostream_logger.h %{DEST_INC_DIR}
 cp resource/csdk/stack/include/ocpresence.h %{DEST_INC_DIR}
 cp resource/csdk/stack/include/ocpayload.h %{DEST_INC_DIR}
 cp resource/c_common/platform_features.h %{DEST_INC_DIR}
+cp resource/c_common/iotivity_config.h %{DEST_INC_DIR}
 cp resource/c_common/*/include/*.h %{DEST_INC_DIR}
 cp resource/csdk/stack/include/payload_logging.h %{DEST_INC_DIR}
 cp resource/csdk/stack/include/rdpayload.h %{DEST_INC_DIR}
index 914db6f..b9d0bd4 100644 (file)
@@ -42,4 +42,9 @@ else:
        else:
                env.AppendUnique(CPPDEFINES = ['NO_WIFI_ADAPTER'])
 
+       if env.get('WITH_TCP'):
+               env.AppendUnique(CPPDEFINES = ['TCP_ADAPTER', 'WITH_TCP'])
+       else:
+               env.AppendUnique(CPPDEFINES = ['NO_TCP_ADAPTER'])
+
 env.SConscript(['../resource/SConscript'])
index cc2bfb4..6f1a702 100644 (file)
@@ -18,9 +18,9 @@
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-
+#include "iotivity_config.h"
 #include "occlientcb.h"
-#include "utlist.h"
+#include <coap/coap.h>
 #include "logger.h"
 #include "oic_malloc.h"
 #include <string.h>
@@ -31,7 +31,6 @@
 #ifdef HAVE_ARDUINO_TIME_H
 #include "Time.h"
 #endif
-#include "coap_time.h"
 
 #include "cacommon.h"
 #include "cainterface.h"
@@ -49,7 +48,7 @@ AddClientCB (ClientCB** clientCB, OCCallbackData* cbData,
              OCDevAddr *devAddr, char * requestUri,
              char * resourceTypeName, uint32_t ttl)
 {
-    if (!clientCB || !cbData || !handle || !requestUri || tokenLength > CA_MAX_TOKEN_LEN)
+    if (!clientCB || !cbData || !handle || tokenLength > CA_MAX_TOKEN_LEN)
     {
         return OC_STACK_INVALID_PARAM;
     }
@@ -156,8 +155,11 @@ void DeleteClientCB(ClientCB * cbNode)
         CADestroyToken (cbNode->token);
         OICFree(cbNode->devAddr);
         OICFree(cbNode->handle);
-        OIC_LOG_V (INFO, TAG, "Deleting callback with uri %s", cbNode->requestUri);
-        OICFree(cbNode->requestUri);
+        if (cbNode->requestUri)
+        {
+            OIC_LOG_V (INFO, TAG, "Deleting callback with uri %s", cbNode->requestUri);
+            OICFree(cbNode->requestUri);
+        }
         if (cbNode->deleteCallback)
         {
             cbNode->deleteCallback(cbNode->context);
index 2051f73..3e0a9ba 100644 (file)
@@ -31,8 +31,8 @@
 #include "ocserverrequest.h"
 #include "logger.h"
 
-#include "utlist.h"
-#include "pdu.h"
+#include <coap/utlist.h>
+#include <coap/pdu.h>
 
 
 // Module Name
index 3af571e..2b17fdd 100644 (file)
@@ -21,6 +21,7 @@
 // Required for strok_r
 #define _POSIX_C_SOURCE 200112L
 
+#include "iotivity_config.h"
 #include <stdio.h>
 #include "ocpayload.h"
 #include "octypes.h"
@@ -174,6 +175,15 @@ static void OCCopyPropertyValueArray(OCRepPayloadValue* dest, OCRepPayloadValue*
                 dest->arr.objArray[i] = OCRepPayloadClone(source->arr.objArray[i]);
             }
             break;
+        case OCREP_PROP_BYTE_STRING:
+            dest->arr.ocByteStrArray = (OCByteString*)OICMalloc(dimTotal * sizeof(OCByteString));
+            VERIFY_PARAM_NON_NULL(TAG, dest->arr.ocByteStrArray, "Failed allocating memory");
+            for (size_t i = 0; i < dimTotal; ++i)
+            {
+                OCByteStringCopy(&dest->arr.ocByteStrArray[i], &source->arr.ocByteStrArray[i]);
+                VERIFY_PARAM_NON_NULL(TAG, dest->arr.ocByteStrArray[i].bytes, "Failed allocating memory");
+            }
+            break;
         default:
             OIC_LOG(ERROR, TAG, "CopyPropertyValueArray invalid type");
             break;
@@ -246,16 +256,19 @@ static void OCFreeRepPayloadValueContents(OCRepPayloadValue* val)
                 OICFree(val->arr.iArray);
                 break;
             case OCREP_PROP_STRING:
-                for(size_t i = 0; i< dimTotal; ++i)
+                for(size_t i = 0; i < dimTotal; ++i)
                 {
                     OICFree(val->arr.strArray[i]);
                 }
                 OICFree(val->arr.strArray);
                 break;
             case OCREP_PROP_BYTE_STRING:
-                for (size_t i = 0; i< dimTotal; ++i)
+                for (size_t i = 0; i < dimTotal; ++i)
                 {
-                    OICFree(val->arr.ocByteStrArray[i].bytes);
+                    if (val->arr.ocByteStrArray[i].bytes)
+                    {
+                        OICFree(val->arr.ocByteStrArray[i].bytes);
+                    }
                 }
                 OICFree(val->arr.ocByteStrArray);
                 break;
@@ -520,6 +533,7 @@ static bool OCRepPayloadSetProp(OCRepPayload* payload, const char* name,
                return val->str != NULL;
         case OCREP_PROP_BYTE_STRING:
                val->ocByteStr = *(OCByteString*)value;
+               return val->ocByteStr.bytes != NULL;
                break;
         case OCREP_PROP_NULL:
                return val != NULL;
@@ -619,18 +633,13 @@ bool OCRepPayloadSetPropByteString(OCRepPayload* payload, const char* name, OCBy
         return false;
     }
 
-    OCByteString ocByteStr = {
-                    .bytes = (uint8_t*)OICMalloc(value.len * sizeof(uint8_t)),
-                    .len = value.len };
+    OCByteString ocByteStr = {NULL, 0};
+    bool b = OCByteStringCopy(&ocByteStr, &value);
 
-    if (!ocByteStr.bytes)
+    if (b)
     {
-        return false;
+        b = OCRepPayloadSetPropByteStringAsOwner(payload, name, &ocByteStr);
     }
-    memcpy(ocByteStr.bytes, value.bytes, ocByteStr.len);
-
-    bool b = OCRepPayloadSetPropByteStringAsOwner(payload, name, &ocByteStr);
-
     if (!b)
     {
         OICFree(ocByteStr.bytes);
@@ -687,6 +696,153 @@ bool OCRepPayloadGetPropBool(const OCRepPayload* payload, const char* name, bool
     return true;
 }
 
+#ifdef __WITH_TLS__
+static char *getStringFromEncodingType(OicEncodingType_t type)
+{
+    char *str = NULL;
+    switch (type)
+    {
+        case OIC_ENCODING_BASE64: str = OC_RSRVD_BASE64; break;
+        case OIC_ENCODING_DER: str = OC_RSRVD_DER; break;
+        case OIC_ENCODING_PEM: str = OC_RSRVD_PEM; break;
+        case OIC_ENCODING_RAW: str = OC_RSRVD_RAW; break;
+        default: str = OC_RSRVD_UNKNOWN; break;
+    }
+    char encoding[32];
+    snprintf(encoding, sizeof(encoding), "%s.%s.%s", OC_OIC_SEC, OC_RSRVD_ENCODING, str);
+
+    return OICStrdup(encoding);
+}
+
+bool OCRepPayloadSetPropPubDataTypeAsOwner(OCRepPayload *payload, const char *name,
+                                           const OicSecKey_t *value)
+{
+    if (!payload || !name || !value)
+    {
+        return false;
+    }
+
+    bool binary_field = false;
+    if (OIC_ENCODING_RAW == value->encoding || OIC_ENCODING_DER == value->encoding)
+    {
+        binary_field = true;
+    }
+
+    OCRepPayload *heplerPayload = OCRepPayloadCreate();
+    if (!heplerPayload)
+    {
+        return false;
+    }
+
+    char *encoding = getStringFromEncodingType(value->encoding);
+    if (!OCRepPayloadSetPropString(heplerPayload, OC_RSRVD_ENCODING, encoding))
+    {
+        OIC_LOG_V(ERROR, TAG, "Can't set %s", OC_RSRVD_ENCODING);
+    }
+
+    OCByteString val = {.bytes = value->data, .len = value->len};
+    if (binary_field)
+    {
+        if (!OCRepPayloadSetPropByteString(heplerPayload, OC_RSRVD_DATA, val))
+        {
+            OIC_LOG_V(ERROR, TAG, "Can't set %s", OC_RSRVD_DATA);
+        }
+    }
+    else
+    {
+        if (!OCRepPayloadSetPropString(heplerPayload, OC_RSRVD_DATA, (char *)val.bytes))
+        {
+            OIC_LOG_V(ERROR, TAG, "Can't set %s", OC_RSRVD_DATA);
+        }
+    }
+
+    if (!OCRepPayloadSetPropObject(payload, name, (const OCRepPayload *)heplerPayload))
+    {
+        OIC_LOG_V(ERROR, TAG, "Can't set %s", name);
+    }
+
+    OCRepPayloadDestroy(heplerPayload);
+    OICFree(encoding);
+
+    return true;
+}
+
+bool OCRepPayloadSetPropPubDataType(OCRepPayload *payload, const char *name,
+                                    const OicSecKey_t *value)
+{
+    return OCRepPayloadSetPropPubDataTypeAsOwner(payload, name, value);
+}
+
+static OicEncodingType_t getEncodingTypeFromString(char *encoding)
+{
+    OicEncodingType_t type = OIC_ENCODING_UNKNOW;
+
+    char *str = strrchr(encoding, '.');
+    if (NULL == str)
+    {
+        OIC_LOG_V(ERROR, TAG, "Can't find . in %s", encoding);
+        return type;
+    }
+    str++; //go to encoding itself
+
+    if (0 == strcmp(str, OC_RSRVD_BASE64)) type = OIC_ENCODING_BASE64;
+    else if (0 == strcmp(str, OC_RSRVD_DER)) type = OIC_ENCODING_DER;
+    else if (0 == strcmp(str, OC_RSRVD_PEM)) type = OIC_ENCODING_PEM;
+    else if (0 == strcmp(str, OC_RSRVD_RAW)) type = OIC_ENCODING_RAW;
+
+    return type;
+}
+
+bool OCRepPayloadGetPropPubDataType(const OCRepPayload *payload, const char *name, OicSecKey_t *value)
+{
+    OCRepPayload *heplerPayload = NULL;
+    char *encoding = NULL;
+    OCByteString val;
+
+    if (!payload || !name || !value)
+    {
+        return false;
+    }
+
+    if (!OCRepPayloadGetPropObject(payload, name, &heplerPayload))
+    {
+        OIC_LOG_V(ERROR, TAG, "Can't get object with name %s", name);
+        return false;
+    }
+
+    if (!OCRepPayloadGetPropString(heplerPayload, OC_RSRVD_ENCODING, &encoding))
+    {
+        OIC_LOG_V(ERROR, TAG, "Can't get %s", OC_RSRVD_ENCODING);
+    }
+    else
+    {
+        value->encoding = getEncodingTypeFromString(encoding);
+        OICFree(encoding);
+    }
+
+    if (!OCRepPayloadGetPropByteString(heplerPayload, OC_RSRVD_DATA, &val))
+    {
+        if (!OCRepPayloadGetPropString(heplerPayload, OC_RSRVD_DATA, (char **)&val.bytes))
+        {
+            OIC_LOG_V(ERROR, TAG, "Can't get: %s", OC_RSRVD_DATA);
+        }
+        else
+        {
+            value->data = val.bytes;
+            value->len  = strlen(val.bytes);
+        }
+    }
+    else
+    {
+        value->data = val.bytes;
+        value->len  = val.len;
+    }
+
+    OCRepPayloadDestroy(heplerPayload);
+    return true;
+}
+#endif
+
 bool OCRepPayloadSetPropObject(OCRepPayload* payload, const char* name, const OCRepPayload* value)
 {
     OCRepPayload* temp = OCRepPayloadClone(value);
@@ -1305,16 +1461,19 @@ OCStringLL* OCCreateOCStringLL(const char* text)
     for (head = backup; ; head = NULL)
     {
         token = (char *) strtok_r(head, delim, &tail);
-        if (!token) break;
+        if (!token)
+        {
+            break;
+        }
         iter = (OCStringLL *)OICCalloc(1,sizeof(OCStringLL));
         VERIFY_PARAM_NON_NULL(TAG, iter, "Failed allocating memory");
         if (!result)
         {
-             result = iter;
+            result = iter;
         }
         else
         {
-             prev->next = iter;
+            prev->next = iter;
         }
         iter->value = OICStrdup(token);
         VERIFY_PARAM_NON_NULL(TAG, iter->value, "Failed allocating memory");
@@ -1347,7 +1506,7 @@ char* OCCreateString(const OCStringLL* ll)
     {
         len += strlen(it->value) + 1;
     }
-    len--; // renove trailing separator (just added above)
+    len--; // remove trailing separator (just added above)
     str = (char*) malloc(len + 1);
     if (!str)
     {
@@ -1380,6 +1539,36 @@ char* OCCreateString(const OCStringLL* ll)
     return str;
 }
 
+bool OCByteStringCopy(OCByteString* dest, const OCByteString* source)
+{
+    VERIFY_PARAM_NON_NULL(TAG, source, "Bad input");
+
+    if (!dest)
+    {
+        dest = (OCByteString *)OICMalloc(sizeof(OCByteString));
+        VERIFY_PARAM_NON_NULL(TAG, dest, "Failed allocating memory");
+    }
+    if (dest->bytes)
+    {
+        OICFree(dest->bytes);
+    }
+    dest->bytes = (uint8_t*)OICMalloc(source->len * sizeof(uint8_t));
+    VERIFY_PARAM_NON_NULL(TAG, dest->bytes, "Failed allocating memory");
+    memcpy(dest->bytes, source->bytes, source->len * sizeof(uint8_t));
+    dest->len = source->len;
+    return true;
+
+exit:
+    if (dest)
+    {
+        dest->len = 0;
+        OICFree(dest->bytes);
+        dest->bytes = NULL;
+    }
+
+    return false;
+}
+
 OCRepPayload* OCRepPayloadClone (const OCRepPayload* payload)
 {
     if (!payload)
index 2552873..cf5442f 100644 (file)
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
+#ifdef ARDUINO
+#define __STDC_LIMIT_MACROS
+#endif
+
 #include "ocpayloadcbor.h"
 #include "platform_features.h"
 #include <stdlib.h>
@@ -586,7 +590,7 @@ static int64_t OCConvertArrayItem(CborEncoder *array, const OCRepPayloadValueArr
             }
             break;
         case OCREP_PROP_BYTE_STRING:
-            if (!valArray->strArray[index])
+            if (!valArray->ocByteStrArray[index].len)
             {
                 err |= cbor_encode_null(array);
             }
index e5323e6..e2f572e 100755 (executable)
@@ -29,6 +29,7 @@
 #define _GNU_SOURCE
 #endif
 
+#include "iotivity_config.h"
 #ifdef HAVE_STRING_H
 #include <string.h>
 #endif
@@ -1008,6 +1009,12 @@ HandleResourceWithEntityHandler (OCServerRequest *request,
             request->observeResult = OC_STACK_OK;
             ehFlag = (OCEntityHandlerFlag)(OC_REQUEST_FLAG | OC_OBSERVE_FLAG);
         }
+        else if (result == OC_STACK_RESOURCE_ERROR)
+        {
+            OIC_LOG(INFO, TAG, "The Resource is not active, discoverable or observable");
+            request->observeResult = OC_STACK_ERROR;
+            ehFlag = OC_REQUEST_FLAG;
+        }
         else
         {
             // The error in observeResult for the request will be used when responding to this
index 8c825e4..041c75c 100644 (file)
@@ -36,8 +36,8 @@
 #include "cacommon.h"
 #include "cainterface.h"
 
-#include "utlist.h"
-#include "pdu.h"
+#include <coap/utlist.h>
+#include <coap/pdu.h>
 
 // Module Name
 #define VERIFY_NON_NULL(arg) { if (!arg) {OIC_LOG(FATAL, TAG, #arg " is NULL"); goto exit;} }
@@ -643,7 +643,7 @@ OCStackResult HandleSingleResponse(OCEntityHandlerResponse * ehResponse)
                     OICFree(responseInfo.info.options);
                     return result;
                 }
-                //Add CONTENT_FORMAT OPT if payload exist
+                // Add CONTENT_FORMAT OPT if payload exist
                 if (responseInfo.info.payloadSize > 0)
                 {
                     responseInfo.info.payloadFormat = CA_FORMAT_APPLICATION_CBOR;
index 13d595b..7042ad9 100644 (file)
@@ -36,6 +36,7 @@
 #ifndef __STDC_LIMIT_MACROS
 #define __STDC_LIMIT_MACROS
 #endif
+#include "iotivity_config.h"
 #include <inttypes.h>
 #include <string.h>
 #include <ctype.h>
@@ -57,7 +58,6 @@
 #include "cainterface.h"
 #include "ocpayload.h"
 #include "ocpayloadcbor.h"
-#include "platform_features.h"
 
 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
 #include "routingutility.h"
@@ -80,9 +80,7 @@
 #ifdef HAVE_SYS_TIME_H
 #include <sys/time.h>
 #endif
-#include "coap_time.h"
-#include "utlist.h"
-#include "pdu.h"
+#include <coap/coap.h>
 
 #ifdef HAVE_ARPA_INET_H
 #include <arpa/inet.h>
@@ -137,8 +135,8 @@ static bool gRASetInfo = false;
 #endif
 OCDeviceEntityHandler defaultDeviceHandler;
 void* defaultDeviceHandlerCallbackParameter = NULL;
-static const char COAP_TCP[] = "coap+tcp:";
-static const char COAPS_TCP[] = "coaps+tcp:";
+static const char COAP_TCP_SCHEME[] = "coap+tcp:";
+static const char COAPS_TCP_SCHEME[] = "coaps+tcp:";
 static const char CORESPEC[] = "core";
 
 //-----------------------------------------------------------------------------
@@ -419,6 +417,25 @@ static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *
 // Internal functions
 //-----------------------------------------------------------------------------
 
+bool checkProxyUri(OCHeaderOption *options, uint8_t numOptions)
+{
+    if (!options || 0 == numOptions)
+    {
+        OIC_LOG (INFO, TAG, "No options present");
+        return false;
+    }
+
+    for (uint8_t i = 0; i < numOptions; i++)
+    {
+        if (options[i].protocolID == OC_COAP_ID && options[i].optionID == OC_RSRVD_PROXY_OPTION_ID)
+        {
+            OIC_LOG(DEBUG, TAG, "Proxy URI is present");
+            return true;
+        }
+    }
+    return false;
+}
+
 uint32_t GetTicks(uint32_t afterMilliSeconds)
 {
     coap_tick_t now;
@@ -1341,25 +1358,33 @@ void OCHandleResponse(const CAEndpoint_t* endPoint, const CAResponseInfo_t* resp
                          cbNode->method == OC_REST_OBSERVE_ALL ||
                          cbNode->method == OC_REST_DELETE)
                 {
-                    char targetUri[MAX_URI_LENGTH];
-                    snprintf(targetUri, MAX_URI_LENGTH, "%s?rt=%s", OC_RSRVD_RD_URI,
-                            OC_RSRVD_RESOURCE_TYPE_RDPUBLISH);
-                    if (strcmp(targetUri, cbNode->requestUri) == 0)
-                    {
-                        type = PAYLOAD_TYPE_RD;
-                    }
-                    else if (strcmp(OC_RSRVD_PLATFORM_URI, cbNode->requestUri) == 0)
-                    {
-                        type = PAYLOAD_TYPE_PLATFORM;
-                    }
-                    else if (strcmp(OC_RSRVD_DEVICE_URI, cbNode->requestUri) == 0)
+                    if (cbNode->requestUri)
                     {
-                        type = PAYLOAD_TYPE_DEVICE;
+                        char targetUri[MAX_URI_LENGTH];
+                        snprintf(targetUri, MAX_URI_LENGTH, "%s?rt=%s", OC_RSRVD_RD_URI,
+                                OC_RSRVD_RESOURCE_TYPE_RDPUBLISH);
+                        if (strcmp(targetUri, cbNode->requestUri) == 0)
+                        {
+                            type = PAYLOAD_TYPE_RD;
+                        }
+                        else if (strcmp(OC_RSRVD_PLATFORM_URI, cbNode->requestUri) == 0)
+                        {
+                            type = PAYLOAD_TYPE_PLATFORM;
+                        }
+                        else if (strcmp(OC_RSRVD_DEVICE_URI, cbNode->requestUri) == 0)
+                        {
+                            type = PAYLOAD_TYPE_DEVICE;
+                        }
+                        if (type == PAYLOAD_TYPE_INVALID)
+                        {
+                            OIC_LOG_V(INFO, TAG, "Assuming PAYLOAD_TYPE_REPRESENTATION: %d %s",
+                                    cbNode->method, cbNode->requestUri);
+                            type = PAYLOAD_TYPE_REPRESENTATION;
+                        }
                     }
-                    if (type == PAYLOAD_TYPE_INVALID)
+                    else
                     {
-                        OIC_LOG_V(INFO, TAG, "Assuming PAYLOAD_TYPE_REPRESENTATION: %d %s",
-                                cbNode->method, cbNode->requestUri);
+                        OIC_LOG(INFO, TAG, "No Request URI, PROXY URI");
                         type = PAYLOAD_TYPE_REPRESENTATION;
                     }
                 }
@@ -1971,6 +1996,11 @@ void OCHandleRequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* reque
                                     CA_RESPONSE_DATA);
         }
     }
+    if (requestResult == OC_STACK_RESOURCE_ERROR
+            && serverRequest.observationOption == OC_OBSERVE_REGISTER)
+    {
+        OIC_LOG_V(ERROR, TAG, "Observe Registration failed due to resource error");
+    }
     else if(!OCResultToSuccess(requestResult))
     {
         OIC_LOG_V(ERROR, TAG, "HandleStackRequests failed. error: %d", requestResult);
@@ -2421,8 +2451,8 @@ static OCStackResult ParseRequestUri(const char *fullUri,
     bool istcp = false;
     if (prefixLen)
     {
-        if (((prefixLen == sizeof(COAP_TCP) - 1) && (!strncmp(fullUri, COAP_TCP, prefixLen)))
-        || ((prefixLen == sizeof(COAPS_TCP) - 1) && (!strncmp(fullUri, COAPS_TCP, prefixLen))))
+        if (((prefixLen == sizeof(COAP_TCP_SCHEME) - 1) && (!strncmp(fullUri, COAP_TCP_SCHEME, prefixLen)))
+        || ((prefixLen == sizeof(COAPS_TCP_SCHEME) - 1) && (!strncmp(fullUri, COAPS_TCP_SCHEME, prefixLen))))
         {
             istcp = true;
         }
@@ -2619,7 +2649,6 @@ OCStackResult OCDoResource(OCDoHandle *handle,
     // Validate input parameters
     VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK);
     VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK);
-    VERIFY_NON_NULL(requestUri , FATAL, OC_STACK_INVALID_URI);
 
     OCStackResult result = OC_STACK_ERROR;
     CAResult_t caResult;
@@ -2645,10 +2674,18 @@ OCStackResult OCDoResource(OCDoHandle *handle,
     adapter = (OCTransportAdapter)(connectivityType >> CT_ADAPTER_SHIFT);
     flags = (OCTransportFlags)(connectivityType & CT_MASK_FLAGS);
 
-    result = ParseRequestUri(requestUri, adapter, flags, &devAddr, &resourceUri, &resourceType);
-    if (result != OC_STACK_OK)
+    if (requestUri)
     {
-        OIC_LOG_V(DEBUG, TAG, "Unable to parse uri: %s", requestUri);
+        result = ParseRequestUri(requestUri, adapter, flags, &devAddr, &resourceUri, &resourceType);
+        if (result != OC_STACK_OK)
+        {
+            OIC_LOG_V(DEBUG, TAG, "Unable to parse uri: %s", requestUri);
+            goto exit;
+        }
+    }
+    else if (!checkProxyUri(options, numOptions))
+    {
+        OIC_LOG(ERROR, TAG, "Request doesn't contain RequestURI/Proxy URI");
         goto exit;
     }
 
@@ -4782,6 +4819,13 @@ bool OCResultToSuccess(OCStackResult ocResult)
     }
 }
 
+#ifdef WITH_CHPROXY
+OCStackResult OCSetProxyURI(const char *uri)
+{
+    return CAResultToOCResult(CASetProxyUri(uri));
+}
+#endif
+
 #if defined(RD_CLIENT) || defined(RD_SERVER)
 OCStackResult OCBindResourceInsToResource(OCResourceHandle handle, uint8_t ins)
 {
index 558f683..8a9e443 100755 (executable)
@@ -20,6 +20,8 @@
 
 #define _POSIX_C_SOURCE 200112L
 
+#include "iotivity_config.h"
+
 #include <string.h>
 
 #include "oicgroup.h"
@@ -32,8 +34,6 @@
 #include "logger.h"
 #include "timer.h"
 
-#include "platform_features.h"
-
 #define TAG "OIC_RI_GROUP"
 
 #define DESC_DELIMITER          "\""
@@ -436,11 +436,13 @@ void DeleteAction(OCAction** action)
 
 void DeleteActionSet(OCActionSet** actionset)
 {
+    OCAction* pointer = NULL;
+    OCAction* pDel = NULL;
+
     if(*actionset == NULL)
         return;
 
-    OCAction* pointer = (*actionset)->head;
-    OCAction* pDel = NULL;
+    pointer = (*actionset)->head;
 
     while (pointer)
     {
index 8acd7d0..aabb391 100644 (file)
@@ -579,8 +579,14 @@ OCStackResult SendPingMessage(KeepAliveEntry_t *entry)
     payload->base.type = PAYLOAD_TYPE_REPRESENTATION;
     OCRepPayloadSetPropInt(payload, INTERVAL, entry->interval);
 
-    OCDoResource(NULL, OC_REST_PUT, KEEPALIVE_RESOURCE_URI, &devAddr,
-                 (OCPayload *) payload, CT_ADAPTER_TCP, OC_LOW_QOS, &pingData, NULL, 0);
+    OCStackResult result = OCDoResource(NULL, OC_REST_PUT, KEEPALIVE_RESOURCE_URI, &devAddr,
+                                        (OCPayload *) payload, CT_ADAPTER_TCP, OC_LOW_QOS,
+                                        &pingData, NULL, 0);
+    if (OC_STACK_OK != result)
+    {
+        OIC_LOG(ERROR, TAG, "OCDoResource has failed");
+        return result;
+    }
 
     // Update timeStamp with time sent ping message for next ping message.
     entry->timeStamp = OICGetCurrentTime(TIME_IN_US);
@@ -741,8 +747,14 @@ void HandleKeepAliveConnCB(const CAEndpoint_t *endpoint, bool isConnected)
         OCDevAddr devAddr = { .adapter = OC_ADAPTER_TCP };
         CopyEndpointToDevAddr(endpoint, &devAddr);
 
-        OCDoResource(NULL, OC_REST_DISCOVER, KEEPALIVE_RESOURCE_URI, &devAddr, NULL,
-                     CT_ADAPTER_TCP, OC_HIGH_QOS, &pingData, NULL, 0);
+        OCStackResult result = OCDoResource(NULL, OC_REST_DISCOVER, KEEPALIVE_RESOURCE_URI,
+                                            &devAddr, NULL, CT_ADAPTER_TCP, OC_HIGH_QOS,
+                                            &pingData, NULL, 0);
+        if (OC_STACK_OK != result)
+        {
+            OIC_LOG(ERROR, TAG, "OCDoResource has failed");
+            return;
+        }
     }
     else
     {
index 4a60a77..8920bde 100644 (file)
@@ -17,6 +17,7 @@
 // limitations under the License.
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#include "iotivity_config.h"
 #include "oicresourcedirectory.h"
 
 #include "rdpayload.h"
index 0f82960..f265df2 100644 (file)
 // limitations under the License.
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#ifdef ARDUINO
+#define __STDC_LIMIT_MACROS
+#endif
+
 #include "rdpayload.h"
 
 #include "oic_malloc.h"
index 82e6ab3..46cc864 100644 (file)
@@ -60,7 +60,6 @@ if stacktest_env.get('LOGGING'):
        stacktest_env.AppendUnique(CPPDEFINES = ['TB_LOG'])
 
 if target_os in ['msys_nt', 'windows']:
-       stacktest_env.AppendUnique(LINKFLAGS = ['/subsystem:CONSOLE'])
        stacktest_env.AppendUnique(LIBS = ['ws2_32', 'iphlpapi', 'kernel32'])
 else:
        stacktest_env.PrependUnique(LIBS = ['m'])
index dcd6bd7..c8cc507 100644 (file)
@@ -681,6 +681,14 @@ INPUT                  = . \
                          ../../csdk/stack/include/internal/oicgroup.h \
                          ../../csdk/stack/include/internal/oickeepalive.h \
                          guides \
+                         ../../csdk/security/include \
+                         ../../csdk/security/include\internal \
+                         ../../csdk/security/provisioning/include \
+                         ../../csdk/security/provisioning/include/internal \
+                         ../../csdk/security/provisioning/include/oxm \
+                         ../../csdk/security/provisioning/include/cloud \
+                         ../../csdk/security/provisioning/sample/cloudAuth.h \
+                         ../../csdk/security/provisioning/sample/cloudWrapper.h \
                          ../../../service/easy-setup/inc \
                          ../../../service/easy-setup/enrollee/inc \
                          ../../../service/resource-directory/include \
index 6368e93..1ce1e6b 100644 (file)
@@ -23,6 +23,7 @@
 /// This sample provides steps to define an interface for a resource
 /// (properties and methods) and host this resource on the server.
 ///
+#include "iotivity_config.h"
 
 #ifdef HAVE_UNISTD_H
 #include <unistd.h>
index 5bb8b06..228e6af 100644 (file)
 /// (properties and methods) and host this resource on the server.
 ///
 
+#include "iotivity_config.h"
 #include <functional>
 
+#ifdef HAVE_PTHREAD_H
 #include <pthread.h>
+#endif
 #include <array>
 #include <mutex>
 #include <condition_variable>
@@ -36,7 +39,6 @@
 #ifdef HAVE_WINDOWS_H
 #include <windows.h>
 #endif
-#include "platform_features.h"
 
 using namespace OC;
 using namespace std;
index f9452af..a2997bc 100644 (file)
@@ -20,6 +20,7 @@
 
 // OCClient.cpp : Defines the entry point for the console application.
 //
+#include "iotivity_config.h"
 #ifdef HAVE_UNISTD_H
 #include <unistd.h>
 #endif
index be585fc..6d631d3 100644 (file)
 
 // OCClient.cpp : Defines the entry point for the console application.
 //
+#include "iotivity_config.h"
+
 #include <set>
 #include <string>
 #include <cstdlib>
-#ifdef HAVE_PTHREAD_H
-#include <pthread.h>
-#endif
 #include <mutex>
 #include <condition_variable>
 #include "OCPlatform.h"
 #include "OCApi.h"
 
+#if defined(HAVE_PTHREAD_H)
+#include <pthread.h>
+#endif
 #if defined(HAVE_WINDOWS_H)
 #include <windows.h>
 #endif
-#include "platform_features.h"
 
 using namespace OC;
 
index 13981cb..b005900 100644 (file)
@@ -22,8 +22,9 @@
 /// This sample provides steps to define an interface for a resource
 /// (properties and methods) and host this resource on the server.
 ///
-#include <functional>
+#include "iotivity_config.h"
 
+#include <functional>
 #ifdef HAVE_UNISTD_H
 #include <unistd.h>
 #endif
@@ -38,7 +39,6 @@
 #ifdef HAVE_WINDOWS_H
 #include <windows.h>
 #endif
-#include "platform_features.h"
 
 using namespace OC;
 using namespace std;
index 3adef4e..6d641e7 100644 (file)
@@ -23,6 +23,7 @@
 /// (properties and methods) and host this resource on the server.
 ///
 
+#include "iotivity_config.h"
 #include <functional>
 
 #ifdef HAVE_PTHREAD_H
@@ -37,7 +38,6 @@
 #ifdef HAVE_WINDOWS_H
 #include <windows.h>
 #endif
-#include "platform_features.h"
 
 using namespace OC;
 using namespace std;
index 1eaaeba..46cfbec 100644 (file)
@@ -23,6 +23,7 @@
 /// server in a separate thread, and running 2 clients in each thread.
 ///
 
+#include "iotivity_config.h"
 
 #include <memory>
 #include <iostream>
@@ -37,7 +38,6 @@
 #ifdef HAVE_WINDOWS_H
 #include <windows.h>
 #endif
-#include "platform_features.h"
 
 using namespace OC;
 
index 5b9ca83..3315356 100644 (file)
@@ -54,6 +54,7 @@ namespace OC
         bool,
         std::string,
         OC::OCRepresentation,
+        OCByteString,
 
         // Sequences:
         std::vector<int>,
@@ -61,6 +62,7 @@ namespace OC
         std::vector<bool>,
         std::vector<std::string>,
         std::vector<OC::OCRepresentation>,
+        std::vector<OCByteString>,
 
         // Nested sequences:
         std::vector<std::vector<int>>,
@@ -78,6 +80,9 @@ namespace OC
         std::vector<std::vector<OC::OCRepresentation>>,
         std::vector<std::vector<std::vector<OC::OCRepresentation>>>,
 
+        std::vector<std::vector<OCByteString>>,
+        std::vector<std::vector<std::vector<OCByteString>>>,
+
         // used for binary data type
         std::vector<uint8_t>
     > AttributeValue;
@@ -91,7 +96,8 @@ namespace OC
         String,
         OCRepresentation,
         Vector,
-        Binary
+        Binary,
+        OCByteString
     };
 
     template<typename T>
@@ -134,6 +140,12 @@ namespace OC
     };
 
     template<>
+    struct AttributeTypeConvert<OCByteString>
+    {
+       BOOST_STATIC_CONSTEXPR AttributeType type = AttributeType::OCByteString;
+    };
+
+    template<>
     struct AttributeTypeConvert<std::vector<uint8_t>>
     {
         BOOST_STATIC_CONSTEXPR AttributeType type = AttributeType::Binary;
index c07974a..1e025eb 100644 (file)
@@ -333,6 +333,7 @@ namespace OC
                      std::is_same<T, bool>::value ||
                      std::is_same<T, std::string>::value ||
                      std::is_same<T, OCRepresentation>::value ||
+                     std::is_same<T, OCByteString>::value ||
                      std::is_same<T, std::vector<int>>::value ||
                      std::is_same<T, std::vector<std::vector<int>>>::value ||
                      std::is_same<T, std::vector<std::vector<std::vector<int>>>>::value ||
@@ -347,7 +348,10 @@ namespace OC
                      std::is_same<T, std::vector<std::vector<std::vector<std::string>>>>::value ||
                      std::is_same<T, std::vector<OCRepresentation>>::value ||
                      std::is_same<T, std::vector<std::vector<OCRepresentation>>>::value ||
-                     std::is_same<T, std::vector<std::vector<std::vector<OCRepresentation>>>>::value
+                     std::is_same<T, std::vector<std::vector<std::vector<OCRepresentation>>>>::value ||
+                     std::is_same<T, std::vector<OCByteString>>::value ||
+                     std::is_same<T, std::vector<std::vector<OCByteString>>>::value ||
+                     std::is_same<T, std::vector<std::vector<std::vector<OCByteString>>>>::value
                      , int>::type = 0// enable_if
                     >
 #else
index d8cf349..9b2d7a3 100644 (file)
@@ -25,6 +25,14 @@ ocprovision_env = env.Clone()
 ######################################################################
 # Build flags
 ######################################################################
+with_upstream_libcoap = ocprovision_env.get('WITH_UPSTREAM_LIBCOAP')
+if with_upstream_libcoap == '1':
+       # For bring up purposes only, we manually copy the forked version to where the unforked version is downloaded.
+       ocprovision_env.AppendUnique(CPPPATH = ['#extlibs/libcoap/libcoap/include'])
+else:
+       # For bring up purposes only, the forked version will live here.
+       ocprovision_env.AppendUnique(CPPPATH = ['../csdk/connectivity/lib/libcoap-4.1.1/include'])
+
 ocprovision_env.AppendUnique(CPPPATH = [
                '../include/',
                '../csdk/stack/include',
@@ -36,25 +44,24 @@ ocprovision_env.AppendUnique(CPPPATH = [
                '../csdk/security/provisioning/include',
                '../csdk/security/provisioning/include/oxm',
                '../csdk/security/provisioning/include/internal',
-        '../csdk/connectivity/lib/libcoap-4.1.1/',
-        '../../extlibs/cjson/'
+               '../../extlibs/cjson/'
                ])
 
-target_os = env.get('TARGET_OS')
+target_os = ocprovision_env.get('TARGET_OS')
 if target_os not in ['windows']:
        ocprovision_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-fPIC'])
 
 if target_os == 'android':
        ocprovision_env.AppendUnique(CXXFLAGS = ['-frtti', '-fexceptions'])
-       ocprovision_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
+       ocprovision_env.AppendUnique(LIBPATH = [ocprovision_env.get('BUILD_DIR')])
        ocprovision_env.AppendUnique(LIBS = ['oc', 'octbstack', 'ocpmapi', 'oc_logger', 'boost_thread', 'gnustl_shared', 'log'])
 
 if target_os in ['linux', 'tizen']:
-       ocprovision_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
+       ocprovision_env.AppendUnique(LIBPATH = [ocprovision_env.get('BUILD_DIR')])
         ocprovision_env.AppendUnique(LIBS = ['oc', 'octbstack', 'ocpmapi', 'oc_logger', 'boost_thread'])
 
 if target_os in ['darwin', 'ios']:
-       ocprovision_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
+       ocprovision_env.AppendUnique(LIBPATH = [ocprovision_env.get('BUILD_DIR')])
        ocprovision_env.AppendUnique(LIBS = ['octbstack', 'oc_logger'])
 
 ######################################################################
index 09f2057..f873a93 100644 (file)
@@ -84,6 +84,9 @@ if target_os in ['android']:
 if target_os in ['darwin', 'ios']:
        examples_env.AppendUnique(CPPDEFINES = ['_DARWIN_C_SOURCE'])
 
+if target_os == 'tizen':
+    examples_env.AppendUnique(CPPDEFINES = ['__TIZEN__'])
+
 
 ######################################################################
 # Source files and Targets
index e077f01..b5b2b37 100644 (file)
@@ -339,6 +339,7 @@ namespace OC
             return OC_STACK_DELETE_TRANSACTION;
         }
 
+        std::string resourceURI = clientResponse->resourceUri;
         if (clientResponse->result != OC_STACK_OK)
         {
             oclog() << "listenMQCallback(): failed to create resource. clientResponse: "
@@ -346,7 +347,7 @@ namespace OC
                     << std::flush;
 
             std::thread exec(context->callback, clientResponse->result,
-                             std::string(clientResponse->resourceUri), nullptr);
+                             resourceURI, nullptr);
             exec.detach();
 
             return OC_STACK_DELETE_TRANSACTION;
@@ -369,7 +370,7 @@ namespace OC
             for (auto resource : container.Resources())
             {
                 std::thread exec(context->callback, clientResponse->result,
-                                 std::string(clientResponse->resourceUri), resource);
+                                 resourceURI, resource);
                 exec.detach();
             }
         }
index 5da112a..669917f 100644 (file)
@@ -77,6 +77,11 @@ OCStackResult OCAccountManager::signUp(const std::string& authProvider,
                                        const QueryParamsMap& options,
                                        PostCallback cloudConnectHandler)
 {
+    if (authProvider.empty() || authCode.empty())
+    {
+        return result_guard(OC_STACK_INVALID_PARAM);
+    }
+
     std::string uri = m_host + OC_RSRVD_ACCOUNT_URI;
 
     OCRepresentation rep;
@@ -86,12 +91,10 @@ OCStackResult OCAccountManager::signUp(const std::string& authProvider,
 
     if (!options.empty())
     {
-        OCRepresentation optionsRep;
         for (auto iter : options)
         {
-            optionsRep[iter.first] = iter.second;
+            rep.setValue(iter.first, iter.second);
         }
-        rep.setValue(OC_RSRVD_OPTIONS, optionsRep);
     }
 
     return checked_guard(m_clientWrapper.lock(), &IClientWrapper::PostResourceRepresentation,
@@ -103,6 +106,11 @@ OCStackResult OCAccountManager::signIn(const std::string& userUuid,
                                        const std::string& accessToken,
                                        PostCallback cloudConnectHandler)
 {
+    if (userUuid.empty() || accessToken.empty())
+    {
+        return result_guard(OC_STACK_INVALID_PARAM);
+    }
+
     return result_guard(signInOut(userUuid, accessToken, true, cloudConnectHandler));
 }
 
@@ -136,6 +144,11 @@ OCStackResult OCAccountManager::refreshAccessToken(const std::string& userUuid,
                                                    const std::string& refreshToken,
                                                    PostCallback cloudConnectHandler)
 {
+    if (userUuid.empty() || refreshToken.empty())
+    {
+        return result_guard(OC_STACK_INVALID_PARAM);
+    }
+
     std::string uri = m_host + OC_RSRVD_ACCOUNT_TOKEN_REFRESH_URI;
 
     OCRepresentation rep;
@@ -152,12 +165,22 @@ OCStackResult OCAccountManager::refreshAccessToken(const std::string& userUuid,
 OCStackResult OCAccountManager::searchUser(const std::string& userUuid,
                                            GetCallback cloudConnectHandler)
 {
+    if (userUuid.empty())
+    {
+        return result_guard(OC_STACK_INVALID_PARAM);
+    }
+
     return result_guard(searchUser(userUuid, QueryParamsMap(), cloudConnectHandler));
 }
 
 OCStackResult OCAccountManager::searchUser(const QueryParamsMap& queryParams,
                                            GetCallback cloudConnectHandler)
 {
+    if (queryParams.empty())
+    {
+        return result_guard(OC_STACK_INVALID_PARAM);
+    }
+
     return result_guard(searchUser("", queryParams, cloudConnectHandler));
 }
 
@@ -193,6 +216,11 @@ OCStackResult OCAccountManager::searchUser(const std::string& userUuid,
 OCStackResult OCAccountManager::deleteDevice(const std::string& deviceId,
                                              DeleteCallback cloudConnectHandler)
 {
+    if (deviceId.empty())
+    {
+        return result_guard(OC_STACK_INVALID_PARAM);
+    }
+
     std::string uri = m_host + OC_RSRVD_ACCOUNT_URI
                       + "?" + OC_RSRVD_DEVICE_ID + "=" + deviceId;
 
@@ -238,6 +266,11 @@ OCStackResult OCAccountManager::getGroupList(GetCallback cloudConnectHandler)
 OCStackResult OCAccountManager::deleteGroup(const std::string& groupId,
                                             DeleteCallback cloudConnectHandler)
 {
+    if (groupId.empty())
+    {
+        return result_guard(OC_STACK_INVALID_PARAM);
+    }
+
     std::string uri = m_host + OC_RSRVD_ACL_GROUP_URI
                       + "?" + OC_RSRVD_GROUP_ID + "=" + groupId;
 
@@ -249,6 +282,11 @@ OCStackResult OCAccountManager::deleteGroup(const std::string& groupId,
 OCStackResult OCAccountManager::joinGroup(const std::string& groupId,
                                           PostCallback cloudConnectHandler)
 {
+    if (groupId.empty())
+    {
+        return result_guard(OC_STACK_INVALID_PARAM);
+    }
+
     std::string uri = m_host + OC_RSRVD_ACL_GROUP_URI + "/" + groupId;
 
     return checked_guard(m_clientWrapper.lock(), &IClientWrapper::PostResourceRepresentation,
@@ -260,7 +298,7 @@ OCStackResult OCAccountManager::addDeviceToGroup(const std::string& groupId,
                                                  const std::vector<std::string>& deviceId,
                                                  PostCallback cloudConnectHandler)
 {
-    if (deviceId.empty())
+    if (groupId.empty() || deviceId.empty())
     {
         return result_guard(OC_STACK_INVALID_PARAM);
     }
@@ -278,6 +316,11 @@ OCStackResult OCAccountManager::addDeviceToGroup(const std::string& groupId,
 OCStackResult OCAccountManager::getGroupInfo(const std::string& groupId,
                                              GetCallback cloudConnectHandler)
 {
+    if (groupId.empty())
+    {
+        return result_guard(OC_STACK_INVALID_PARAM);
+    }
+
     std::string uri = m_host + OC_RSRVD_ACL_GROUP_URI + "/" + groupId;
 
     return checked_guard(m_clientWrapper.lock(), &IClientWrapper::GetResourceRepresentation,
@@ -288,6 +331,11 @@ OCStackResult OCAccountManager::getGroupInfo(const std::string& groupId,
 OCStackResult OCAccountManager::leaveGroup(const std::string& groupId,
                                            DeleteCallback cloudConnectHandler)
 {
+    if (groupId.empty())
+    {
+        return result_guard(OC_STACK_INVALID_PARAM);
+    }
+
     std::string uri = m_host + OC_RSRVD_ACL_GROUP_URI + "/" + groupId;
 
     return checked_guard(m_clientWrapper.lock(), &IClientWrapper::DeleteResource,
@@ -299,7 +347,7 @@ OCStackResult OCAccountManager::deleteDeviceFromGroup(const std::string& groupId
                                                       const std::vector<std::string>& deviceId,
                                                       DeleteCallback cloudConnectHandler)
 {
-    if (deviceId.empty())
+    if (groupId.empty() || deviceId.empty())
     {
         return result_guard(OC_STACK_INVALID_PARAM);
     }
@@ -322,6 +370,11 @@ OCStackResult OCAccountManager::deleteDeviceFromGroup(const std::string& groupId
 OCStackResult OCAccountManager::observeGroup(const std::string& groupId,
                                              ObserveCallback cloudConnectHandler)
 {
+    if (groupId.empty())
+    {
+        return result_guard(OC_STACK_INVALID_PARAM);
+    }
+
     std::string uri = m_host + OC_RSRVD_ACL_GROUP_URI + "/" + groupId;
 
     OCDoHandle handle = nullptr;
@@ -342,6 +395,11 @@ OCStackResult OCAccountManager::observeGroup(const std::string& groupId,
 
 OCStackResult OCAccountManager::cancelObserveGroup(const std::string& groupId)
 {
+    if (groupId.empty())
+    {
+        return result_guard(OC_STACK_INVALID_PARAM);
+    }
+
     auto found = m_groupObserveHandles.find(groupId);
     if (m_groupObserveHandles.end() == found)
     {
@@ -400,6 +458,11 @@ OCStackResult OCAccountManager::sendInvitation(const std::string& groupId,
                                                const std::string& userUuid,
                                                PostCallback cloudConnectHandler)
 {
+    if (groupId.empty() || userUuid.empty())
+    {
+        return result_guard(OC_STACK_INVALID_PARAM);
+    }
+
     std::string uri = m_host + OC_RSRVD_ACL_INVITE_URI;
 
     OCRepresentation invitation;
@@ -420,6 +483,11 @@ OCStackResult OCAccountManager::cancelInvitation(const std::string& groupId,
                                                  const std::string& userUuid,
                                                  DeleteCallback cloudConnectHandler)
 {
+    if (groupId.empty() || userUuid.empty())
+    {
+        return result_guard(OC_STACK_INVALID_PARAM);
+    }
+
     std::string uri = m_host + OC_RSRVD_ACL_INVITE_URI + "?" + OC_RSRVD_GROUP_ID + "=" + groupId
                       + ";" + OC_RSRVD_MEMBER_ID + "=" + userUuid;
 
@@ -431,6 +499,11 @@ OCStackResult OCAccountManager::cancelInvitation(const std::string& groupId,
 OCStackResult OCAccountManager::deleteInvitation(const std::string& groupId,
                                                  DeleteCallback cloudConnectHandler)
 {
+    if (groupId.empty())
+    {
+        return result_guard(OC_STACK_INVALID_PARAM);
+    }
+
     std::string uri = m_host + OC_RSRVD_ACL_INVITE_URI + "?" + OC_RSRVD_GROUP_ID + "=" + groupId;
 
     return checked_guard(m_clientWrapper.lock(), &IClientWrapper::DeleteResource,
index 7fdc9f5..529573f 100644 (file)
@@ -21,6 +21,9 @@
 #include "OCApi.h"
 
 #if defined(_MSC_VER)
+
+#include <iostream>
+
 namespace OC
 {
     std::ostream& oclog()
index 476d72b..8fe41d5 100644 (file)
@@ -30,6 +30,7 @@
 
 #include <boost/lexical_cast.hpp>
 #include <algorithm>
+#include <iomanip>
 #include "ocpayload.h"
 #include "ocrandom.h"
 #include "oic_malloc.h"
@@ -369,6 +370,24 @@ namespace OC
     }
 
     template<>
+    void get_payload_array::copy_to_array(OCByteString item, void *array, size_t pos)
+    {
+        ((OCByteString *)array)[pos] = item;
+    }
+
+    template<>
+    void get_payload_array::copy_to_array(OCByteString &item, void *array, size_t pos)
+    {
+        ((OCByteString *)array)[pos] = item;
+    }
+
+    template<>
+    void get_payload_array::copy_to_array(const OCByteString &item, void *array, size_t pos)
+    {
+        ((OCByteString *)array)[pos] = item;
+    }
+
+    template<>
     void get_payload_array::copy_to_array(OC::OCRepresentation item, void* array, size_t pos)
     {
         ((OCRepPayload**)array)[pos] = item.getPayload();
@@ -403,6 +422,10 @@ namespace OC
                         (char**)vis.array,
                         vis.dimensions);
                 break;
+            case AttributeType::OCByteString:
+                OCRepPayloadSetByteStringArrayAsOwner(payload, item.attrname().c_str(),
+                                                      (OCByteString *)vis.array, vis.dimensions);
+                break;
             case AttributeType::OCRepresentation:
                 OCRepPayloadSetPropObjectArrayAsOwner(payload, item.attrname().c_str(),
                         (OCRepPayload**)vis.array, vis.dimensions);
@@ -454,6 +477,9 @@ namespace OC
                     OCRepPayloadSetPropString(root, val.attrname().c_str(),
                             static_cast<std::string>(val).c_str());
                     break;
+                case AttributeType::OCByteString:
+                    OCRepPayloadSetPropByteString(root, val.attrname().c_str(), val.getValue<OCByteString>());
+                    break;
                 case AttributeType::OCRepresentation:
                     OCRepPayloadSetPropObjectAsOwner(root, val.attrname().c_str(),
                             static_cast<OCRepresentation>(val).getPayload());
@@ -529,6 +555,19 @@ namespace OC
             return std::string{};
         }
     }
+
+    template<>
+    OCByteString OCRepresentation::payload_array_helper_copy<OCByteString>(
+        size_t index, const OCRepPayloadValue *pl)
+    {
+        OCByteString result {NULL, 0};
+        if (pl->arr.ocByteStrArray[index].len)
+        {
+            result = (pl->arr.ocByteStrArray[index]);
+        }
+        return result;
+    }
+
     template<>
     OCRepresentation OCRepresentation::payload_array_helper_copy<OCRepresentation>(
             size_t index, const OCRepPayloadValue* pl)
@@ -612,6 +651,9 @@ namespace OC
             case OCREP_PROP_STRING:
                 payload_array_helper<std::string>(pl, calcArrayDepth(pl->arr.dimensions));
                 break;
+            case OCREP_PROP_BYTE_STRING:
+                payload_array_helper<OCByteString>(pl, calcArrayDepth(pl->arr.dimensions));
+                break;
             case OCREP_PROP_OBJECT:
                 payload_array_helper<OCRepresentation>(pl, calcArrayDepth(pl->arr.dimensions));
                 break;
@@ -923,6 +965,9 @@ namespace OC
             case AttributeType::String:
                 os << "String";
                 break;
+            case AttributeType::OCByteString:
+                os << "OCByteString";
+                break;
             case AttributeType::OCRepresentation:
                 os << "OCRepresentation";
                 break;
@@ -1216,6 +1261,24 @@ namespace OC
         str = "(null)";
     }
 
+    template <>
+    void to_string_visitor::operator()(std::vector<uint8_t> const &item)
+    {
+        std::ostringstream stream;
+        for (size_t i = 0; i < item.size(); i++ )
+        {
+            stream << "\\x" << std::hex << (int) item[i];
+        }
+        str = stream.str();
+    }
+
+    template<>
+    void to_string_visitor::operator()(OCByteString const &item)
+    {
+        std::vector<uint8_t> v(item.bytes, item.bytes + item.len);
+        operator()(v);
+    }
+
     template<>
     void to_string_visitor::operator()(OCRepresentation const& /*item*/)
     {
index b83061f..9fd3d5b 100644 (file)
@@ -18,6 +18,7 @@
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
+#include "iotivity_config.h"
 #include "OCResource.h"
 #include "OCUtilities.h"
 
index cdf7d7c..e0106c5 100644 (file)
@@ -37,13 +37,20 @@ with_mq = oclib_env.get('WITH_MQ')
 ######################################################################
 # Build flags
 ######################################################################
+with_upstream_libcoap = oclib_env.get('WITH_UPSTREAM_LIBCOAP')
+if with_upstream_libcoap == '1':
+       # For bring up purposes only, we manually copy the forked version to where the unforked version is downloaded.
+       oclib_env.AppendUnique(CPPPATH = ['#extlibs/libcoap/libcoap/include'])
+else:
+       # For bring up purposes only, the forked version will live here.
+       oclib_env.AppendUnique(CPPPATH = ['../csdk/connectivity/lib/libcoap-4.1.1/include'])
+
 oclib_env.AppendUnique(CPPPATH = [
                '../include/',
                '../csdk/stack/include',
                '../c_common/ocrandom/include',
                '../csdk/logger/include',
                '../oc_logger/include',
-               '../csdk/connectivity/lib/libcoap-4.1.1',
                '../csdk/connectivity/api'
                ])
 
@@ -67,6 +74,7 @@ if target_os == 'android':
 
 if target_os == 'tizen':
        oclib_env.AppendUnique(CPPDEFINES = ['__TIZEN__'])
+       oclib_env.ParseConfig('pkg-config --cflags --libs sqlite3')
 
 if target_os in ['linux'] and oclib_env.get('SIMULATOR', False):
     oclib_env.Append( RPATH = oclib_env.Literal('\\$$ORIGIN'))
index 40b1e79..c018e28 100644 (file)
@@ -29,7 +29,7 @@ target_os = env.get('TARGET_OS')
 src_dir = env.get('SRC_DIR')
 build_dir = env.get('BUILD_DIR')
 
-if target_os in ['linux']:
+if target_os in ['linux', 'windows']:
        # Verify that 'google unit test' library is installed.  If not,
        # get it and install it
        SConscript('#extlibs/gtest/SConscript')
@@ -59,24 +59,9 @@ if target_os in ['linux']:
        # Build Provisioning API unit test
        if env.get('SECURED') == '1':
                SConscript('csdk/security/provisioning/unittest/SConscript')
-               SConscript('provisioning/unittests/SConscript')
-
-elif target_os == 'windows' and env.get('TEST') == '1':
-       # Verify that 'google unit test' library is installed.  If not,
-       # get it and install it
-       SConscript('#extlibs/gtest/SConscript')
-
-       # Build C stack's unit tests.
-       SConscript('csdk/stack/test/SConscript')
-       SConscript('csdk/connectivity/test/SConscript')
-
-       # Build Security Resource Manager unit tests
-       if env.get('SECURED') == '1':
-               SConscript('csdk/security/unittest/SConscript')
-
-       # Build Provisioning API unit test
-       if env.get('SECURED') == '1':
-               SConscript('csdk/security/provisioning/unittest/SConscript')
+               # TODO: Enable provisioning and associated unit tests for Windows
+               if target_os != 'windows':
+                       SConscript('provisioning/unittests/SConscript')
 
 elif target_os in ['darwin', 'msys_nt']:
        # Verify that 'google unit test' library is installed.  If not,
index 5e177be..54fc760 100644 (file)
 #include <oic_string.h>
 #include "payload_logging.h"
 
+bool operator==(const OCByteString& lhs, const OCByteString& rhs)
+{
+    bool result = (lhs.len == rhs.len);
+    if (result)
+    {
+        result = (memcmp(lhs.bytes, rhs.bytes, lhs.len) == 0);
+    }
+    return result;
+}
+
 namespace OC
 {
     bool operator==(const OC::NullType&, const OC::NullType&)
@@ -249,6 +259,13 @@ namespace OCRepresentationEncodingTest
         startRep.setValue("DoubleAttr", 3.333);
         startRep.setValue("BoolAttr", true);
         startRep.setValue("StringAttr", std::string("String attr"));
+
+        uint8_t binval[] = {0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8,
+                            0x9, 0x0, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF
+                           };
+        OCByteString byteString = {binval, sizeof(binval)};
+        startRep.setValue("ByteStringAttr", byteString);
+
         OC::MessageContainer mc1;
         mc1.addRepresentation(startRep);
 
@@ -274,6 +291,8 @@ namespace OCRepresentationEncodingTest
         EXPECT_EQ(3.333, r.getValue<double>("DoubleAttr"));
         EXPECT_EQ(true, r.getValue<bool>("BoolAttr"));
         EXPECT_STREQ("String attr", r.getValue<std::string>("StringAttr").c_str());
+        const char *expectedByteString = "\\x1\\x2\\x3\\x4\\x5\\x6\\x7\\x8\\x9\\x0\\xa\\xb\\xc\\xd\\xe\\xf";
+        EXPECT_STREQ(expectedByteString, r.getValueToString("ByteStringAttr").c_str());
 
         OCPayloadDestroy(cparsed);
     }
@@ -331,8 +350,8 @@ namespace OCRepresentationEncodingTest
 
         uint8_t* cborData;
         size_t cborSize;
-        OCPayload* cparsed;
         EXPECT_EQ(OC_STACK_OK, OCConvertPayload((OCPayload*)cstart, &cborData, &cborSize));
+        OCPayload* cparsed;
         EXPECT_EQ(OC_STACK_OK, OCParsePayload(&cparsed, PAYLOAD_TYPE_REPRESENTATION,
                     cborData, cborSize));
         OCPayloadDestroy((OCPayload*)cstart);
@@ -375,11 +394,23 @@ namespace OCRepresentationEncodingTest
         std::vector<std::string> strarr {"item1", "item2", "item3", "item4"};
         std::vector<OC::OCRepresentation> objarr {subRep1, subRep2, subRep3};
 
+        uint8_t binval1[] = {0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8};
+        OCByteString byteStringRef1 {binval1, sizeof(binval1)};
+        OCByteString byteString1 {NULL,0};
+        EXPECT_TRUE(OCByteStringCopy(&byteString1, &byteStringRef1));
+        uint8_t binval2[] = {0x9, 0x0, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF};
+        OCByteString byteStringRef2 {binval2, sizeof(binval2)};
+        OCByteString byteString2 {NULL,0};
+        EXPECT_TRUE(OCByteStringCopy(&byteString2, &byteStringRef2));
+        std::vector<OCByteString> bytestrarrRef {byteStringRef1, byteStringRef2 };
+        std::vector<OCByteString> bytestrarr {byteString1, byteString2 };
+
         startRep["iarr"] = iarr;
         startRep["darr"] = darr;
         startRep["barr"] = barr;
         startRep["strarr"] = strarr;
         startRep["objarr"] = objarr;
+        startRep["bytestrarr"] = bytestrarr;
 
         // Encode/decode
         OC::MessageContainer mc1;
@@ -391,16 +422,16 @@ namespace OCRepresentationEncodingTest
         uint8_t* cborData;
         size_t cborSize;
         OCPayload* cparsed;
-        EXPECT_EQ(OC_STACK_OK, OCConvertPayload((OCPayload*)cstart, &cborData, &cborSize));
+        EXPECT_EQ(OC_STACK_OK, OCConvertPayload((OCPayload *)cstart, &cborData, &cborSize));
         EXPECT_EQ(OC_STACK_OK, OCParsePayload(&cparsed, PAYLOAD_TYPE_REPRESENTATION,
-                    cborData, cborSize));
-        OCPayloadDestroy((OCPayload*)cstart);
+                                              cborData, cborSize));
+        OCPayloadDestroy((OCPayload *)cstart);
         OICFree(cborData);
 
         OC::MessageContainer mc2;
         mc2.setPayload(cparsed);
         EXPECT_EQ(1u, mc2.representations().size());
-        const OC::OCRepresentationr = mc2.representations()[0];
+        const OC::OCRepresentation &r = mc2.representations()[0];
 
         // Test
         std::vector<int> iarr2 = r["iarr"];
@@ -408,12 +439,15 @@ namespace OCRepresentationEncodingTest
         std::vector<bool> barr2 = r["barr"];
         std::vector<std::string> strarr2 = r["strarr"];
         std::vector<OC::OCRepresentation> objarr2 = r["objarr"];
+        std::vector<OCByteString> bytestrarr2 = r["bytestrarr"];
 
         EXPECT_EQ(iarr, iarr2);
         EXPECT_EQ(darr, darr2);
         EXPECT_EQ(barr, barr2);
         EXPECT_EQ(strarr, strarr2);
         EXPECT_EQ(objarr, objarr2);
+
+        EXPECT_EQ(bytestrarrRef, bytestrarr2);
         OCPayloadDestroy(cparsed);
     }
 
@@ -438,32 +472,58 @@ namespace OCRepresentationEncodingTest
         std::vector<std::vector<OC::OCRepresentation>> objarr
         {{subRep1, subRep2, subRep3}, {subRep3, subRep2, subRep1}};
 
+        uint8_t binval1[] = {0x1, 0x2, 0x3, 0x4};
+        OCByteString byteStringRef1 {binval1, sizeof(binval1) };
+        OCByteString byteString1 {NULL,0};
+        EXPECT_TRUE(OCByteStringCopy(&byteString1, &byteStringRef1));
+        uint8_t binval2[] = {0x5, 0x6, 0x7, 0x8};
+        OCByteString byteStringRef2 {binval2, sizeof(binval2) };
+        OCByteString byteString2 {NULL,0};
+        EXPECT_TRUE(OCByteStringCopy(&byteString2, &byteStringRef2));
+        uint8_t binval3[] = {0x9, 0x0, 0xA, 0xB};
+        OCByteString byteStringRef3 {binval3, sizeof(binval3) };
+        OCByteString byteString3 {NULL,0};
+        EXPECT_TRUE(OCByteStringCopy(&byteString3, &byteStringRef3));
+        uint8_t binval4[] = {0xC, 0xD, 0xE, 0xF};
+        OCByteString byteStringRef4 {binval4, sizeof(binval4) };
+        OCByteString byteString4 {NULL,0};
+        EXPECT_TRUE(OCByteStringCopy(&byteString4, &byteStringRef4));
+        std::vector<std::vector<OCByteString>> bytestrarrRef
+        {
+            {byteStringRef1, byteStringRef2}, {byteStringRef3, byteStringRef4}
+        };
+        std::vector<std::vector<OCByteString>> bytestrarr
+        {
+            {byteString1, byteString2}, {byteString3, byteString4}
+        };
+
         startRep["iarr"] = iarr;
         startRep["darr"] = darr;
         startRep["barr"] = barr;
         startRep["strarr"] = strarr;
         startRep["objarr"] = objarr;
+        startRep["bytestrarr"] = bytestrarr;
 
         // Encode/decode
         OC::MessageContainer mc1;
         mc1.addRepresentation(startRep);
 
-        OCRepPayloadcstart = mc1.getPayload();
+        OCRepPayload *cstart = mc1.getPayload();
         EXPECT_EQ(PAYLOAD_TYPE_REPRESENTATION, cstart->base.type);
 
         uint8_t* cborData;
         size_t cborSize;
         OCPayload* cparsed;
-        EXPECT_EQ(OC_STACK_OK, OCConvertPayload((OCPayload*)cstart, &cborData, &cborSize));
+        EXPECT_EQ(OC_STACK_OK, OCConvertPayload((OCPayload *)cstart, &cborData, &cborSize));
         EXPECT_EQ(OC_STACK_OK, OCParsePayload(&cparsed, PAYLOAD_TYPE_REPRESENTATION,
-                    cborData, cborSize));
-        OCPayloadDestroy((OCPayload*)cstart);
+                                              cborData, cborSize));
+        OCPayloadDestroy((OCPayload *)cstart);
         OICFree(cborData);
 
         OC::MessageContainer mc2;
         mc2.setPayload(cparsed);
         EXPECT_EQ(1u, mc2.representations().size());
-        const OC::OCRepresentationr = mc2.representations()[0];
+        const OC::OCRepresentation &r = mc2.representations()[0];
 
         // Test
         std::vector<std::vector<int>> iarr2 = r["iarr"];
@@ -471,12 +531,16 @@ namespace OCRepresentationEncodingTest
         std::vector<std::vector<bool>> barr2 = r["barr"];
         std::vector<std::vector<std::string>> strarr2 = r["strarr"];
         std::vector<std::vector<OC::OCRepresentation>> objarr2 = r["objarr"];
+        std::vector<std::vector<OCByteString>> bytestrarr2 = r["bytestrarr"];
 
         EXPECT_EQ(iarr, iarr2);
         EXPECT_EQ(darr, darr2);
         EXPECT_EQ(barr, barr2);
         EXPECT_EQ(strarr, strarr2);
         EXPECT_EQ(objarr, objarr2);
+
+        EXPECT_EQ(bytestrarrRef, bytestrarr2);
+
         OCPayloadDestroy(cparsed);
     }
 
@@ -501,32 +565,62 @@ namespace OCRepresentationEncodingTest
         std::vector<std::vector<OC::OCRepresentation>> objarr
         {{subRep1, subRep3}, {subRep3, subRep2, subRep1}};
 
+        uint8_t binval1[] = {0x1};
+        OCByteString byteStringRef1 {binval1, sizeof(binval1) };
+        OCByteString byteString1 {NULL,0};
+        EXPECT_TRUE(OCByteStringCopy(&byteString1, &byteStringRef1));
+        uint8_t binval3[] = {0x2, 0x3, 0x4};
+        OCByteString byteStringRef3 {binval3, sizeof(binval3) };
+        OCByteString byteString3 {NULL,0};
+        EXPECT_TRUE(OCByteStringCopy(&byteString3, &byteStringRef3));
+        uint8_t binval4[] = {0x5, 0x6, 0x7, 0x8};
+        OCByteString byteStringRef4 {binval4, sizeof(binval4) };
+        OCByteString byteString4 {NULL,0};
+        EXPECT_TRUE(OCByteStringCopy(&byteString4, &byteStringRef4));
+
+        std::vector<std::vector<OCByteString>> bytestrarrRef
+        {
+            {byteStringRef1}, {byteStringRef3, byteStringRef4}
+        };
+
+        std::vector<std::vector<OCByteString>> bytestrarr
+        {
+            {byteString1}, {byteString3, byteString4}
+        };
+
         startRep["iarr"] = iarr;
         startRep["darr"] = darr;
         startRep["barr"] = barr;
         startRep["strarr"] = strarr;
         startRep["objarr"] = objarr;
 
+        startRep["bytestrarr"] = bytestrarr;
+
+        EXPECT_STREQ("[[\\x1 ] [\\x2\\x3\\x4 \\x5\\x6\\x7\\x8 ] ]",
+                     startRep.getValueToString("bytestrarr").c_str());
         // Encode/decode
         OC::MessageContainer mc1;
         mc1.addRepresentation(startRep);
 
-        OCRepPayloadcstart = mc1.getPayload();
+        OCRepPayload *cstart = mc1.getPayload();
         EXPECT_EQ(PAYLOAD_TYPE_REPRESENTATION, cstart->base.type);
 
-        uint8_tcborData;
+        uint8_t *cborData;
         size_t cborSize;
-        OCPayload* cparsed;
-        EXPECT_EQ(OC_STACK_OK, OCConvertPayload((OCPayload*)cstart, &cborData, &cborSize));
-        EXPECT_EQ(OC_STACK_OK, OCParsePayload(&cparsed, PAYLOAD_TYPE_REPRESENTATION,
-                    cborData, cborSize));
-        OCPayloadDestroy((OCPayload*)cstart);
+        OCPayload *cparsed;
+        OCStackResult result = OCConvertPayload((OCPayload *)cstart, &cborData, &cborSize);
+        EXPECT_EQ(OC_STACK_OK, result);
+        result = OCParsePayload(&cparsed, PAYLOAD_TYPE_REPRESENTATION,
+                                cborData, cborSize);
+        EXPECT_EQ(OC_STACK_OK, result);
+
+        OCPayloadDestroy((OCPayload *)cstart);
         OICFree(cborData);
 
         OC::MessageContainer mc2;
         mc2.setPayload(cparsed);
         EXPECT_EQ(1u, mc2.representations().size());
-        const OC::OCRepresentationr = mc2.representations()[0];
+        const OC::OCRepresentation &r = mc2.representations()[0];
 
         // Test
         std::vector<std::vector<int>> iarr2 = r["iarr"];
@@ -535,6 +629,8 @@ namespace OCRepresentationEncodingTest
         std::vector<std::vector<std::string>> strarr2 = r["strarr"];
         std::vector<std::vector<OC::OCRepresentation>> objarr2 = r["objarr"];
 
+        std::vector<std::vector<OCByteString>> bytestrarr2 = r["bytestrarr"];
+
         // Note: due to the way that the CSDK works, all 2d arrays need to be rectangular.
         // Since std::vector doesn't require this, items received on the other side end up
         // being backfilled.  This section removes the backfilling
@@ -543,12 +639,16 @@ namespace OCRepresentationEncodingTest
         barr2[1].pop_back();
         strarr2[0].pop_back();
         objarr2[0].pop_back();
+        bytestrarr2[0].pop_back();
 
         EXPECT_EQ(iarr, iarr2);
         EXPECT_EQ(darr, darr2);
         EXPECT_EQ(barr, barr2);
         EXPECT_EQ(strarr, strarr2);
         EXPECT_EQ(objarr, objarr2);
+        EXPECT_EQ(bytestrarr.size(), bytestrarr2.size());
+        EXPECT_EQ(bytestrarrRef, bytestrarr2);
+
         OCPayloadDestroy(cparsed);
     }
 
@@ -587,32 +687,96 @@ namespace OCRepresentationEncodingTest
                 {{subRep3, subRep2},{subRep1, subRep2}}
             };
 
+        uint8_t binval1[] = {0x1, 0x2, 0x3, 0x4};
+        OCByteString byteStringRef1 {binval1, sizeof(binval1)};
+        OCByteString byteString1 {NULL,0};
+        EXPECT_TRUE(OCByteStringCopy(&byteString1, &byteStringRef1));
+        uint8_t binval2[] = {0x5, 0x6, 0x7, 0x8};
+        OCByteString byteStringRef2 {binval2, sizeof(binval2)};
+        OCByteString byteString2 {NULL,0};
+        EXPECT_TRUE(OCByteStringCopy(&byteString2, &byteStringRef2));
+        uint8_t binval3[] = {0x9, 0x0, 0xA, 0xB};
+        OCByteString byteStringRef3 {binval3, sizeof(binval3)};
+        OCByteString byteString3 {NULL,0};
+        EXPECT_TRUE(OCByteStringCopy(&byteString3, &byteStringRef3));
+        uint8_t binval4[] = {0xC, 0xD, 0xE, 0xF};
+        OCByteString byteStringRef4 {binval4, sizeof(binval4)};
+        OCByteString byteString4 {NULL,0};
+        EXPECT_TRUE(OCByteStringCopy(&byteString4, &byteStringRef4));
+        uint8_t binval5[] = {0x11, 0x12, 0x13, 0x14};
+        OCByteString byteStringRef5 {binval5, sizeof(binval5)};
+        OCByteString byteString5 {NULL,0};
+        EXPECT_TRUE(OCByteStringCopy(&byteString5, &byteStringRef5));
+        uint8_t binval6[] = {0x15, 0x16, 0x17, 0x18};
+        OCByteString byteStringRef6 {binval6, sizeof(binval6)};
+        OCByteString byteString6 {NULL,0};
+        EXPECT_TRUE(OCByteStringCopy(&byteString6, &byteStringRef6));
+        uint8_t binval7[] = {0x19, 0x10, 0x1A, 0x1B};
+        OCByteString byteStringRef7 {binval7, sizeof(binval7)};
+        OCByteString byteString7 {NULL,0};
+        EXPECT_TRUE(OCByteStringCopy(&byteString7, &byteStringRef7));
+        uint8_t binval8[] = {0x1C, 0x1D, 0x1E, 0x1F};
+        OCByteString byteStringRef8 {binval8, sizeof(binval8)};
+        OCByteString byteString8 {NULL,0};
+        EXPECT_TRUE(OCByteStringCopy(&byteString8, &byteStringRef8));
+        uint8_t binval9[] = {0x21, 0x22, 0x23, 0x24};
+        OCByteString byteStringRef9 {binval9, sizeof(binval9)};
+        OCByteString byteString9 {NULL,0};
+        EXPECT_TRUE(OCByteStringCopy(&byteString9, &byteStringRef9));
+        uint8_t binval10[] = {0x25, 0x26, 0x27, 0x28};
+        OCByteString byteStringRef10 {binval10, sizeof(binval10)};
+        OCByteString byteString10 {NULL,0};
+        EXPECT_TRUE(OCByteStringCopy(&byteString10, &byteStringRef10));
+        uint8_t binval11[] = {0x29, 0x20, 0x2A, 0x2B};
+        OCByteString byteStringRef11 {binval11, sizeof(binval11)};
+        OCByteString byteString11 {NULL,0};
+        EXPECT_TRUE(OCByteStringCopy(&byteString11, &byteStringRef11));
+        uint8_t binval12[] = {0xFF};
+        OCByteString byteStringRef12 {binval12, sizeof(binval12)};
+        OCByteString byteString12 {NULL,0};
+        EXPECT_TRUE(OCByteStringCopy(&byteString12, &byteStringRef12));
+
+        std::vector<std::vector<std::vector<OCByteString>>> bytestrarrRef
+        {
+            {{byteStringRef1, byteStringRef2}, {byteStringRef3, byteStringRef4}},
+            {{byteStringRef5, byteStringRef6}, {byteStringRef7, byteStringRef8}},
+            {{byteStringRef9, byteStringRef10}, {byteStringRef11, byteStringRef12}}
+        };
+
+        std::vector<std::vector<std::vector<OCByteString>>> bytestrarr
+        {
+            {{byteString1, byteString2}, {byteString3, byteString4}},
+            {{byteString5, byteString6}, {byteString7, byteString8}},
+            {{byteString9, byteString10}, {byteString11, byteString12}}
+        };
+
         startRep["iarr"] = iarr;
         startRep["darr"] = darr;
         startRep["barr"] = barr;
         startRep["strarr"] = strarr;
         startRep["objarr"] = objarr;
+        startRep["bytestrarr"] = bytestrarr;
 
         // Encode/decode
         OC::MessageContainer mc1;
         mc1.addRepresentation(startRep);
 
-        OCRepPayloadcstart = mc1.getPayload();
+        OCRepPayload *cstart = mc1.getPayload();
         EXPECT_EQ(PAYLOAD_TYPE_REPRESENTATION, cstart->base.type);
 
-        uint8_tcborData;
+        uint8_t *cborData;
         size_t cborSize;
-        OCPayloadcparsed;
-        EXPECT_EQ(OC_STACK_OK, OCConvertPayload((OCPayload*)cstart, &cborData, &cborSize));
+        OCPayload *cparsed;
+        EXPECT_EQ(OC_STACK_OK, OCConvertPayload((OCPayload *)cstart, &cborData, &cborSize));
         EXPECT_EQ(OC_STACK_OK, OCParsePayload(&cparsed, PAYLOAD_TYPE_REPRESENTATION,
-                    cborData, cborSize));
-        OCPayloadDestroy((OCPayload*)cstart);
+                                              cborData, cborSize));
+        OCPayloadDestroy((OCPayload *)cstart);
         OICFree(cborData);
 
         OC::MessageContainer mc2;
         mc2.setPayload(cparsed);
         EXPECT_EQ(1u, mc2.representations().size());
-        const OC::OCRepresentationr = mc2.representations()[0];
+        const OC::OCRepresentation &r = mc2.representations()[0];
 
         // Test
         std::vector<std::vector<std::vector<int>>> iarr2 = r["iarr"];
@@ -620,12 +784,14 @@ namespace OCRepresentationEncodingTest
         std::vector<std::vector<std::vector<bool>>> barr2 = r["barr"];
         std::vector<std::vector<std::vector<std::string>>> strarr2 = r["strarr"];
         std::vector<std::vector<std::vector<OC::OCRepresentation>>> objarr2 = r["objarr"];
+        std::vector<std::vector<std::vector<OCByteString>>> bytestrarr2 = r["bytestrarr"];
 
         EXPECT_EQ(iarr, iarr2);
         EXPECT_EQ(darr, darr2);
         EXPECT_EQ(barr, barr2);
         EXPECT_EQ(strarr, strarr2);
         EXPECT_EQ(objarr, objarr2);
+        EXPECT_EQ(bytestrarrRef, bytestrarr2);
         OCPayloadDestroy(cparsed);
     }
 
@@ -673,32 +839,92 @@ namespace OCRepresentationEncodingTest
                 {{subRep3, subRep2}}
             };
 
+        uint8_t binval1[] = {0x1, 0x2, 0x3, 0x4};
+        OCByteString byteStringRef1 {binval1, sizeof(binval1)};
+        OCByteString byteString1 {NULL,0};
+        EXPECT_TRUE(OCByteStringCopy(&byteString1, &byteStringRef1));
+        uint8_t binval2[] = {0x5, 0x6, 0x7, 0x8};
+        OCByteString byteStringRef2 {binval2, sizeof(binval2)};
+        OCByteString byteString2 {NULL,0};
+        EXPECT_TRUE(OCByteStringCopy(&byteString2, &byteStringRef2));
+        uint8_t binval3[] = {0x9, 0x0, 0xA, 0xB};
+        OCByteString byteStringRef3 {binval3, sizeof(binval3)};
+        OCByteString byteString3 {NULL,0};
+        EXPECT_TRUE(OCByteStringCopy(&byteString3, &byteStringRef3));
+        uint8_t binval4[] = {0xC, 0xD, 0xE, 0xF};
+        OCByteString byteStringRef4 {binval4, sizeof(binval4)};
+        OCByteString byteString4 {NULL,0};
+        EXPECT_TRUE(OCByteStringCopy(&byteString4, &byteStringRef4));
+        uint8_t binval5[] = {0x11, 0x12, 0x13, 0x14};
+        OCByteString byteStringRef5 {binval5, sizeof(binval5)};
+        OCByteString byteString5 {NULL,0};
+        EXPECT_TRUE(OCByteStringCopy(&byteString5, &byteStringRef5));
+        uint8_t binval6[] = {0x15, 0x16, 0x17, 0x18};
+        OCByteString byteStringRef6 {binval6, sizeof(binval6)};
+        OCByteString byteString6 {NULL,0};
+        EXPECT_TRUE(OCByteStringCopy(&byteString6, &byteStringRef6));
+        uint8_t binval8[] = {0x1C, 0x1D, 0x1E, 0x1F};
+        OCByteString byteStringRef8 {binval8, sizeof(binval8)};
+        OCByteString byteString8 {NULL,0};
+        EXPECT_TRUE(OCByteStringCopy(&byteString8, &byteStringRef8));
+        uint8_t binval9[] = {0x21, 0x22, 0x23, 0x24};
+        OCByteString byteStringRef9 {binval9, sizeof(binval9)};
+        OCByteString byteString9 {NULL,0};
+        EXPECT_TRUE(OCByteStringCopy(&byteString9, &byteStringRef9));
+        uint8_t binval10[] = {0x25, 0x26, 0x27, 0x28};
+        OCByteString byteStringRef10 {binval10, sizeof(binval10)};
+        OCByteString byteString10 {NULL,0};
+        EXPECT_TRUE(OCByteStringCopy(&byteString10, &byteStringRef10));
+        uint8_t binval11[] = {0x29, 0x20, 0x2A, 0x2B};
+        OCByteString byteStringRef11 {binval11, sizeof(binval11)};
+        OCByteString byteString11 {NULL,0};
+        EXPECT_TRUE(OCByteStringCopy(&byteString11, &byteStringRef11));
+        uint8_t binval12[] = {0xFF};
+        OCByteString byteStringRef12 {binval12, sizeof(binval12)};
+        OCByteString byteString12 {NULL,0};
+        EXPECT_TRUE(OCByteStringCopy(&byteString12, &byteStringRef12));
+
+        std::vector<std::vector<std::vector<OCByteString>>> bytestrarrRef
+        {
+            {{byteStringRef1, byteStringRef2}, {byteStringRef3, byteStringRef4}},
+            {{byteStringRef5, byteStringRef6}, {byteStringRef8}},
+            {{byteStringRef9, byteStringRef10}, {byteStringRef11, byteStringRef12}}
+        };
+
+        std::vector<std::vector<std::vector<OCByteString>>> bytestrarr
+        {
+            {{byteString1, byteString2}, {byteString3, byteString4}},
+            {{byteString5, byteString6}, {byteString8}},
+            {{byteString9, byteString10}, {byteString11, byteString12}}
+        };
+
         startRep["iarr"] = iarr;
         startRep["darr"] = darr;
         startRep["barr"] = barr;
         startRep["strarr"] = strarr;
         startRep["objarr"] = objarr;
+        startRep["bytestrarr"] = bytestrarr;
 
         // Encode/decode
         OC::MessageContainer mc1;
         mc1.addRepresentation(startRep);
 
-        OCRepPayloadcstart = mc1.getPayload();
+        OCRepPayload *cstart = mc1.getPayload();
         EXPECT_EQ(PAYLOAD_TYPE_REPRESENTATION, cstart->base.type);
 
-        uint8_tcborData;
+        uint8_t *cborData;
         size_t cborSize;
-        OCPayloadcparsed;
-        EXPECT_EQ(OC_STACK_OK, OCConvertPayload((OCPayload*)cstart, &cborData, &cborSize));
+        OCPayload *cparsed;
+        EXPECT_EQ(OC_STACK_OK, OCConvertPayload((OCPayload *)cstart, &cborData, &cborSize));
         EXPECT_EQ(OC_STACK_OK, OCParsePayload(&cparsed, PAYLOAD_TYPE_REPRESENTATION,
-                    cborData, cborSize));
-        OCPayloadDestroy((OCPayload*)cstart);
+                                              cborData, cborSize));
+        OCPayloadDestroy((OCPayload *)cstart);
         OICFree(cborData);
 
         OC::MessageContainer mc2;
         mc2.setPayload(cparsed);
         EXPECT_EQ(1u, mc2.representations().size());
-        const OC::OCRepresentationr = mc2.representations()[0];
+        const OC::OCRepresentation &r = mc2.representations()[0];
 
         // Test
         std::vector<std::vector<std::vector<int>>> iarr2 = r["iarr"];
@@ -706,6 +932,7 @@ namespace OCRepresentationEncodingTest
         std::vector<std::vector<std::vector<bool>>> barr2 = r["barr"];
         std::vector<std::vector<std::vector<std::string>>> strarr2 = r["strarr"];
         std::vector<std::vector<std::vector<OC::OCRepresentation>>> objarr2 = r["objarr"];
+        std::vector<std::vector<std::vector<OCByteString>>> bytestrarr2 = r["bytestrarr"];
 
         // Note: due to the way that the CSDK works, all 3d arrays need to be cuboidal.
         // Since std::vector doesn't require this, items received on the other side end up
@@ -716,12 +943,14 @@ namespace OCRepresentationEncodingTest
         strarr2[1][1].pop_back();
         objarr2[1][1].pop_back();
         objarr2[2].pop_back();
+        bytestrarr2[1][1].pop_back();
 
         EXPECT_EQ(iarr, iarr2);
         EXPECT_EQ(darr, darr2);
         EXPECT_EQ(barr, barr2);
         EXPECT_EQ(strarr, strarr2);
         EXPECT_EQ(objarr, objarr2);
+        EXPECT_EQ(bytestrarrRef, bytestrarr2);
         OCPayloadDestroy(cparsed);
     }
 
index 5701fc2..471c302 100644 (file)
@@ -148,6 +148,21 @@ namespace OCRepresentationTest
         EXPECT_EQ("OC::OCRepresentation", rep[AttrName].getValueToString());
     }
 
+    TEST(OCRepresentationValueToString, ByteString)
+    {
+        static const std::string AttrName = "ByteStringTest";
+        static uint8_t binval[] = {0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8,
+                                   0x9, 0x0, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF};
+
+        OCByteString bytestring {binval, sizeof(binval)};
+        OCRepresentation rep;
+
+        rep.setValue(AttrName, bytestring);
+        const char* expected = "\\x1\\x2\\x3\\x4\\x5\\x6\\x7\\x8"
+                               "\\x9\\x0\\xa\\xb\\xc\\xd\\xe\\xf";
+        EXPECT_STREQ(expected, rep.getValueToString(AttrName).c_str() );
+    }
+
     TEST(OCRepresentationValueToString, IntegerVector)
     {
         static const std::string AttrName = "VectorTest";
@@ -344,6 +359,125 @@ namespace OCRepresentationTest
         EXPECT_EQ(Expected, rep[AttrName].getValueToString());
     }
 
+    TEST(OCRepresentationValueToByteString, ByteStringVector)
+    {
+        static const std::string AttrName = "VectorTest";
+        OCRepresentation rep;
+
+        uint8_t binval1[] = {0x1, 0x2, 0x3, 0x4};
+        OCByteString s1 {binval1, sizeof(binval1)};
+        uint8_t binval2[] = {0x5, 0x6, 0x7, 0x8};
+        OCByteString s2 {binval2, sizeof(binval2)};
+        uint8_t binval3[] = {0x9, 0x0, 0xA, 0xB};
+        OCByteString s3 {binval3, sizeof(binval3)};
+        vector<OCByteString> vect {s1, s2, s3};
+
+        uint8_t binval4[] = {0xC, 0xD, 0xE, 0xF};
+        OCByteString s4 {binval4, sizeof(binval4)};
+        uint8_t binval5[] = {0x11, 0x12, 0x13, 0x14};
+        OCByteString s5 {binval5, sizeof(binval5)};
+        uint8_t binval6[] = {0x15, 0x16, 0x17, 0x18};
+        OCByteString s6 {binval6, sizeof(binval6)};
+        vector<OCByteString> vect2 {s4, s5, s6};
+
+        rep.setValue(AttrName, vect);
+        const char *expected1tob = "[\\x1\\x2\\x3\\x4 \\x5\\x6\\x7\\x8 \\x9\\x0\\xa\\xb ]";
+        EXPECT_EQ(expected1tob, rep.getValueToString(AttrName));
+        EXPECT_EQ(expected1tob, rep[AttrName].getValueToString());
+
+        rep.setValue(AttrName, vect2);
+        const char *expectedcto18 = "[\\xc\\xd\\xe\\xf \\x11\\x12\\x13\\x14 \\x15\\x16\\x17\\x18 ]";
+        EXPECT_EQ(expectedcto18, rep.getValueToString(AttrName));
+        EXPECT_EQ(expectedcto18, rep[AttrName].getValueToString());
+    }
+
+    TEST(OCRepresentationValueToByteString, ByteStringVectorVector)
+    {
+        static const std::string AttrName = "VectorTest";
+        OCRepresentation rep;
+
+        uint8_t binval1[] = {0x1, 0x2, 0x3, 0x4};
+        OCByteString s1 {binval1, sizeof(binval1)};
+        uint8_t binval2[] = {0x5, 0x6, 0x7, 0x8};
+        OCByteString s2 {binval2, sizeof(binval2)};
+        uint8_t binval3[] = {0x9, 0x0, 0xA, 0xB};
+        OCByteString s3 {binval3, sizeof(binval3)};
+        vector<OCByteString> vect1 {s1, s2, s3};
+
+        uint8_t binval4[] = {0xC, 0xD, 0xE, 0xF};
+        OCByteString s4 {binval4, sizeof(binval4)};
+        uint8_t binval5[] = {0x11, 0x12, 0x13, 0x14};
+        OCByteString s5 {binval5, sizeof(binval5)};
+        uint8_t binval6[] = {0x15, 0x16, 0x17, 0x18};
+        OCByteString s6 {binval6, sizeof(binval6)};
+        vector<OCByteString> vect2 {s4, s5, s6};
+
+        vector<vector<OCByteString>> vect {vect1, vect2};
+
+        rep.setValue(AttrName, vect);
+
+        const char *expected =
+            "[["
+            "\\x1\\x2\\x3\\x4 \\x5\\x6\\x7\\x8 \\x9\\x0\\xa\\xb "
+            "] ["
+            "\\xc\\xd\\xe\\xf \\x11\\x12\\x13\\x14 \\x15\\x16\\x17\\x18 "
+            "] ]"
+            ;
+
+        EXPECT_EQ(expected, rep.getValueToString(AttrName));
+        EXPECT_EQ(expected, rep[AttrName].getValueToString());
+    }
+
+    TEST(OCRepresentationValueToByteString, ByteStringVectorVectorVector)
+    {
+        static const std::string AttrName = "VectorTest";
+        OCRepresentation rep;
+
+        uint8_t binval1[] = {0x1, 0x2, 0x3, 0x4};
+        OCByteString s1 {binval1, sizeof(binval1)};
+        uint8_t binval2[] = {0x5, 0x6, 0x7, 0x8};
+        OCByteString s2 {binval2, sizeof(binval2)};
+        uint8_t binval3[] = {0x9, 0x0, 0xA, 0xB};
+        OCByteString s3 {binval3, sizeof(binval3)};
+        vector<OCByteString> vect11 {s1, s2, s3};
+
+        uint8_t binval4[] = {0xC, 0xD, 0xE, 0xF};
+        OCByteString s4 {binval4, sizeof(binval4)};
+        uint8_t binval5[] = {0x11, 0x12, 0x13, 0x14};
+        OCByteString s5 {binval5, sizeof(binval5)};
+        uint8_t binval6[] = {0x15, 0x16, 0x17, 0x18};
+        OCByteString s6 {binval6, sizeof(binval6)};
+        vector<OCByteString> vect12 {s4, s5, s6};
+
+        uint8_t binval7[] = {0x19, 0x10, 0x1A, 0x1B};
+        OCByteString s7 {binval7, sizeof(binval7)};
+        uint8_t binval8[] = {0x1C, 0x1D, 0x1E, 0x1F};
+        OCByteString s8 {binval8, sizeof(binval8)};
+        vector<OCByteString> vect21 {s7, s8};
+
+        uint8_t binval9[] = {0x21, 0x22, 0x23, 0x24};
+        OCByteString s9 {binval9, sizeof(binval9)};
+        vector<OCByteString> vect22 {s9};
+
+        vector<vector<OCByteString>> vect1 {vect11, vect12};
+        vector<vector<OCByteString>> vect2 {vect21, vect22};
+        vector<vector<vector<OCByteString>>> vect {vect1, vect2};
+        rep.setValue(AttrName, vect);
+        static const std::string expected =
+            "[[["
+            "\\x1\\x2\\x3\\x4 \\x5\\x6\\x7\\x8 \\x9\\x0\\xa\\xb "
+            "] ["
+            "\\xc\\xd\\xe\\xf \\x11\\x12\\x13\\x14 \\x15\\x16\\x17\\x18 "
+            "] ] [["
+            "\\x19\\x10\\x1a\\x1b \\x1c\\x1d\\x1e\\x1f "
+            "] ["
+            "\\x21\\x22\\x23\\x24 "
+            "] ] ]";
+
+        EXPECT_EQ(expected, rep.getValueToString(AttrName));
+        EXPECT_EQ(expected, rep[AttrName].getValueToString());
+    }
+
     TEST(OCRepresentationValueToString, SubRepresentationVector)
     {
         static const std::string AttrName = "VectorTest";
@@ -413,12 +547,15 @@ namespace OCRepresentationTest
         rep[AttrName] = nullptr;
         EXPECT_TRUE(rep.isNULL(AttrName));
 
+// @todo: Re-enable this part of the unit test. MSVC can't assign to nullptr_t.
+#ifndef _MSC_VER
         std::nullptr_t repout = rep[AttrName];
         std::nullptr_t repout2;
         repout2 = rep[AttrName];
 
         EXPECT_EQ(nullptr, repout);
         EXPECT_EQ(nullptr, repout2);
+#endif
 
         double badout;
         EXPECT_FALSE(rep.getValue<double>(AttrName, badout));
index c53c83c..3968948 100644 (file)
@@ -119,7 +119,11 @@ namespace OCResourceResponseTest
         EXPECT_EQ(NULL, response.getRequestHandle());
     }
 
+#ifdef _MSC_VER
+    TEST(ResourceHandleTest, DISABLED_SetGetResourceHandleValidHandle)
+#else
     TEST(ResourceHandleTest, SetGetResourceHandleValidHandle)
+#endif
     {
         OCResourceResponse response;
         OCResourceHandle resHandle;
index dc9907f..9d2684f 100644 (file)
@@ -46,6 +46,10 @@ unittests_env.PrependUnique(CPPPATH = [
                '#extlibs/hippomocks-master/HippoMocksTest'
                ])
 
+if target_os in ['windows']:
+       unittests_env.AppendUnique(LIBS = ['ws2_32'])
+       unittests_env.AppendUnique(CPPPATH = ['#extlibs/boost/boost'])
+
 unittests_env.AppendUnique(LIBPATH = [unittests_env.get('BUILD_DIR')])
 unittests_env.PrependUnique(LIBS = [
                'oc',
@@ -81,6 +85,14 @@ unittests_src = [
                'OCHeaderOptionTest.cpp'
        ]
 
+# TODO: Fix errors in the following Windows tests.
+if target_os in ['windows']:
+       unittests_src.remove('OCPlatformTest.cpp')
+       unittests_src.remove('OCRepresentationEncodingTest.cpp')
+       if '12.0' == unittests_env['MSVC_VERSION']:
+               unittests_src.remove('OCRepresentationTest.cpp')
+               unittests_src.remove('OCResourceTest.cpp')
+
 if (('SUB' in with_mq) or ('PUB' in with_mq) or ('BROKER' in with_mq)):
        unittests_src = unittests_src + ['OCMQResourceTest.cpp']
 
@@ -93,7 +105,9 @@ Alias("unittests", [unittests])
 
 unittests_env.AppendTarget('unittests')
 if unittests_env.get('TEST') == '1':
-       if target_os in ['linux']:
+       if target_os in ['windows']:
+               unittests_env.AppendENVPath('PATH', unittests_env.get('BUILD_DIR'))
+       if target_os in ['linux', 'windows']:
                 from tools.scons.RunTest import *
                 run_test(unittests_env,
                          'resource_unittests_unittests.memcheck',
diff --git a/run.bat b/run.bat
index 861d851..a81745e 100644 (file)
--- a/run.bat
+++ b/run.bat
@@ -22,24 +22,6 @@ if "!SECOND_ARG!"=="debug" (
   set DEBUG="%ProgramFiles(x86)%\Windows Kits\10\Debuggers\x64\cdb.exe" -2 -c "g" 
 )
 
-IF "%CURRENT_ARG%" == "build" IF "%BUILD_MSYS%" == "" (
-  IF NOT "%VS140COMNTOOLS%" == "" (
-    CALL "%VS140COMNTOOLS%"vsvars32.bat
-  ) ELSE (
-    IF NOT "%VS120COMNTOOLS%" == "" (
-      CALL "%VS120COMNTOOLS%"vsvars32.bat
-      )
-    )
-
-  IF NOT "!VSINSTALLDIR!" == "" (
-      CALL "!VSINSTALLDIR!VC\vcvarsall.bat" amd64
-  ) ELSE (
-    @ECHO WARNING: Could not find vsvarsall.bat.
-    @ECHO WARNING: VISUAL STUDIO 2013/2015 DOES NOT APPEAR TO BE INSTALLED ON THIS MACHINE
-    GOTO :EOF
-  )
-)
-
 REM We need to append the "PATH" so the octbstack.dll can be found by executables
 IF "%BUILD_MSYS%" == "" (
   set BUILD_DIR=out\windows\amd64\debug
@@ -57,8 +39,15 @@ set TEST=1
 set LOGGING=OFF
 set WITH_RD=1
 set ROUTING=EP
+set WITH_UPSTREAM_LIBCOAP=0
 
-set BUILD_OPTIONS= TARGET_OS=%TARGET_OS% TARGET_ARCH=%TARGET_ARCH% RELEASE=0 WITH_RA=0 TARGET_TRANSPORT=IP SECURED=%SECURED% WITH_TCP=0 BUILD_SAMPLE=ON LOGGING=%LOGGING% TEST=%TEST% WITH_RD=%WITH_RD% ROUTING=%ROUTING%
+set BUILD_OPTIONS= TARGET_OS=%TARGET_OS% TARGET_ARCH=%TARGET_ARCH% RELEASE=0 WITH_RA=0 TARGET_TRANSPORT=IP SECURED=%SECURED% WITH_TCP=0 BUILD_SAMPLE=ON LOGGING=%LOGGING% TEST=%TEST% WITH_RD=%WITH_RD% ROUTING=%ROUTING% WITH_UPSTREAM_LIBCOAP=%WITH_UPSTREAM_LIBCOAP%
+
+REM Use MSVC_VERSION=12.0 for VS2013, or MSVC_VERSION=14.0 for VS2015.
+REM If MSVC_VERSION has not been defined here, SCons chooses automatically a VS version.
+IF NOT "%MSVC_VERSION%" == "" (
+  set BUILD_OPTIONS=%BUILD_OPTIONS% MSVC_VERSION=%MSVC_VERSION%
+)
 
 REM *** BUILD OPTIONS ***
 
@@ -101,21 +90,29 @@ if "!CURRENT_ARG!"=="server" (
   %DEBUG% %BUILD_DIR%\resource\csdk\stack\test\cbortests.exe
   %DEBUG% %BUILD_DIR%\resource\csdk\security\unittest\unittest.exe
   %DEBUG% %BUILD_DIR%\resource\csdk\security\provisioning\unittest\unittest.exe
+  %DEBUG% %BUILD_DIR%\resource\c_common\ocrandom\test\randomtests.exe
+  %DEBUG% %BUILD_DIR%\resource\c_common\oic_malloc\test\malloctests.exe
+  %DEBUG% %BUILD_DIR%\resource\c_common\oic_string\test\stringtests.exe
+  %DEBUG% %BUILD_DIR%\resource\c_common\oic_time\test\timetests.exe
+  %DEBUG% %BUILD_DIR%\resource\unittests\unittests.exe
 ) else if "!CURRENT_ARG!"=="build" (
   echo Starting IoTivity build with these options:
   echo   TARGET_OS=%TARGET_OS%
   echo   TARGET_ARCH=%TARGET_ARCH%
   echo   SECURED=%SECURED%
+  echo   TEST=%TEST%
   echo   LOGGING=%LOGGING%
   echo   WITH_RD=%WITH_RD%
   echo   ROUTING=%ROUTING%
-  CL.exe | findstr "Compiler Verison"
+  echo   WITH_UPSTREAM_LIBCOAP=%WITH_UPSTREAM_LIBCOAP%
   echo.scons VERBOSE=1 %BUILD_OPTIONS%
   scons VERBOSE=1 %BUILD_OPTIONS%
 ) else if "!CURRENT_ARG!"=="clean" (
   scons VERBOSE=1 %BUILD_OPTIONS% -c clean
   rd /s /q out
   del .sconsign.dblite
+  del extlibs\gtest\gtest*.lib
+  del extlibs\gtest\gtest-1.7.0\src\gtest*.obj
 ) else if "!CURRENT_ARG!"=="cleangtest" (
   rd /s /q extlibs\gtest\gtest-1.7.0
   del extlibs\gtest\gtest-1.7.0.zip
index 1b9e7f3..4203602 100644 (file)
@@ -41,7 +41,7 @@ CPPPATH: The directories that the preprocessor will search for include headers.
 CPPDEFINES: Platform independent specification of C preprocessor definitions.
 
 Note: CPPPATH and CPPDEFINES is common for all compiler. But others are
-compiler specific, when change the key value, it may requried to specify the
+compiler specific, when change the key value, it may required to specify the
 target platform(actually the compiler).
 
 e.g.
@@ -82,7 +82,7 @@ In above example, 'target_os' is used. How to get it?
 
 User can build IoTivity project on Linux / Windows / MAC OSX for various
 targets(Linux, Tizen, Android, Arduino, Windows, MAC OSX, IOS ...). Most
-platform specific configures have been done in the common scripts which are in
+platform specific configurations have been done in the common scripts which are in
 build_common. The common scripts prepare an environment named 'env' with
 target platform specific configuration.
 
@@ -105,7 +105,7 @@ or
        env['XXX']
 
 XXX is the information name, below are the extra information added by IoTivity
-common scrirpts:
+common scripts:
 BUILD_DIR: the path of the build directory, all output are in this directory
 SRC_DIR: the path of the top directory of the source code
 RELEASE: build type, boolean. True - release build, False - debug build
@@ -136,7 +136,7 @@ PrintTargets(): print all target names in the help information.
 AppendTarget(name, target = None): add a target name into targets list, when use
        PrintTargets, the target name will be print
 # @param name - the name of the target(s)(user defined name)
-# @param target - Final binary, file(s) etc genereted after build.
+# @param target - Final binary, file(s) etc generated after build.
 
 InstallTarget(files, name): it takes the same action as AppendTarget, besides,
        it installs the 'files' to BUILD_DIR.
@@ -149,7 +149,7 @@ will be auto added to the environment and the library will be built and linked
 into the final binary.
 
 CreateBin(bin, src): For Arduino, after build the program, it's required to
-be converted into specific format (e.g .hex). This function will genearate the
+be converted into specific format (e.g .hex). This function will generate the
 required .hex (and .eep if target arch is avr) file from 'bin'.
 
 UploadHelp(): For different board, the upload command line is different, this
@@ -171,7 +171,7 @@ Download(target, url): Download source code from URL 'url' and save as 'target'.
 # @param target - the name of the source code package to be saved as
 # @param url - the URL from which to download the source code
 
-Configure(cwd, cmd): Run configure command(such as: boostrap, configure etc.
+Configure(cwd, cmd): Run configure command(such as: bootstrap, configure etc.
 usually it's done before build a library)
 # @param cwd - the work directory, full path or relative path to the directory
                where the library build script in
@@ -188,7 +188,7 @@ Install_lib(lib): Install library binaries to <src_dir>/deps/<target_os>/lib/<ar
 Scons provides a function 'SConscript(scripts, [exports, variant_dir, duplicate])'
 It tells scons to execute one or more subsidiary configuration files(A script,
 usually named SConscript). Take below project hierarchy as example to show how
-to organize the scripts.
+to organise the scripts.
 
                prj
                |-------prj_1
@@ -204,7 +204,7 @@ to organize the scripts.
 As above project hierarchy, in 'SConstruct' file in the 'prj' directory, there
 should include some lines like these:
 
-#Please change this part according to the organization of your projects.
+#Please change this part according to the organisation of your projects.
 #Note: To make the output is in build_dir, the path of the scripts should
 #be relevant to build_dir
 SConscript(build_dir + 'prj_1/SConscript')
@@ -223,7 +223,7 @@ The path is relevant to 'prj_1/SConscript'. You can also use the full path
 (build_dir + 'prj_1/sub_prj_1x/SConscript'), but it's not recommended.
 
 Above just to show a recommended way to manage subsidiary scripts. You don't
-need restrictly follow it.
+need strictly follow it.
 
 ==== The content of a typical script ====
 
@@ -231,8 +231,8 @@ After run the scripts in build_common (usually it's done at the beginning of
 SConstruct), an global environment 'env' is exported, 'env' has include the
 default configuration of the target OS and arch. 'env' is used in all projects,
 should avoid to change its keys. To avoid change 'env', usually clone 'env' and
-update it accroding to the requirement of current sub project. Then specify the
-target(usually binary) to build.
+update it according to the requirement of current sub project. Then specify the
+target (usually binary) to build.
 
 Below is an example:
        # import the global environment 'env'
@@ -247,7 +247,7 @@ Below is an example:
        new_env.AppendUnique(xxx = [ .... ])
 
        # Specify the target(application, library, object or others) to build
-       ts = new_env.Program('progam_name', [source_list])
+       ts = new_env.Program('program_name', [source_list])
 
        # Install the target (optional)
        # If it's an important library or daemon to be published
index 2f92966..22eb6db 100755 (executable)
@@ -55,6 +55,10 @@ if target_os not in ['arduino','darwin', 'ios', 'windows']:
     #if env.get('WITH_RD') == '1':
         #SConscript('resource-directory/SConscript')
 
+    # Build coap-http-proxy project
+    if target_os in ['linux'] and env.get('WITH_PROXY', False):
+        SConscript('coap-http-proxy/SConscript')
+
 # Build EasySetup module
 if target_os in ['arduino', 'android', 'linux','tizen']:
     SConscript('easy-setup/SConscript')
diff --git a/service/coap-http-proxy/SConscript b/service/coap-http-proxy/SConscript
new file mode 100644 (file)
index 0000000..cc3aa2c
--- /dev/null
@@ -0,0 +1,86 @@
+#******************************************************************
+#
+# Copyright 2016 Samsung Electronics 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.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+##
+# CoAP-HTTP Proxy build script
+##
+Import('env')
+import os
+local_env = env.Clone()
+
+if local_env.get('LOGGING'):
+    local_env.AppendUnique(CPPDEFINES = ['-DTB_LOG'])
+
+if env.get('RELEASE'):
+    env.AppendUnique(CCFLAGS = ['-Os'])
+    env.AppendUnique(CPPDEFINES = ['NDEBUG'])
+else:
+    env.AppendUnique(CCFLAGS = ['-g'])
+
+target_os = env.get('TARGET_OS')
+src_dir = env.get('SRC_DIR')
+
+######################################################################
+# Build flags
+######################################################################
+local_env.AppendUnique(CPPPATH = ['include',
+                        os.path.join(src_dir, 'resource/csdk/stack/include'),
+                        os.path.join(src_dir, 'resource/csdk/connectivity/common/inc/'),
+                        os.path.join(src_dir, 'resource/csdk/connectivity/lib/libcoap-4.1.1'),
+                        os.path.join(src_dir, 'extlibs/cjson'),
+               ])
+local_env.PrependUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'connectivity_abstraction', 'coap'])
+if target_os not in ['windows']:
+    local_env.AppendUnique(CXXFLAGS = ['-O2', '-g', '-Wall', '-Wextra'])
+
+if target_os in ['linux']:
+    local_env.AppendUnique(LIBS = ['pthread', 'curl'])
+
+if target_os == 'android':
+    local_env.AppendUnique(CXXFLAGS = ['-frtti', '-fexceptions'])
+    local_env.AppendUnique(LIBS = ['gnustl_static'])
+
+    if not env.get('RELEASE'):
+        rd_env.AppendUnique(LIBS = ['log'])
+######################################################################
+# Source files and Targets
+######################################################################
+
+proxy_src = [
+       './src/CoapHttpHandler.c',
+       './src/CoapHttpMap.c',
+       './src/CoapHttpParser.c',
+]
+
+if target_os in ['tizen'] :
+    proxysdk = local_env.SharedLibrary('coap_http_proxy', proxy_src)
+else :
+    proxysdk = local_env.StaticLibrary('coap_http_proxy', proxy_src)
+
+local_env.InstallTarget(proxysdk, 'coap_http_proxy')
+local_env.UserInstallTargetLib(proxysdk, 'coap_http_proxy')
+local_env.UserInstallTargetHeader('include/CoapHttpHandler.h', 'service/coap-http-proxy', 'CoapHttpHandler.h')
+
+
+######################################################################
+# Samples for the proxy
+######################################################################
+if target_os in ['linux']:
+    SConscript('samples/SConscript')
diff --git a/service/coap-http-proxy/include/CoapHttpHandler.h b/service/coap-http-proxy/include/CoapHttpHandler.h
new file mode 100644 (file)
index 0000000..7843000
--- /dev/null
@@ -0,0 +1,58 @@
+/* ****************************************************************
+ *
+ * Copyright 2016 Samsung Electronics 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.
+ *
+ ******************************************************************/
+
+/**
+ * @file
+ * This file contains the functions to initiate request or response handling by CHP
+ */
+
+#ifndef COAP_HTTP_HANDLER_H_
+#define COAP_HTTP_HANDLER_H_
+
+#include "ocstack.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+/**
+ * Initialize the CoAP HTTP Proxy.
+ * @return  ::OC_STACK_OK or Appropriate error code.
+ */
+OCStackResult CHPInitialize();
+
+/**
+ * Terminate the CoAP HTTP Proxy.
+ * @return  ::OC_STACK_OK or Appropriate error code.
+ */
+OCStackResult CHPTerminate();
+
+/**
+ * API to check if CoAP-HTTP Proxy is initialized.
+ * @return  true if initialized else false.
+ */
+bool CHPIsInitialized();
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/service/coap-http-proxy/include/CoapHttpMap.h b/service/coap-http-proxy/include/CoapHttpMap.h
new file mode 100644 (file)
index 0000000..c0e9d6e
--- /dev/null
@@ -0,0 +1,94 @@
+/* ****************************************************************
+ *
+ * Copyright 2016 Samsung Electronics 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.
+ *
+ ******************************************************************/
+
+/**
+ * @file
+ * This file contains CoAP to HTTP mapping
+ */
+
+#ifndef COAP_HTTP_MAP_H_
+#define COAP_HTTP_MAP_H_
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+#include "CoapHttpParser.h"
+#include "cJSON.h"
+
+/**
+ * Function to get CoAP code for an HTTP code.
+ * @param[in]   httpCode            HTTP Code.
+ * @param[in]   method              Request Method type
+ * @param[out]  ocfCode             Corresponding OCF code.
+ * @return ::OC_STACK_OK or appropriate error code.
+ */
+OCStackResult CHPGetOCCode(const HttpResponseResult_t httpCode, const OCMethod method,
+                           OCEntityHandlerResult *ocfCode);
+
+/**
+ * Function to get CoAP option for an HTTP option.
+ * @param[in]   httpOption        HTTP Option.
+ * @param[out]  ret               Corresponding CoAP option.
+ * @return ::OC_STACK_OK or appropriate error code.
+ */
+OCStackResult CHPGetOCOption(const HttpHeaderOption_t *httpOption, OCHeaderOption *ret);
+
+/**
+ * Function to get CoAP payload format for HTTP payload format.
+ * @param[in]   httpContentType   HTTP payload format.
+ * @return CoAP payload format.
+ */
+OCPayloadFormat CHPGetOCContentType(const char *httpContentType);
+
+/**
+ * Function to get HTTP method for OCF method.
+ * @param[in]   method            OCF method.
+ * @param[out]  httpMethod        Corresponding HTTP method.
+ * @return ::OC_STACK_OK or appropriate error code.
+ */
+OCStackResult CHPGetHttpMethod(const OCMethod method, HttpMethod_t *httpMethod);
+
+/**
+ * Function to get HTTP option for OCF option.
+ * @param[in]   option            OCF option.
+ * @param[out]  ret               Corresponding HTTP option.
+ * @return ::OC_STACK_OK or appropriate error code.
+ */
+OCStackResult CHPGetHttpOption(const OCHeaderOption* option, HttpHeaderOption_t **ret);
+
+/**
+ * Function to convert Json payload to CBOR representational payload.
+ * @param[in]   rootJSon          Json payload.
+ * @param[out]  payload           CBor representational payload.
+ */
+void CHPJsonToRepPayload(cJSON* rootJSon, OCRepPayload* payload);
+
+/**
+ * Function to convert CBOR representational payload to Json payload.
+ * @param[in]   repData           Cbor representational payload.
+ * @return CJson payload.
+ */
+cJSON* CHPRepPayloadToJson(OCRepPayload* repData);
+#ifdef __cplusplus
+}
+#endif
+#endif
diff --git a/service/coap-http-proxy/include/CoapHttpParser.h b/service/coap-http-proxy/include/CoapHttpParser.h
new file mode 100644 (file)
index 0000000..5e5067c
--- /dev/null
@@ -0,0 +1,195 @@
+/* ****************************************************************
+ *
+ * Copyright 2016 Samsung Electronics 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.
+ *
+ ******************************************************************/
+
+/**
+ * @file
+ * This file contains HTTP parsing functions
+ */
+
+#ifndef COAP_HTTP_PARSER_H_
+#define COAP_HTTP_PARSER_H_
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+#include <unistd.h>
+#include "uarraylist.h"
+#include "octypes.h"
+
+#define CHP_MAX_HF_DATA_LENGTH 1024
+#define CHP_MAX_HF_NAME_LENGTH 255
+#define JSON_CONTENT_TYPE "application/json"
+#define CBOR_CONTENT_TYPE "application/cbor"
+#define ACCEPT_MEDIA_TYPE (CBOR_CONTENT_TYPE "; q=1.0, " JSON_CONTENT_TYPE "; q=0.5")
+
+// HTTP Option types
+#define HTTP_OPTION_CACHE_CONTROL   "cache-control"
+#define HTTP_OPTION_ACCEPT          "accept"
+#define HTTP_OPTION_IF_MATCH        "if-match"
+#define HTTP_OPTION_IF_NONE_MATCH   "if-none-match"
+#define HTTP_OPTION_ETAG            "etag"
+#define HTTP_OPTION_CONTENT_TYPE    "content-type"
+#define HTTP_OPTION_CONTENT_LENGTH  "content-length"
+#define HTTP_OPTION_EXPIRES         "expires"
+
+/**
+ * @enum HttpResponseResult_t
+ * Enums for HTTP Response values
+ */
+typedef enum
+{
+    /* Response status code - START HERE */
+    CHP_EMPTY = 0,                       /**< Empty */
+    CHP_SUCCESS = 200,                   /**< Success */
+    CHP_CREATED = 201,                   /**< Created */
+    CHP_ACCEPTED = 202,                  /**< Accepted */
+    CHP_NO_CONTENT = 204,                /**< No Content */
+    CHP_RESET_CONTENT = 205,             /**< Reset content */
+    CHP_NOT_MODIFIED = 304,              /**< Not Modified */
+    CHP_BAD_REQ = 400,                   /**< Bad Request */
+    CHP_UNAUTHORIZED_REQ = 401,          /**< Unauthorized Request */
+    CHP_FORBIDDEN_REQ = 403,             /**< Forbidden Request */
+    CHP_NOT_FOUND = 404,                 /**< Not found */
+    CHP_NOT_ACCEPTABLE = 406,            /**< Not Acceptable */
+    CHP_REQUEST_ENTITY_TOO_LARGE = 413,  /**< Request Entity Too Large */
+    CHP_REQUEST_URI_TOO_LARGE = 414,     /**< Request URI Too Large */
+    CHP_UNSUPPORTED_MEDIA_TYPE = 415,    /**< Unsupported Media type */
+    CHP_INTERNAL_SERVER_ERROR = 500,     /**< Internal server Error */
+    CHP_NOT_IMPLEMENTED = 501,           /**< Not Implemented */
+    CHP_BAD_GATEWAY = 502,               /**< Bad Gateway */
+    CHP_SERVICE_UNAVAILABLE = 503,       /**< Service Unavailable */
+    CHP_GATEWAY_TIMEOUT = 504,           /**< Gateway Timeout */
+    CHP_VERSION_NOT_SUPPORTED = 505      /**< Version not supported */
+    /* Response status code - END HERE */
+} HttpResponseResult_t;
+
+/**
+ * Header fields structure to be filled
+ *
+ * This structure is used to hold header information.
+ */
+typedef struct
+{
+    uint16_t optionLength;                                  /**< Option length. **/
+    char optionName[CHP_MAX_HF_NAME_LENGTH];                /**< Option name. **/
+    char optionData[CHP_MAX_HF_DATA_LENGTH];                /**< Option data values. **/
+} HttpHeaderOption_t;
+
+typedef enum
+{
+    CHP_GET = 1,   /**< GET */
+    CHP_POST,      /**< POST */
+    CHP_PUT,       /**< PUT */
+    CHP_DELETE,    /**< DELETE */
+    CHP_INVALID
+}HttpMethod_t;
+
+typedef struct HttpRequest_t
+{
+    unsigned short httpMajor;
+    unsigned short httpMinor;
+    HttpMethod_t method;
+    u_arraylist_t *headerOptions;
+    char resourceUri[CHP_MAX_HF_DATA_LENGTH];
+    void *payload;
+    size_t payloadLength;
+    bool payloadCached;
+    char payloadFormat[CHP_MAX_HF_DATA_LENGTH];
+    char acceptFormat[CHP_MAX_HF_DATA_LENGTH];
+}HttpRequest_t;
+
+typedef struct HttpResponse_t
+{
+    unsigned short httpMajor;
+    unsigned short httpMinor;
+    HttpResponseResult_t status;
+    u_arraylist_t *headerOptions;
+    char dataFormat[CHP_MAX_HF_DATA_LENGTH];
+    void *payload;
+    size_t payloadLength;
+}HttpResponse_t;
+
+typedef void (*CHPResponseCallback)(const HttpResponse_t *response, void *context);
+
+/**
+ * Function to initialize Parser and HTTP stack.
+ */
+OCStackResult CHPParserInitialize();
+
+/**
+ * Function to terminate parser and HTTP stack.
+ */
+OCStackResult CHPParserTerminate();
+
+/**
+ * Function to initiate TCP session and post HTTP request. If the method returns
+ * success, payload might be cached by the parser (req->payloadCached) and caller shall not free the
+ * payload if the flag is set.
+ * @param[in]   req         Object containing HTTP request information.
+ * @param[in]   httpcb      Callback for http response.
+ * @param[in]   context     Any app specific context for request
+ */
+OCStackResult CHPPostHttpRequest(HttpRequest_t *req, CHPResponseCallback httpcb,
+                                 void *context);
+
+/**
+ * Macro to verify the validity of input argument.
+ *
+ * @param  arg  log level
+ * @param  log_tag  log tag
+ * @param  log_message  log message
+ * @param  ret  return value
+ */
+#define VERIFY_NON_NULL_RET(arg, log_tag, log_message, ret) \
+    if (NULL == (arg)) \
+    { \
+        OIC_LOG_V(ERROR, (log_tag), "Invalid input:%s", (log_message)); \
+        return (ret); \
+    } \
+
+/**
+ * Macro to verify the validity of input argument.
+ *
+ * @param  arg  log level
+ * @param  log_tag  log tag
+ * @param  log_message  log message
+ */
+#define VERIFY_NON_NULL(arg, log_tag, log_message) \
+    VERIFY_NON_NULL_RET((arg), (log_tag), (log_message), CA_STATUS_INVALID_PARAM)
+
+/**
+ * Macro to verify the validity of input argument.
+ *
+ * @param  arg  log level
+ * @param  log_tag  log tag
+ * @param  log_message  log message
+ */
+#define VERIFY_NON_NULL_VOID(arg, log_tag, log_message) \
+    if (NULL == (arg)) { \
+        OIC_LOG_V(ERROR, (log_tag), "Invalid input:%s", (log_message)); \
+        return; \
+    } \
+
+#ifdef __cplusplus
+}
+#endif
+#endif
diff --git a/service/coap-http-proxy/samples/SConscript b/service/coap-http-proxy/samples/SConscript
new file mode 100644 (file)
index 0000000..fe165a2
--- /dev/null
@@ -0,0 +1,54 @@
+#******************************************************************
+#
+# Copyright 2016 Samsung Electronics 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.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+##
+# CoAP-HTTP-Proxy Sample Apps build script
+##
+
+Import('env')
+
+lib_env = env.Clone()
+SConscript('#service/third_party_libs.scons', 'lib_env')
+
+proxy_sample_app_env = lib_env.Clone()
+
+target_os = env.get('TARGET_OS')
+######################################################################
+# Build flags
+######################################################################
+proxy_sample_app_env.AppendUnique(CPPPATH = ['../include'])
+
+if target_os not in ['windows']:
+    proxy_sample_app_env.AppendUnique(CXXFLAGS = ['-O2', '-g', '-Wall', '-Wextra', '-std=c++0x'])
+proxy_sample_app_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
+proxy_sample_app_env.AppendUnique(RPATH = [env.get('BUILD_DIR')])
+proxy_sample_app_env.PrependUnique(LIBS = ['coap_http_proxy', 'oc', 'octbstack', 'curl', 'connectivity_abstraction'])
+
+if env.get('SECURED') == '1':
+    proxy_sample_app_env.AppendUnique(LIBS = ['tinydtls'])
+
+####################################################################
+# Source files and Targets
+######################################################################
+proxy_server = proxy_sample_app_env.Program('proxy_main', 'proxy_main.c')
+
+Alias("coap_http_proxy", [proxy_server])
+
+env.AppendTarget('coap_http_proxy')
diff --git a/service/coap-http-proxy/samples/proxy_main.c b/service/coap-http-proxy/samples/proxy_main.c
new file mode 100644 (file)
index 0000000..9f2479d
--- /dev/null
@@ -0,0 +1,95 @@
+//******************************************************************
+//
+// Copyright 2016 Samsung Electronics 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#include "CoapHttpHandler.h"
+
+#include <signal.h>
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+
+int g_quitFlag = 0;
+
+void handleSigInt(int signum);
+
+/*
+* This method is an entry point of CoAP-HTTP Proxy.
+*/
+
+int main()
+{
+    printf("CoAP-HTTP proxy is starting..\n");
+    OCStackResult result = OCInit(NULL, 0, OC_SERVER);
+    if (result != OC_STACK_OK)
+    {
+        printf("Failed starting proxy\n");
+        return 0;
+    }
+
+    if (CHPInitialize() != OC_STACK_OK)
+    {
+        printf("Failed to start proxy.\n");
+        OCStop();
+        return 0;
+    }
+
+    printf("Proxy started successfully.\n");
+
+    signal(SIGINT, handleSigInt);
+    while (!g_quitFlag)
+    {
+        if (OCProcess() != OC_STACK_OK)
+        {
+            CHPTerminate();
+            OCStop();
+            printf("OCStack process error\n");
+            return 0;
+        }
+    }
+
+    if (CHPTerminate() != OC_STACK_OK)
+    {
+        printf("CHPTerminate failed.\n");
+    }
+    else
+    {
+        printf("CHPTerminate success.\n");
+    }
+
+    OCStop();
+    printf("Exiting proxy main loop...\n");
+    return 0;
+
+}
+
+/*
+* This is a signal handling function for SIGINT(CTRL+C).
+* A Resource Directory handle the SIGINT signal for safe exit.
+*
+* @param[in] signal
+*                 signal number of caught signal.
+*/
+void handleSigInt(int signum)
+{
+    if (signum == SIGINT)
+    {
+        g_quitFlag = 1;
+    }
+}
+
diff --git a/service/coap-http-proxy/src/CoapHttpHandler.c b/service/coap-http-proxy/src/CoapHttpHandler.c
new file mode 100644 (file)
index 0000000..f0ee86d
--- /dev/null
@@ -0,0 +1,502 @@
+/* ****************************************************************
+ *
+ * Copyright 2016 Samsung Electronics 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.
+ *
+ ******************************************************************/
+
+#include "CoapHttpHandler.h"
+#include "oic_malloc.h"
+#include "oic_string.h"
+#include "logger.h"
+#include "pdu.h"
+#include "ocpayload.h"
+#include "uarraylist.h"
+#include "CoapHttpParser.h"
+#include "CoapHttpMap.h"
+#include "cJSON.h"
+
+#define TAG "CHPHandler"
+
+#define CHP_RESOURCE_TYPE_NAME "core.chp"
+#define CHP_RESOURCE_INTF_NAME "oc.mi.def"
+
+/**
+ * CoAP request tracking.
+ * This structure is used to hold CoAP request information
+ */
+typedef struct
+{
+    OCMethod method;
+    OCRequestHandle requestHandle;
+} CHPRequest_t;
+
+/**
+ * Pointer to handle of the newly created proxy resource.
+ */
+static OCResourceHandle g_proxyHandle = NULL;
+static int g_isCHProxyInitialized = false;
+
+/**
+ * Function to hand over CoAP request handling to Proxy.
+ */
+OCStackResult CHPHandleOCFRequest(const OCEntityHandlerRequest* requestInfo,
+                                   const char* proxyUri);
+
+/**
+ * Entity handler to receive requests from csdk.
+ */
+OCEntityHandlerResult CHPEntityHandler(OCEntityHandlerFlag flag,
+                                       OCEntityHandlerRequest* entityHandlerRequest,
+                                       void* callbackParam);
+bool CHPIsInitialized()
+{
+    return g_isCHProxyInitialized;
+}
+
+OCStackResult CHPInitialize()
+{
+    OIC_LOG(DEBUG, TAG, "CHPInitialize IN");
+    if (g_isCHProxyInitialized)
+    {
+        OIC_LOG(DEBUG, TAG, "CH Proxy already initialized");
+        return OC_STACK_OK;
+    }
+
+    OCStackResult result = CHPParserInitialize();
+    if (OC_STACK_OK != result)
+    {
+        OIC_LOG_V(ERROR, TAG, "Parser initialization failed[%d]", result);
+        return result;
+    }
+
+    result = OCSetProxyURI(OC_RSRVD_PROXY_URI);
+    if (OC_STACK_OK != result)
+    {
+        OIC_LOG_V(ERROR, TAG, "Setting proxy uri failed[%d]", result);
+        CHPParserTerminate();
+        return result;
+    }
+
+    result = OCCreateResource(&g_proxyHandle,
+                               CHP_RESOURCE_TYPE_NAME,
+                               CHP_RESOURCE_INTF_NAME,
+                               OC_RSRVD_PROXY_URI,
+                               CHPEntityHandler,
+                               NULL,
+                               OC_ACTIVE | OC_DISCOVERABLE | OC_SLOW);
+
+    if (OC_STACK_OK != result)
+    {
+        OIC_LOG_V(ERROR, TAG, "Create resource for proxy failed[%d]", result);
+        CHPParserTerminate();
+        return result;
+    }
+
+    g_isCHProxyInitialized = true;
+    OIC_LOG(DEBUG, TAG, "CHPInitialize OUT");
+    return OC_STACK_OK;
+}
+
+OCStackResult CHPTerminate()
+{
+    OIC_LOG(DEBUG, TAG, "CHPTerminate IN");
+    OCStackResult result = CHPParserTerminate();
+    if (OC_STACK_OK != result)
+    {
+        OIC_LOG_V(ERROR, TAG, "Parser termination failed[%d]", result);
+    }
+
+    result = OCDeleteResource(g_proxyHandle);
+    if (OC_STACK_OK != result)
+    {
+        OIC_LOG_V(ERROR, TAG, "Delete resource for proxy failed[%d]", result);
+    }
+
+    g_proxyHandle = NULL;
+    g_isCHProxyInitialized = false;
+    return result;
+    OIC_LOG(DEBUG, TAG, "CHPTerminate OUT");
+}
+
+static void CHPGetProxyURI(OCHeaderOption* options, uint8_t *numOptions, char* uri,
+                           size_t uriLength)
+{
+    OIC_LOG(DEBUG, TAG, "CHPGetProxyURI IN");
+    if(!uri || uriLength <= 0)
+    {
+        OIC_LOG (INFO, TAG, "Invalid uri buffer");
+        return;
+    }
+
+    if (!options || !numOptions || 0 == *numOptions)
+    {
+        OIC_LOG (INFO, TAG, "No options present");
+        return;
+    }
+
+    for (int count = 0; count < *numOptions; count++)
+    {
+        if (options[count].protocolID == OC_COAP_ID &&
+                options[count].optionID == COAP_OPTION_PROXY_URI)
+        {
+            OIC_LOG(DEBUG, TAG, "Proxy URI is present");
+            // Extract proxy-uri and delete it from headeroptions.
+            OICStrcpy(uri, uriLength, (char *)options[count].optionData);
+            for (int fwd = count; fwd < *numOptions-1; fwd++)
+            {
+                options[count] = options[count+1];
+            }
+            *numOptions -= 1;
+            return;
+        }
+    }
+
+    OIC_LOG(DEBUG, TAG, "CHPGetProxyURI OUT");
+    return;
+}
+
+// TODO: Will be moved to OCProxyPayload
+static OCRepPayload* CHPGetDiscoveryPayload()
+{
+    OCRepPayload* payload = OCRepPayloadCreate();
+    if(!payload)
+    {
+        OIC_LOG(ERROR, TAG, PCF("Failed to create Payload"));
+        return NULL;
+    }
+
+    OCRepPayloadSetUri(payload, OC_RSRVD_PROXY_URI);
+    OCRepPayloadSetPropString(payload, OC_RSRVD_DEVICE_ID, OCGetServerInstanceIDString());
+    return payload;
+}
+
+OCEntityHandlerResult CHPEntityHandler(OCEntityHandlerFlag flag,
+                                       OCEntityHandlerRequest* entityHandlerRequest,
+                                       void* callbackParam)
+{
+    OIC_LOG_V(INFO, TAG, "Proxy request received");
+    UNUSED(callbackParam);
+
+    if(!g_isCHProxyInitialized)
+    {
+        OIC_LOG (ERROR, TAG, "Proxy not initialized");
+        return OC_EH_INTERNAL_SERVER_ERROR;
+    }
+
+    if (!entityHandlerRequest)
+    {
+        OIC_LOG (ERROR, TAG, "Invalid request pointer");
+        return OC_EH_ERROR;
+    }
+
+    if(flag & OC_OBSERVE_FLAG)
+    {
+        OIC_LOG_V (ERROR, TAG, "Proxy is not observable");
+        return OC_EH_BAD_REQ;
+    }
+    else if (flag & OC_REQUEST_FLAG)
+    {
+        /*
+         *  A proxy can handle two type of requests:
+         *  1. Discovery request in which case proxy-uri option will not be present.
+         *  2. Request for HTTP resource with proxy-uri option.
+         */
+        char proxyUri[MAX_HEADER_OPTION_DATA_LENGTH] = {'\0'};
+        CHPGetProxyURI(entityHandlerRequest->rcvdVendorSpecificHeaderOptions,
+                       &(entityHandlerRequest->numRcvdVendorSpecificHeaderOptions),
+                       proxyUri, sizeof(proxyUri));
+
+        if(proxyUri[0] != '\0')
+        {
+            // A request for HTTP resource. Response will be sent asynchronously
+            if(OC_STACK_OK == CHPHandleOCFRequest(entityHandlerRequest,
+                                                  proxyUri) )
+            {
+                return OC_EH_SLOW;
+            }
+        }
+        else
+        {
+            OCEntityHandlerResult ehResult = OC_EH_ERROR;
+            switch (entityHandlerRequest->method)
+            {
+                case OC_REST_GET:
+                case OC_REST_DISCOVER:
+                {
+                    // Generate discovery payload
+                    OIC_LOG (INFO, TAG, "Discovery request from client");
+                    ehResult = OC_EH_OK;
+                    OCEntityHandlerResponse response =
+                                { .requestHandle = entityHandlerRequest->requestHandle,
+                                  .resourceHandle = entityHandlerRequest->resource,
+                                  .ehResult = ehResult};
+
+                    response.payload = (OCPayload *)CHPGetDiscoveryPayload();
+                    // Indicate that response is NOT in a persistent buffer
+                    response.persistentBufferFlag = 0;
+
+                    // Send the response
+                    if (OCDoResponse(&response) != OC_STACK_OK)
+                    {
+                        OIC_LOG(ERROR, TAG, "Error sending response");
+                        ehResult = OC_EH_ERROR;
+                    }
+
+                    OCPayloadDestroy(response.payload);
+                    break;
+                }
+                default:
+                    // Other methods are not supported
+                    OIC_LOG (INFO, TAG, "Invalid method from client");
+                    ehResult = OC_EH_METHOD_NOT_ALLOWED;
+                    break;
+            }
+            return ehResult;
+        }
+    }
+
+    return OC_EH_ERROR;
+}
+
+void CHPHandleHttpResponse(const HttpResponse_t *httpResponse, void *context)
+{
+    OIC_LOG(DEBUG, TAG, "CHPHandleHttpResponse IN");
+    if (!httpResponse || !context)
+    {
+        OIC_LOG(ERROR, TAG, "Invalid arguements");
+        return;
+    }
+
+    CHPRequest_t *ctxt = (CHPRequest_t *)context;
+    OCEntityHandlerResponse response = { .requestHandle = ctxt->requestHandle,
+                                         .resourceHandle = g_proxyHandle};
+    response.persistentBufferFlag = 0;
+
+    OCStackResult result = CHPGetOCCode(httpResponse->status, ctxt->method,
+                                        &response.ehResult);
+    if (OC_STACK_OK != result)
+    {
+        OIC_LOG_V(ERROR, TAG, "%s failed[%d]", __func__, result);
+        response.ehResult = OC_EH_INTERNAL_SERVER_ERROR;
+        if (OCDoResponse(&response) != OC_STACK_OK)
+        {
+            OIC_LOG(ERROR, TAG, "Error sending response");
+        }
+        OICFree(ctxt);
+        return;
+    }
+
+    // ctxt not required now.
+    OICFree(ctxt);
+
+    OCPayloadFormat format = CHPGetOCContentType(httpResponse->dataFormat);
+    switch (format)
+    {
+        case OC_FORMAT_CBOR:
+            OIC_LOG(DEBUG, TAG, "Payload format is CBOR");
+            result = OCParsePayload(&response.payload, PAYLOAD_TYPE_REPRESENTATION,
+                                    httpResponse->payload, httpResponse->payloadLength);
+            if(result  != OC_STACK_OK)
+            {
+                OIC_LOG(ERROR, TAG, "Error parsing payload");
+                response.ehResult = OC_EH_INTERNAL_SERVER_ERROR;
+                if (OCDoResponse(&response) != OC_STACK_OK)
+                {
+                    OIC_LOG(ERROR, TAG, "Error sending response");
+                }
+                return;
+            }
+            break;
+        case OC_FORMAT_JSON:
+            OIC_LOG(DEBUG, TAG, "Payload format is JSON");
+            cJSON *payloadJson = cJSON_Parse((char *)httpResponse->payload);
+            OCRepPayload* payloadCbor = OCRepPayloadCreate();
+            if(!payloadCbor)
+            {
+                response.ehResult = OC_EH_INTERNAL_SERVER_ERROR;
+                if (OCDoResponse(&response) != OC_STACK_OK)
+                {
+                    OIC_LOG(ERROR, TAG, "Error sending response");
+                }
+                cJSON_Delete(payloadJson);
+                return;
+            }
+
+            CHPJsonToRepPayload(payloadJson, payloadCbor);
+            response.payload = (OCPayload *)payloadCbor;
+            cJSON_Delete(payloadJson);
+            break;
+        default:
+            OIC_LOG(ERROR, TAG, "Payload format is not supported");
+            response.ehResult = OC_EH_INTERNAL_SERVER_ERROR;
+            if (OCDoResponse(&response) != OC_STACK_OK)
+            {
+                OIC_LOG(ERROR, TAG, "Error sending response");
+            }
+            return;
+    }
+
+    // Header Options parsing
+    response.numSendVendorSpecificHeaderOptions = 0;
+    OCHeaderOption *optionsPointer = response.sendVendorSpecificHeaderOptions;
+
+    uint8_t tempOptionNumber = u_arraylist_length(httpResponse->headerOptions);
+    for (int numOptions = 0; numOptions < tempOptionNumber &&
+                             response.numSendVendorSpecificHeaderOptions < MAX_HEADER_OPTIONS;
+                             numOptions++)
+    {
+        HttpHeaderOption_t *httpOption = u_arraylist_get(httpResponse->headerOptions, numOptions);
+        result = CHPGetOCOption(httpOption, optionsPointer);
+        if (OC_STACK_OK != result)
+        {
+            OIC_LOG_V(ERROR, TAG, "CHPGetCoAPOption failed[%d][%d]", result,
+                                                response.numSendVendorSpecificHeaderOptions);
+            continue;
+        }
+
+        response.numSendVendorSpecificHeaderOptions++;
+        optionsPointer += 1;
+    }
+
+    if (OCDoResponse(&response) != OC_STACK_OK)
+    {
+        OIC_LOG(ERROR, TAG, "Error sending response");
+    }
+
+    //OICFree(coapResponseInfo.info.payload);
+    OIC_LOG(DEBUG, TAG, "CHPHandleHttpResponse OUT");
+}
+
+OCStackResult CHPHandleOCFRequest(const OCEntityHandlerRequest* requestInfo,
+                                   const char* proxyUri)
+{
+    OIC_LOG_V(DEBUG, TAG, "%s IN", __func__);
+
+    HttpRequest_t httpRequest = { .httpMajor = 1,
+                                  .httpMinor = 1};
+
+    OCEntityHandlerResponse response = { .requestHandle = requestInfo->requestHandle,
+                                         .resourceHandle = requestInfo->resource};
+    OCStackResult result = CHPGetHttpMethod(requestInfo->method, &httpRequest.method);
+    if (OC_STACK_OK != result)
+    {
+        OIC_LOG(ERROR, TAG, "Method not found in HTTP");
+        response.ehResult = OC_EH_BAD_REQ;
+        if (OCDoResponse(&response) != OC_STACK_OK)
+        {
+            OIC_LOG(ERROR, TAG, "Error sending response");
+        }
+
+        return OC_STACK_ERROR;
+    }
+
+    uint8_t vendorOptions = requestInfo->numRcvdVendorSpecificHeaderOptions;
+    if (vendorOptions)
+    {
+        httpRequest.headerOptions = u_arraylist_create();
+        for (int option = 0; option < vendorOptions; option++)
+        {
+            HttpHeaderOption_t *httpOption = NULL;
+            result = CHPGetHttpOption(requestInfo->rcvdVendorSpecificHeaderOptions + option,
+                                      &httpOption);
+            if (OC_STACK_OK != result || NULL == httpOption )
+            {
+                OIC_LOG_V(ERROR, TAG, "CHPGetHttpOption failed [%d]", result);
+                continue;
+            }
+            u_arraylist_add(httpRequest.headerOptions, (void *)httpOption);
+        }
+    }
+
+    OICStrcpy(httpRequest.resourceUri, sizeof(httpRequest.resourceUri), proxyUri);
+
+    if (requestInfo->payload && requestInfo->payload->type == PAYLOAD_TYPE_REPRESENTATION)
+    {
+        // Conversion from cbor to json.
+        cJSON *payloadJson = CHPRepPayloadToJson((OCRepPayload *)requestInfo->payload);
+        if(!payloadJson)
+        {
+            response.ehResult = OC_EH_BAD_REQ;
+            if (OCDoResponse(&response) != OC_STACK_OK)
+            {
+                OIC_LOG(ERROR, TAG, "Error sending response");
+            }
+
+            return OC_STACK_ERROR;
+
+        }
+        httpRequest.payload = (void *)cJSON_Print(payloadJson);
+        httpRequest.payloadLength = strlen(httpRequest.payload);
+        OICStrcpy(httpRequest.payloadFormat, sizeof(httpRequest.payloadFormat),
+                  CBOR_CONTENT_TYPE);
+        cJSON_Delete(payloadJson);
+    }
+
+    OICStrcpy(httpRequest.acceptFormat, sizeof(httpRequest.acceptFormat),
+              ACCEPT_MEDIA_TYPE);
+    CHPRequest_t *chpRequest = (CHPRequest_t *)OICCalloc(1, sizeof(CHPRequest_t));
+    if (!chpRequest)
+    {
+        OIC_LOG(ERROR, TAG, "Calloc failed");
+        response.ehResult = OC_EH_INTERNAL_SERVER_ERROR;
+        if (OCDoResponse(&response) != OC_STACK_OK)
+        {
+            OIC_LOG(ERROR, TAG, "Error sending response");
+        }
+
+        OICFree(httpRequest.payload);
+        u_arraylist_destroy(httpRequest.headerOptions);
+        return OC_STACK_NO_MEMORY;
+    }
+
+    chpRequest->requestHandle = requestInfo->requestHandle;
+    chpRequest->method = requestInfo->method;
+
+    result = CHPPostHttpRequest(&httpRequest, CHPHandleHttpResponse,
+                                (void *)chpRequest);
+    if (OC_STACK_OK != result)
+    {
+        OIC_LOG_V(ERROR, TAG, "CHPPostHttpRequest failed[%d]", result);
+        switch (result)
+        {
+            case OC_STACK_INVALID_URI:
+                response.ehResult = OC_EH_BAD_REQ;
+                break;
+            default:
+                response.ehResult = OC_EH_INTERNAL_SERVER_ERROR;
+        }
+
+        if (OCDoResponse(&response) != OC_STACK_OK)
+        {
+            OIC_LOG(ERROR, TAG, "Error sending response");
+        }
+
+        OICFree(httpRequest.payload);
+        OICFree(chpRequest);
+        u_arraylist_destroy(httpRequest.headerOptions);
+        return OC_STACK_ERROR;
+    }
+
+    if(!httpRequest.payloadCached)
+    {
+        // Free only if parser has not cached it.
+        OICFree(httpRequest.payload);
+    }
+    u_arraylist_destroy(httpRequest.headerOptions);
+    OIC_LOG_V(DEBUG, TAG, "%s OUT", __func__);
+    return OC_STACK_OK;
+}
diff --git a/service/coap-http-proxy/src/CoapHttpMap.c b/service/coap-http-proxy/src/CoapHttpMap.c
new file mode 100644 (file)
index 0000000..82252a7
--- /dev/null
@@ -0,0 +1,520 @@
+/* ****************************************************************
+ *
+ * Copyright 2016 Samsung Electronics 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.
+ *
+ ******************************************************************/
+
+#include "CoapHttpMap.h"
+#include <string.h>
+#include "oic_malloc.h"
+#include "oic_string.h"
+#include "logger.h"
+#include "ocstack.h"
+#include "pdu.h"
+#include "ocpayload.h"
+
+#define TAG "CHPMap"
+
+int CHPGetOptionID(const char *httpOptionName)
+{
+    if (!httpOptionName)
+    {
+        OIC_LOG(ERROR, TAG, "HTTP option name is NULL");
+        return 0;
+    }
+
+    OICStringToLower((char *)httpOptionName);
+    if (0 == strcmp(httpOptionName, HTTP_OPTION_CACHE_CONTROL) ||
+        0 == strcmp(httpOptionName, HTTP_OPTION_EXPIRES))
+    {
+        return COAP_OPTION_MAXAGE;
+    }
+    else if (0 == strcmp(httpOptionName, HTTP_OPTION_IF_MATCH))
+    {
+        return COAP_OPTION_IF_MATCH;
+    }
+    else if (0 == strcmp(httpOptionName, HTTP_OPTION_IF_NONE_MATCH))
+    {
+        return COAP_OPTION_IF_NONE_MATCH;
+    }
+    else if (0 == strcmp(httpOptionName, HTTP_OPTION_ETAG))
+    {
+        return COAP_OPTION_ETAG;
+    }
+    else
+    {
+        OIC_LOG_V(ERROR, TAG, "No Mapping found for %s", httpOptionName);
+    }
+
+    return 0;
+}
+
+OCStackResult CHPGetOCCode(const HttpResponseResult_t httpCode, const OCMethod method,
+                            OCEntityHandlerResult *ocfCode)
+{
+    OIC_LOG_V(DEBUG, TAG, "%s IN", __func__);
+    OIC_LOG_V(DEBUG, TAG, "Http Code is %d", httpCode);
+
+    switch (httpCode)
+    {
+        case CHP_SUCCESS:
+            if (OC_REST_GET == method)
+            {
+                *ocfCode = OC_EH_CONTENT;
+            }
+            else if (OC_REST_DELETE == method)
+            {
+                *ocfCode = OC_EH_RESOURCE_DELETED;
+            }
+            else
+            {
+                *ocfCode = OC_EH_CHANGED;
+            }
+            break;
+        case CHP_NO_CONTENT:
+            if (OC_REST_DELETE == method)
+            {
+                *ocfCode = OC_EH_RESOURCE_DELETED;
+            }
+            else
+            {
+                *ocfCode = OC_EH_CHANGED;
+            }
+            break;
+        case CHP_CREATED:
+            *ocfCode = OC_EH_RESOURCE_CREATED;
+            break;
+        case CHP_NOT_MODIFIED:
+            *ocfCode = OC_EH_VALID;
+            break;
+        case CHP_BAD_REQ:
+        case CHP_REQUEST_URI_TOO_LARGE:
+            *ocfCode = OC_EH_BAD_REQ;
+            break;
+        case CHP_BAD_GATEWAY:
+        case CHP_VERSION_NOT_SUPPORTED:
+            *ocfCode = OC_EH_BAD_GATEWAY;
+            break;
+        case CHP_UNAUTHORIZED_REQ:
+        case CHP_FORBIDDEN_REQ:
+        case CHP_NOT_FOUND:
+        case CHP_NOT_ACCEPTABLE:
+        case CHP_REQUEST_ENTITY_TOO_LARGE:
+        case CHP_UNSUPPORTED_MEDIA_TYPE:
+        case CHP_INTERNAL_SERVER_ERROR:
+        case CHP_NOT_IMPLEMENTED:
+        case CHP_SERVICE_UNAVAILABLE:
+        case CHP_GATEWAY_TIMEOUT:
+            *ocfCode = httpCode;
+            break;
+        default:
+            OIC_LOG_V(ERROR, TAG, "HTTP Response code[%d] is not matching the OCF Response code",
+                      httpCode);
+            return OC_STACK_ERROR;
+    }
+
+    OIC_LOG_V(DEBUG, TAG, "%s OUT", __func__);
+    return OC_STACK_OK;
+}
+
+OCStackResult CHPGetOCOption(const HttpHeaderOption_t *httpOption, OCHeaderOption *ocfOption)
+{
+    OIC_LOG(DEBUG, TAG, "CHPGetCoAPOption IN");
+    if (!httpOption)
+    {
+        OIC_LOG(ERROR, TAG, "HTTP option is Null");
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    ocfOption->optionID = CHPGetOptionID(httpOption->optionName);
+    if (!ocfOption->optionID)
+    {
+        OIC_LOG(INFO, TAG, "No match for HTTP option found");
+        return OC_STACK_INVALID_OPTION;
+    }
+
+    ocfOption->protocolID = OC_COAP_ID;
+    ocfOption->optionLength = httpOption->optionLength < sizeof(ocfOption->optionData) ?
+                                httpOption->optionLength : sizeof(ocfOption->optionData);
+    memcpy(ocfOption->optionData,  httpOption->optionData, ocfOption->optionLength);
+
+    OIC_LOG(DEBUG, TAG, "CHPGetCoAPOption OUT");
+    return OC_STACK_OK;
+}
+
+OCPayloadFormat CHPGetOCContentType(const char *httpContentType)
+{
+    OIC_LOG_V(DEBUG, TAG, "%s IN", __func__);
+
+    OICStringToLower((char *)httpContentType);
+    if (strstr(httpContentType, CBOR_CONTENT_TYPE))
+    {
+        return OC_FORMAT_CBOR;
+    }
+    else if (strstr(httpContentType, JSON_CONTENT_TYPE))
+    {
+        return OC_FORMAT_JSON;
+    }
+
+    OIC_LOG_V(DEBUG, TAG, "%s OUT", __func__);
+    return OC_FORMAT_UNSUPPORTED;
+}
+
+OCStackResult CHPGetHttpMethod(const OCMethod method, HttpMethod_t *httpMethod)
+{
+    OIC_LOG_V(DEBUG, TAG, "%s IN", __func__);
+
+    switch (method)
+    {
+        case OC_REST_GET:
+            *httpMethod = CHP_GET;
+            break;
+        case OC_REST_PUT:
+            *httpMethod = CHP_PUT;
+            break;
+        case OC_REST_POST:
+            *httpMethod = CHP_POST;
+            break;
+        case OC_REST_DELETE:
+            *httpMethod = CHP_DELETE;
+            break;
+        default:
+            *httpMethod = CHP_INVALID;
+            OIC_LOG_V(ERROR, TAG, "Unknown method type %d", method);
+            return OC_STACK_INVALID_METHOD;
+    }
+
+    OIC_LOG_V(DEBUG, TAG, "%s OUT", __func__);
+    return OC_STACK_OK;
+}
+
+OCStackResult CHPGetHttpOption(const OCHeaderOption* option, HttpHeaderOption_t** httpOption)
+{
+    OIC_LOG_V(DEBUG, TAG, "%s IN", __func__);
+    if (!option)
+    {
+        OIC_LOG(ERROR, TAG, "option is NULL");
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    *httpOption = (HttpHeaderOption_t *)OICCalloc(1, sizeof(HttpHeaderOption_t));
+    if (NULL == *httpOption)
+    {
+        OIC_LOG(ERROR, TAG, "Memory allocation failed");
+        return OC_STACK_NO_MEMORY;
+    }
+
+    switch (option->optionID)
+    {
+        case COAP_OPTION_ACCEPT:
+            OICStrcpy((*httpOption)->optionName, sizeof((*httpOption)->optionName),
+                      HTTP_OPTION_ACCEPT);
+            break;
+        case COAP_OPTION_IF_MATCH:
+            OICStrcpy((*httpOption)->optionName, sizeof((*httpOption)->optionName),
+                      HTTP_OPTION_IF_MATCH);
+            break;
+        case COAP_OPTION_IF_NONE_MATCH:
+            OICStrcpy((*httpOption)->optionName, sizeof((*httpOption)->optionName),
+                      HTTP_OPTION_IF_NONE_MATCH);
+            break;
+        case COAP_OPTION_ETAG:
+            OICStrcpy((*httpOption)->optionName, sizeof((*httpOption)->optionName),
+                      HTTP_OPTION_ETAG);
+            break;
+        case COAP_OPTION_CONTENT_TYPE:
+            OICStrcpy((*httpOption)->optionName, sizeof((*httpOption)->optionName),
+                      HTTP_OPTION_CONTENT_TYPE);
+            break;
+        default:
+            OIC_LOG_V(INFO, TAG, "No Matching found for the ID %d", option->optionID);
+    }
+
+    if ('\0' == (*httpOption)->optionName[0])
+    {
+        OIC_LOG(ERROR, TAG, "No matching is found");
+        OICFree(*httpOption);
+        return OC_STACK_INVALID_OPTION;
+    }
+
+    (*httpOption)->optionLength = option->optionLength < sizeof((*httpOption)->optionData) ?
+                                      option->optionLength : sizeof((*httpOption)->optionData);
+    memcpy((*httpOption)->optionData, option->optionData, (*httpOption)->optionLength);
+
+    OIC_LOG_V(DEBUG, TAG, "%s OUT", __func__);
+    return OC_STACK_OK;
+}
+
+void CHPJsonToRepPayload(cJSON* rootJSon, OCRepPayload* payload)
+{
+    cJSON* dataJson = rootJSon->child;
+    while (dataJson)
+    {
+        switch (dataJson->type)
+        {
+            case cJSON_String:
+                OCRepPayloadSetPropString(payload, dataJson->string, dataJson->valuestring);
+                break;
+            case cJSON_Number:
+                if (dataJson->valueint == dataJson->valuedouble)
+                {
+                    OCRepPayloadSetPropInt(payload, dataJson->string, dataJson->valueint);
+                }
+                else
+                {
+                    OCRepPayloadSetPropDouble(payload, dataJson->string, dataJson->valuedouble);
+                }
+                break;
+            case cJSON_False:
+                OCRepPayloadSetPropBool(payload, dataJson->string, false);
+                break;
+            case cJSON_True:
+                OCRepPayloadSetPropBool(payload, dataJson->string, true);
+                break;
+            case cJSON_Object:
+            {
+                OCRepPayload* childPayload = OCRepPayloadCreate();
+                CHPJsonToRepPayload(dataJson,childPayload);
+                OCRepPayloadSetPropObject(payload, dataJson->string,childPayload );
+                break;
+            }
+            case cJSON_Array:
+            {
+                int size = cJSON_GetArraySize(dataJson);
+                size_t dimensions[MAX_REP_ARRAY_DEPTH];
+                dimensions[0] = size;
+                dimensions[1] = dimensions[2] = 0;
+
+                int i = 0;
+                int type = cJSON_IsReference;
+                int numType = 0;    // int:1, double:2
+                const int intType = 1;
+                const int doubleType = 2;
+
+                int64_t intArray[size];
+                double doubleArray[size];
+                char* strArray[size];
+                OCRepPayload* objPayloadArray[size];
+
+                for (; i < size ; ++i)
+                {
+                    cJSON* subitem = cJSON_GetArrayItem(dataJson, i);
+                    if (subitem == NULL)
+                    {
+                        continue;
+                    }
+
+                    if ((type != cJSON_IsReference) && (type != subitem->type))
+                    {
+                        continue;
+                    }
+                    else
+                    {
+                        type = subitem->type;
+                        switch (type)
+                        {
+                            case cJSON_Number:
+                                if (subitem->valueint == subitem->valuedouble)
+                                {
+                                    numType = intType;
+                                    intArray[i] = (int64_t) subitem->valueint;
+                                }
+                                else
+                                {
+                                    numType = doubleType;
+                                    doubleArray[i] = subitem->valuedouble;
+                                }
+                                break;
+                            case cJSON_String:
+                                strArray[i] = subitem->valuestring;
+                                break;
+                            case cJSON_Object:
+                                objPayloadArray[i] = OCRepPayloadCreate();
+                                CHPJsonToRepPayload(subitem,objPayloadArray[i]);
+                                break;
+                            default:
+                                OIC_LOG(ERROR, TAG, "wrong ArrayType in JsonToRepPayload()");
+                                break;
+                        }
+                    }
+                }
+
+                switch (type)
+                {
+                    case cJSON_Number:
+                    if (numType == intType)
+                    {
+                        OCRepPayloadSetIntArray(payload, dataJson->string,(const int64_t*)intArray,
+                                                dimensions);
+                    }
+                    else if (numType == doubleType)
+                    {
+                        OCRepPayloadSetDoubleArray(payload, dataJson->string,
+                                                   (const double*)doubleArray,
+                                                   dimensions);
+                    }
+                    break;
+                    case cJSON_String:
+                        OCRepPayloadSetStringArray(payload, dataJson->string,
+                                                   (const char**)strArray,
+                                                   dimensions);
+                    break;
+                    case cJSON_Object:
+                        OCRepPayloadSetPropObjectArray(payload, dataJson->string,
+                                                       (const OCRepPayload**)objPayloadArray,
+                                                       dimensions);
+                        break;
+                  default:
+                        OIC_LOG(ERROR, TAG, "wrong ArrayType in JsonToRepPayload()");
+                        break;
+                }
+                break;
+            }
+        }
+        dataJson = dataJson->next;
+    }
+}
+
+cJSON* CHPRepPayloadToJson(OCRepPayload* repData)
+{
+    cJSON *outJson = cJSON_CreateObject();
+    if (outJson == NULL)
+    {
+        return NULL;
+    }
+
+    OCRepPayloadValue* val = repData->values;
+    while (val)
+    {
+        switch (val->type)
+        {
+            case OCREP_PROP_NULL:
+                break;
+            case OCREP_PROP_INT:
+                OIC_LOG_V(DEBUG, TAG, "%s(int):%d", val->name, (int)val->i);
+                cJSON_AddNumberToObject(outJson,val->name,(int)val->i);
+                break;
+            case OCREP_PROP_DOUBLE:
+                OIC_LOG_V(DEBUG, TAG, "%s(double):%f", val->name, val->d);
+                cJSON_AddNumberToObject(outJson,val->name,val->d);
+                break;
+            case OCREP_PROP_BOOL:
+                OIC_LOG_V(DEBUG, TAG, "%s(bool):%s", val->name, val->b ? "true" : "false");
+                cJSON_AddBoolToObject(outJson,val->name,val->b);
+                break;
+            case OCREP_PROP_STRING:
+                OIC_LOG_V(DEBUG, TAG, "%s(string):%s", val->name, val->str);
+                cJSON_AddStringToObject(outJson,val->name,val->str);
+                break;
+            case OCREP_PROP_OBJECT:
+            {
+                cJSON *objJson = CHPRepPayloadToJson(val->obj);
+                if (objJson != NULL)
+                {
+                    cJSON_AddItemToObject(outJson,val->name,objJson);
+                }
+                break;
+            }
+            case OCREP_PROP_ARRAY:
+            {
+                unsigned int i = 0;
+                int arraySize = (int)val->arr.dimensions[0];
+                switch (val->arr.type)
+                {
+                    case OCREP_PROP_INT:
+                        OIC_LOG_V(DEBUG, TAG, "%s(int array)", val->name);
+                        if (arraySize > 0)
+                        {
+                            int castVal[val->arr.dimensions[0]];
+                            for (i = 0 ; i < (unsigned int)arraySize ; i++)
+                            {
+                                castVal[i] = (int)val->arr.iArray[i];
+                            }
+                            cJSON *array = cJSON_CreateIntArray(castVal,arraySize);
+                            if (array != NULL)
+                            {
+                                cJSON_AddItemToObject(outJson,val->name,array);
+                            }
+                        }
+                        break;
+                    case OCREP_PROP_DOUBLE:
+                        OIC_LOG_V(DEBUG, TAG, "%s(double array)", val->name);
+                        if (arraySize > 0)
+                        {
+                            cJSON *array = cJSON_CreateDoubleArray(val->arr.dArray,arraySize);
+                            if (array != NULL)
+                            {
+                                cJSON_AddItemToObject(outJson,val->name,array);
+                            }
+                        }
+                        break;
+                    case OCREP_PROP_STRING:
+                        OIC_LOG_V(DEBUG, TAG, "%s(string array)", val->name);
+                        if (arraySize > 0)
+                        {
+                            cJSON *array = cJSON_CreateStringArray((const char**)val->arr.strArray,
+                                                                   arraySize);
+                            if (array != NULL)
+                            {
+                                cJSON_AddItemToObject(outJson,val->name,array);
+                            }
+                        }
+                        break;
+                    case OCREP_PROP_OBJECT:
+                        if (arraySize > 0)
+                        {
+                            cJSON *arrayJson = cJSON_CreateArray();
+                            for (i = 0 ; i < (unsigned int)arraySize ; i++)
+                            {
+                                cJSON *objJson = CHPRepPayloadToJson(val->arr.objArray[i]);
+                                if (objJson != NULL && arrayJson != NULL)
+                                {
+                                    cJSON_AddItemToArray(arrayJson, objJson);
+                                }
+                            }
+                            if (arrayJson != NULL)
+                            {
+                                cJSON_AddItemToObject(outJson,val->name,arrayJson);
+                            }
+                        }
+                        break;
+                    case OCREP_PROP_BOOL:
+                        //TODO : Not support - cJSON_CreateBoolArray
+                        break;
+                    default:
+                        OIC_LOG_V(ERROR, TAG, "Unknown/unsupported array type: %s", val->name);
+                        break;
+                }
+                break;
+            }
+            default:
+                OIC_LOG_V(ERROR, TAG, "Unknown type: %s", val->name);
+                break;
+        }
+        val = val->next;
+    }
+
+    if( repData->values != NULL)
+    {
+        return outJson;
+    }
+    else
+    {
+        cJSON_Delete(outJson);
+        return NULL;
+    }
+}
diff --git a/service/coap-http-proxy/src/CoapHttpParser.c b/service/coap-http-proxy/src/CoapHttpParser.c
new file mode 100644 (file)
index 0000000..c24edff
--- /dev/null
@@ -0,0 +1,869 @@
+/* ****************************************************************
+ *
+ * Copyright 2016 Samsung Electronics 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.
+ *
+ ******************************************************************/
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdint.h>
+
+#include "CoapHttpParser.h"
+#include "oic_malloc.h"
+#include "oic_string.h"
+#include "uarraylist.h"
+#include "logger.h"
+
+#include <string.h>
+#include <curl/curl.h>
+#ifdef HAVE_PTHREAD_H
+#include <pthread.h>
+#endif
+#if !defined(_MSC_VER)
+#include <unistd.h>
+#endif //!defined(_MSC_VER)
+#include <sys/types.h>
+#include <fcntl.h>
+#if !defined(_WIN32)
+#include <sys/select.h>
+#endif //!defined(_WIN32)
+#include <errno.h>
+
+#define TAG "CHP_PARSER"
+
+#define DEFAULT_USER_AGENT "IoTivity"
+#define MAX_PAYLOAD_SIZE (1048576U) // 1 MB
+
+typedef struct
+{
+    void* context;
+    CHPResponseCallback cb;
+    HttpResponse_t resp;
+    /* libcurl will not cache request payload when creating a easy handle hence we need to cache */
+    void* payload;
+    size_t payloadLength;
+    /* To track multiple read_callbacks from curl */
+    size_t readOffset;
+    /* To track multiple write_callbacks from curl */
+    size_t writeOffset;
+    /* libcurl related */
+    CURL* easyHandle;
+    /* libcurl does not copy header options passed to a request */
+    struct curl_slist *list;
+} CHPContext_t;
+
+/* A curl mutihandle is not threadsafe so we require mutexes to add new easy
+ * handles to multihandle.
+ */
+static CURLM *g_multiHandle;
+static int g_activeConnections;
+
+/*  Mutex code is taken from CA.
+ *  General utility functions shall be placed in common location
+ *  so that all modules can use them.
+ */
+static pthread_mutex_t g_multiHandleMutex;
+
+/* Fds used to signal threads to stop */
+static int g_shutdownFds[2];
+
+static bool g_terminateParser;
+
+/*
+ * Fds used to signal fdset to be refreshed.
+ * When a new easy_handle is added to multi_handle,
+ * existing fd_set has to be updated.
+ */
+static int g_refreshFds[2];
+
+/*
+ * Thread handle for curl multi_handle processing.
+ */
+static pthread_t g_multiHandleThread;
+
+static void CHPParserLockMutex();
+static void CHPParserUnlockMutex();
+
+static void CHPParserResetHeaderOptions(u_arraylist_t** headerOptions)
+{
+    VERIFY_NON_NULL_VOID(headerOptions, TAG, "headerOptions is NULL");
+
+    HttpHeaderOption_t *option = NULL;
+    while (NULL != (option = u_arraylist_remove(*headerOptions, 0)))
+    {
+        OICFree(option);
+    }
+    u_arraylist_free(headerOptions);
+}
+
+static void CHPFreeContext(CHPContext_t *ctxt)
+{
+    VERIFY_NON_NULL_VOID(ctxt, TAG, "ctxt is NULL");
+    if(ctxt->list)
+    {
+        curl_slist_free_all(ctxt->list);
+    }
+
+    if(ctxt->easyHandle)
+    {
+        curl_easy_cleanup(ctxt->easyHandle);
+    }
+
+    CHPParserResetHeaderOptions(&(ctxt->resp.headerOptions));
+    OICFree(ctxt->resp.payload);
+    OICFree(ctxt->payload);
+    OICFree(ctxt);
+}
+
+static void *CHPParserExecuteMultiHandle(void* data)
+{
+    OIC_LOG_V(DEBUG, TAG, "%s IN", __func__);
+    UNUSED(data);
+    /*
+     * These fd sets will be fetched from curl multi handle and monitored to execute
+     * curl_multi_perform()
+     */
+    fd_set fdread;
+    fd_set fdwrite;
+    fd_set fdexcep;
+    int maxfd;
+    struct timeval timeout;
+    struct timeval *tv;
+    int activeCon;
+    int activeEasyHandle;
+    bool goForSelect;
+    int retValue;
+
+    /* When active connections exist, curl_multi_perform() shall be called within
+     * curlMultiTimeout seconds regardless of whether select returned successfull or not.
+     */
+    long curlMultiTimeout;
+    while (!g_terminateParser)
+    {
+        // Required everytime before calling curl_multi_fdset()
+        FD_ZERO(&fdread);
+        FD_ZERO(&fdwrite);
+        FD_ZERO(&fdexcep);
+        maxfd = -1;
+        goForSelect = true;
+
+        // Get currently active transfer fds from curl
+        CHPParserLockMutex();
+        curl_multi_fdset(g_multiHandle, &fdread, &fdwrite, &fdexcep, &maxfd);
+        curl_multi_timeout(g_multiHandle, &curlMultiTimeout);
+        activeCon = g_activeConnections;
+        CHPParserUnlockMutex();
+
+        // A 0 represent curl_multi_perform() shall be called.
+        if(curlMultiTimeout < 0)
+        {
+            curlMultiTimeout = 1000;
+        }
+
+        if(maxfd == -1)
+        {
+            /* Nothing to monitor from libcurl.
+             * This mean that no active sockets exist either because
+             * there are no transfer taking place or sockets are not in a
+             * state that could be monitored (connecting, retry etc.)
+             */
+            if(!activeCon)
+            {
+                // wait until something received on shutdown or refresh fd
+                // with no timeout.
+                curlMultiTimeout = -1;
+            }
+            else
+            {
+                // libcurl recommend doing this.
+                usleep(100000);
+                // dont select() and directly call curl_multi_perform()
+                goForSelect = false;
+            }
+        }
+
+        if(goForSelect)
+        {
+            FD_SET(g_shutdownFds[0], &fdread);
+            if (maxfd < g_shutdownFds[0])
+            {
+                maxfd = g_shutdownFds[0];
+            }
+
+            FD_SET(g_refreshFds[0], &fdread);
+            if (maxfd < g_refreshFds[0])
+            {
+                maxfd = g_refreshFds[0];
+            }
+
+            if(curlMultiTimeout == -1)
+            {
+                tv = NULL;
+            }
+            else
+            {
+                timeout.tv_sec = curlMultiTimeout / 1000;
+                timeout.tv_usec = 0;
+                tv = &timeout;
+            }
+
+            // Select here
+            retValue = select(maxfd + 1, &fdread, &fdwrite, &fdexcep, tv);
+            if(retValue == -1)
+            {
+                OIC_LOG_V(ERROR, TAG, "Error in select. %s", strerror(errno));
+                continue;
+            }
+
+            // Some sockets are available for operations, check if shutdown or refresh fds are
+            // among them. In any case, go ahead and call curl_multi_perform()
+            if(retValue)
+            {
+                if (FD_ISSET(g_shutdownFds[0], &fdread))
+                {
+                    OIC_LOG(ERROR, TAG, "Shutdown requested. multi_handle returning");
+                    break;
+                }
+                else if(FD_ISSET(g_refreshFds[0], &fdread))
+                {
+                    char buf[20] = {0};
+                    ssize_t len = read(g_refreshFds[0], buf, sizeof(buf));
+                    UNUSED(len);
+                    // new easy handles added, call multi_perform and refresh fds.
+                    OIC_LOG(ERROR, TAG, "New easy handle added");
+                }
+            }
+        }
+
+        CURLMcode ret;
+        CHPParserLockMutex();
+        do
+        {
+            ret = curl_multi_perform(g_multiHandle, &activeEasyHandle);
+            struct CURLMsg *cmsg;
+            int cmsgq;
+            do
+            {
+                cmsgq = 0;
+                cmsg = curl_multi_info_read(g_multiHandle, &cmsgq);
+                if(cmsg && (cmsg->msg == CURLMSG_DONE))
+                {
+                    CURL *easyHandle = cmsg->easy_handle;
+                    g_activeConnections--;
+                    curl_multi_remove_handle(g_multiHandle, easyHandle);
+
+                    CHPContext_t *ptr;
+                    char *uri = NULL;
+                    char *contentType = NULL;
+                    long responseCode;
+
+                    curl_easy_getinfo(easyHandle, CURLINFO_PRIVATE, &ptr);
+                    curl_easy_getinfo(easyHandle, CURLINFO_EFFECTIVE_URL, &uri);
+                    curl_easy_getinfo(easyHandle, CURLINFO_RESPONSE_CODE, &responseCode);
+                    curl_easy_getinfo(easyHandle, CURLINFO_CONTENT_TYPE, &contentType);
+
+                    ptr->resp.status = responseCode;
+                    OICStrcpy(ptr->resp.dataFormat, sizeof(ptr->resp.dataFormat), contentType);
+                    OIC_LOG_V(DEBUG, TAG, "Transfer completed %d uri: %s, %s", g_activeConnections,
+                                                                           uri, contentType);
+                    ptr->cb(&(ptr->resp), ptr->context);
+                    CHPFreeContext(ptr);
+                }
+            } while(cmsg && !g_terminateParser);
+        }while (ret == CURLM_CALL_MULTI_PERFORM && !g_terminateParser);
+        CHPParserUnlockMutex();
+    }
+
+    if (g_terminateParser)
+    {
+        OIC_LOG_V(DEBUG, TAG, "Shutdown request received.");
+        // g_shutdownFds[1] will be already closed.
+        close(g_shutdownFds[0]);
+        close(g_refreshFds[0]);
+        close(g_refreshFds[1]);
+        g_shutdownFds[0] = -1;
+        g_shutdownFds[1] = -1;
+        g_refreshFds[0] = -1;
+        g_refreshFds[1] = -1;
+    }
+
+    OIC_LOG_V(DEBUG, TAG, "%s IN", __func__);
+    return NULL;
+}
+
+OCStackResult CHPParserInitializePipe(int fds[2])
+{
+    OIC_LOG_V(DEBUG, TAG, "%s IN", __func__);
+    int ret = -1;
+    fds[0] = -1;
+    fds[1] = -1;
+#if defined(HAVE_PIPE2)
+    ret = pipe2(fds, O_CLOEXEC);
+#else
+    ret = pipe(fds);
+    if (-1 != ret)
+    {
+        ret = fcntl(fds[0], F_GETFD);
+        if (-1 != ret)
+        {
+            ret = fcntl(fds[0], F_SETFD, ret|FD_CLOEXEC);
+        }
+        if (-1 != ret)
+        {
+            ret = fcntl(fds[1], F_GETFD);
+        }
+        if (-1 != ret)
+        {
+            ret = fcntl(fds[1], F_SETFD, ret|FD_CLOEXEC);
+        }
+        if (-1 == ret)
+        {
+            close(fds[1]);
+            close(fds[0]);
+            fds[0] = -1;
+            fds[1] = -1;
+        }
+    }
+#endif
+    if (-1 == ret)
+    {
+        OIC_LOG_V(ERROR, TAG, "FD initialization failed: %s", strerror(errno));
+        return OC_STACK_ERROR;
+    }
+    OIC_LOG_V(DEBUG, TAG, "%s OUT", __func__);
+    return OC_STACK_OK;
+}
+
+static OCStackResult CHPParserInitializeMutex()
+{
+    // create the mutex with the attributes set
+    int ret = pthread_mutex_init(&g_multiHandleMutex, PTHREAD_MUTEX_DEFAULT);
+    if (0 != ret)
+    {
+        OIC_LOG_V(ERROR, TAG, "%s Failed to initialize mutex !", __func__);
+        return OC_STACK_ERROR;
+    }
+    return OC_STACK_OK;
+}
+
+static OCStackResult CHPParserTerminateMutex()
+{
+    int ret = pthread_mutex_destroy(&g_multiHandleMutex);
+    if (0 != ret)
+    {
+        OIC_LOG_V(ERROR, TAG, "%s Failed to free mutex !", __func__);
+        return OC_STACK_ERROR;
+    }
+    return OC_STACK_OK;
+}
+
+static void CHPParserLockMutex()
+{
+    int ret = pthread_mutex_lock(&g_multiHandleMutex);
+    if(ret != 0)
+    {
+        OIC_LOG_V(ERROR, TAG, "Pthread Mutex lock failed: %d", ret);
+    }
+}
+
+static void CHPParserUnlockMutex()
+{
+    int ret = pthread_mutex_unlock(&g_multiHandleMutex);
+    if(ret != 0)
+    {
+        OIC_LOG_V(ERROR, TAG, "Pthread Mutex unlock failed: %d", ret);
+    }
+}
+
+static OCStackResult CHPParserInitializeMultiHandle()
+{
+    CHPParserLockMutex();
+    if(g_multiHandle)
+    {
+        OIC_LOG(ERROR, TAG, "Multi handle already initialized.");
+        CHPParserUnlockMutex();
+        return OC_STACK_OK;
+    }
+
+    g_multiHandle = curl_multi_init();
+    if(!g_multiHandle)
+    {
+        OIC_LOG(ERROR, TAG, "Failed to create multi handle.");
+        CHPParserUnlockMutex();
+        return OC_STACK_ERROR;
+    }
+
+    CHPParserUnlockMutex();
+    return OC_STACK_OK;
+}
+
+static OCStackResult CHPParserTerminateMultiHandle()
+{
+    CHPParserLockMutex();
+    if(!g_multiHandle)
+    {
+        OIC_LOG(ERROR, TAG, "Multi handle not initialized.");
+        CHPParserUnlockMutex();
+        return OC_STACK_OK;
+    }
+
+    curl_multi_cleanup(g_multiHandle);
+    g_multiHandle = NULL;
+    CHPParserUnlockMutex();
+    return OC_STACK_OK;
+}
+
+OCStackResult CHPParserInitialize()
+{
+    OIC_LOG_V(DEBUG, TAG, "%s IN", __func__);
+
+    OCStackResult ret = CHPParserInitializeMutex();
+    if(ret != OC_STACK_OK)
+    {
+        return ret;
+    }
+
+    ret = CHPParserInitializeMultiHandle();
+    if(ret != OC_STACK_OK)
+    {
+        OIC_LOG_V(ERROR, TAG, "Failed to intialize multi handle: %d", ret);
+        CHPParserTerminate();
+        return ret;
+    }
+
+    ret = CHPParserInitializePipe(g_shutdownFds);
+    if(ret != OC_STACK_OK)
+    {
+        OIC_LOG_V(ERROR, TAG, "Failed to intialize shutdown fds: %d", ret);
+        CHPParserTerminate();
+        return ret;
+    }
+
+    ret = CHPParserInitializePipe(g_refreshFds);
+    if(ret != OC_STACK_OK)
+    {
+        OIC_LOG_V(ERROR, TAG, "Failed to intialize refresh fds: %d", ret);
+        CHPParserTerminate();
+        return ret;
+    }
+
+    // Launch multi_handle processor thread
+    int result = pthread_create(&g_multiHandleThread, NULL, CHPParserExecuteMultiHandle, NULL);
+    if(result != 0)
+    {
+        OIC_LOG_V(ERROR, TAG, "Thread start failed with error %d", result);
+        CHPParserTerminate();
+        return OC_STACK_ERROR;
+    }
+
+    g_terminateParser = false;
+    CHPParserLockMutex();
+    g_activeConnections = 0;
+    CHPParserUnlockMutex();
+    OIC_LOG_V(DEBUG, TAG, "%s OUT", __func__);
+    return OC_STACK_OK;
+}
+
+OCStackResult CHPParserTerminate()
+{
+    OIC_LOG_V(DEBUG, TAG, "%s IN", __func__);
+    g_terminateParser = true;
+    if (g_shutdownFds[1] != -1)
+    {
+        // Signal multi_handle thread to come out
+        close(g_shutdownFds[1]);
+    }
+    pthread_join(g_multiHandleThread, NULL);
+
+    OCStackResult ret = CHPParserTerminateMultiHandle();
+    if(ret != OC_STACK_OK)
+    {
+        OIC_LOG_V(ERROR, TAG, "Multi handle termination failed: %d", ret);
+    }
+
+    CHPParserLockMutex();
+    g_activeConnections = 0;
+    CHPParserUnlockMutex();
+
+    ret = CHPParserTerminateMutex();
+    if(ret != OC_STACK_OK)
+    {
+        OIC_LOG_V(ERROR, TAG, "mutex termination failed: %d", ret);
+    }
+    OIC_LOG_V(DEBUG, TAG, "%s OUT", __func__);
+    return OC_STACK_OK;
+}
+
+static size_t CHPEasyHandleWriteCb(char *buffer, size_t size, size_t num, void *context)
+{
+    size_t dataToWrite = size * num;
+    if(!dataToWrite)
+    {
+        // Empty payload received. Ignore.
+        return 0;
+    }
+
+    if(!context || !buffer || g_terminateParser)
+    {
+        OIC_LOG_V(ERROR, TAG, "%s invalid arguments or terminating", __func__);
+        return 0;
+    }
+
+    CHPContext_t* ctx = context;
+    HttpResponse_t *resp = &(ctx->resp);
+
+    if(ctx->writeOffset + dataToWrite > MAX_PAYLOAD_SIZE)
+    {
+        OIC_LOG_V(ERROR, TAG, "%s Payload limit exceeded", __func__);
+        resp->payloadLength = 0;
+        ctx->writeOffset = 0;
+        OICFree(resp->payload);
+        resp->payload = NULL;
+        return 0;
+    }
+
+    if (!resp->payload)
+    {
+        resp->payload = OICMalloc(dataToWrite);
+        if (!resp->payload)
+        {
+            OIC_LOG_V(ERROR, TAG, "%s Out of memory!", __func__);
+            return 0;
+        }
+    }
+    else
+    {
+        // Realloc buffer
+        void *newPayload = OICRealloc(resp->payload, ctx->writeOffset + dataToWrite);
+        if (!newPayload)
+        {
+            OIC_LOG_V(ERROR, TAG, "Realloc failed! Current: %u Extra: %u", ctx->writeOffset,
+                                                                           dataToWrite);
+            resp->payloadLength = 0;
+            ctx->writeOffset = 0;
+            OICFree(resp->payload);
+            resp->payload = NULL;
+            return 0;
+        }
+        resp->payload = newPayload;
+    }
+
+    memcpy(resp->payload + ctx->writeOffset, buffer, dataToWrite);
+    ctx->writeOffset += dataToWrite;
+    resp->payloadLength = ctx->writeOffset;
+
+    OIC_LOG_V(DEBUG, TAG, "%s OUT %u : %u", __func__, resp->payloadLength, dataToWrite);
+    return dataToWrite;
+}
+
+static size_t CHPEasyHandleReadCb(char *buffer, size_t size, size_t num, void *context)
+{
+    if(!context || !buffer || g_terminateParser)
+    {
+        OIC_LOG_V(ERROR, TAG, "%s invalid arguments or terminating", __func__);
+        return CURL_READFUNC_ABORT;
+    }
+
+    CHPContext_t *ctx = context;
+    size_t remainingLen = ctx->payloadLength - ctx->readOffset;
+    size_t toTransfer = size * num > remainingLen ? remainingLen : size * num;
+    memcpy(buffer, ctx->payload + ctx->readOffset, toTransfer);
+    ctx->readOffset += toTransfer;
+    return toTransfer;
+}
+
+static size_t CHPEasyHandleHeaderCb(char *buffer, size_t size, size_t num, void *context)
+{
+    size_t dataToWrite = size * num;
+    if(!buffer || !dataToWrite || !context || g_terminateParser)
+    {
+        OIC_LOG_V(ERROR, TAG, "%s invalid arguments or terminating", __func__);
+        return 0;
+    }
+
+    /* curl will call this function for each line in response header including status line
+     * and for each http response that it might have received from http server for ex: redirect,
+     * proxy handshakes etc. All these intermediary responses are not useful for us but there
+     * isn't any mechanism to track which one is going to be final.
+     * Hence here we process each response and assume that the relevant one will be the final
+     * response.
+     */
+
+    /* Start of a response is tracked by presence of status line starting with "HTTP/"
+     * This also acts as a reset for everything else (payload, header options) as we are processing
+     * a new response.
+     */
+
+    CHPContext_t *ctx = context;
+    HttpResponse_t *resp = &(ctx->resp);
+    if (dataToWrite > 5)
+    {
+        if (strncmp("HTTP/", buffer, 5) == 0)
+        {
+            OIC_LOG(ERROR, TAG, "New header received");
+            resp->payloadLength = 0;
+            ctx->writeOffset = 0;
+            OICFree(resp->payload);
+            resp->payload = NULL;
+            CHPParserResetHeaderOptions(&(resp->headerOptions));
+            // This is a status line. We are only interested in header options.
+            return dataToWrite;
+        }
+    }
+
+
+    // A header line can have CR LF NULL and spaces at end. Make endOfHeader point to last
+    // character in header value
+    char* endOfHeader = buffer + dataToWrite;
+    while ((endOfHeader > buffer) && (*endOfHeader == '\r' || *endOfHeader == '\n'
+                || *endOfHeader == ' ' || *endOfHeader == '\0'))
+    {
+        endOfHeader--;
+    }
+
+    /* curl might not send the buffer NULL terminated and copying each header is too much overhead
+     * hence use mem family of function to search */
+    char* ptr = (char*) memchr(buffer, ':', dataToWrite);
+    // There is a colon and its not the first character
+    if(ptr && ptr != buffer && ptr <= endOfHeader)
+    {
+        size_t headerFieldLen = ptr - buffer;
+        size_t headerValueLen;
+        char* headerValuePtr;
+
+        /* Skip any white spaces */
+        ptr++;
+        while(ptr <= endOfHeader && *ptr == ' ')
+        {
+            ptr++;
+        }
+
+        if(ptr > endOfHeader)
+        {
+            headerValueLen = 0;
+            headerValuePtr = NULL;
+        }
+        else
+        {
+            // endOfHeader is pointing to last header value character hence +1
+            headerValueLen = endOfHeader - ptr + 1;
+            headerValuePtr = ptr;
+        }
+
+        if (!(resp->headerOptions))
+        {
+            // First header callback, assign storage for header options
+            resp->headerOptions = u_arraylist_create();
+            if (!(resp->headerOptions))
+            {
+                OIC_LOG(ERROR, TAG, "Memory failed!");
+                return 0;
+            }
+        }
+
+        HttpHeaderOption_t *option = OICCalloc(1, sizeof(HttpHeaderOption_t));
+        if (!option)
+        {
+            OIC_LOG(ERROR, TAG, "Memory failed!");
+            return 0;
+        }
+
+        headerFieldLen = headerFieldLen > (sizeof(option->optionName) - 1) ?
+                             (sizeof(option->optionName) - 1): headerFieldLen;
+        memcpy(option->optionName, buffer, headerFieldLen);
+        option->optionName[headerFieldLen] = '\0';
+
+        if(headerValueLen)
+        {
+            headerValueLen = headerValueLen > (sizeof(option->optionData) - 1) ?
+                              (sizeof(option->optionData) - 1): headerValueLen;
+            memcpy(option->optionData, headerValuePtr, headerValueLen);
+            option->optionData[headerValueLen] = '\0';
+        }
+
+        OIC_LOG_V(DEBUG, TAG, "%s:: %s: %s", __func__, option->optionName, option->optionData);
+        // Add to header option list
+        if(!u_arraylist_add(resp->headerOptions, option))
+        {
+            OIC_LOG(ERROR, TAG, "u_arraylist_add failed!");
+            OICFree(option);
+            return 0;
+        }
+    }
+
+    // ignore else as this might be CRLF header lines.
+    return dataToWrite;
+}
+
+static OCStackResult CHPInitializeEasyHandle(CURL** easyHandle, HttpRequest_t *req,
+                                             CHPContext_t* handleContext)
+{
+    OIC_LOG_V(DEBUG, TAG, "%s IN", __func__);
+    VERIFY_NON_NULL_RET(req, TAG, "req", OC_STACK_INVALID_PARAM);
+    VERIFY_NON_NULL_RET(easyHandle, TAG, "easyHandle", OC_STACK_INVALID_PARAM);
+    VERIFY_NON_NULL_RET(handleContext, TAG, "handleContext", OC_STACK_INVALID_PARAM);
+
+    CURL *e = curl_easy_init();
+    if(!e)
+    {
+        OIC_LOG(ERROR, TAG, "easy init failed!");
+        return OC_STACK_ERROR;
+    }
+
+    /* Set http resource uri */
+    curl_easy_setopt(e, CURLOPT_URL, req->resourceUri);
+    /* Default protocol when scheme is not available in uri */
+    // curl version 7.22 don't support this option.
+    //curl_easy_setopt(e, CURLOPT_DEFAULT_PROTOCOL, "http");
+    /* Set handle context */
+    curl_easy_setopt(e, CURLOPT_PRIVATE, handleContext);
+    curl_easy_setopt(e, CURLOPT_WRITEFUNCTION, CHPEasyHandleWriteCb);
+    curl_easy_setopt(e, CURLOPT_WRITEDATA, handleContext);
+    curl_easy_setopt(e, CURLOPT_READFUNCTION, CHPEasyHandleReadCb);
+    curl_easy_setopt(e, CURLOPT_READDATA, handleContext);
+    curl_easy_setopt(e, CURLOPT_HEADERFUNCTION, CHPEasyHandleHeaderCb);
+    curl_easy_setopt(e, CURLOPT_HEADERDATA, handleContext);
+
+    /* Allow access to only http server's */
+    curl_easy_setopt(e, CURLOPT_PROTOCOLS,
+                     CURLPROTO_HTTP | CURLPROTO_HTTPS);
+    /* complete connection within 15 seconds */
+    curl_easy_setopt(e, CURLOPT_CONNECTTIMEOUT, 15L);
+    /* Abort transaction if getting less than 1kbps for 60 seconds */
+    curl_easy_setopt(e, CURLOPT_LOW_SPEED_LIMIT, 1024L);
+    curl_easy_setopt(e, CURLOPT_LOW_SPEED_TIME, 60L);
+    curl_easy_setopt(e, CURLOPT_USERAGENT, DEFAULT_USER_AGENT);
+    /* Close connection once done with transaction */
+    curl_easy_setopt(e, CURLOPT_FORBID_REUSE, 1L);
+    /* Allow redirect */
+    curl_easy_setopt(e, CURLOPT_FOLLOWLOCATION, 1L);
+    /* Only redirect to http servers */
+    curl_easy_setopt(e, CURLOPT_REDIR_PROTOCOLS,
+                     CURLPROTO_HTTP | CURLPROTO_HTTPS);
+    /* Limit maximum redirects */
+    curl_easy_setopt(e, CURLOPT_MAXREDIRS, 10L);
+
+    handleContext->writeOffset = 0;
+    handleContext->readOffset = 0;
+    switch(req->method)
+    {
+        case CHP_GET:
+            OIC_LOG(DEBUG, TAG, "Sending GET request");
+            curl_easy_setopt(e, CURLOPT_HTTPGET, 1);
+            break;
+        case CHP_POST:
+            OIC_LOG(DEBUG, TAG, "Sending POST request");
+            curl_easy_setopt(e, CURLOPT_POST, 1);
+            curl_easy_setopt(e, CURLOPT_POSTFIELDS, NULL);
+            curl_easy_setopt(e, CURLOPT_POSTFIELDSIZE, req->payloadLength);
+            handleContext->payloadLength = req->payloadLength;
+            handleContext->payload = req->payload;
+            req->payloadCached = true;
+            break;
+        case CHP_PUT:
+            OIC_LOG(DEBUG, TAG, "Sending PUT request");
+            curl_easy_setopt(e, CURLOPT_UPLOAD, 1);
+            curl_easy_setopt(e, CURLOPT_INFILESIZE, req->payloadLength);
+            handleContext->payloadLength = req->payloadLength;
+            handleContext->payload = req->payload;
+            req->payloadCached = true;
+            break;;
+        case CHP_DELETE:
+            OIC_LOG(DEBUG, TAG, "Sending DELETE request");
+            /* libcurl don't have direct option for sending DELETE */
+            curl_easy_setopt(e, CURLOPT_CUSTOMREQUEST, "DELETE");
+            break;
+        default:
+            return OC_STACK_INVALID_METHOD;
+    }
+
+    // Add header options from request
+    struct curl_slist *list = NULL;
+    char buffer[CHP_MAX_HF_NAME_LENGTH + CHP_MAX_HF_DATA_LENGTH + 2]; // extra 2 bytes for ": "
+
+    if (req->headerOptions)
+    {
+        HttpHeaderOption_t *option = NULL;
+        int headerCount = u_arraylist_length(req->headerOptions);
+        for(int i = 0; i < headerCount; i++)
+        {
+            option = u_arraylist_get(req->headerOptions, i);
+            if(option)
+            {
+                OIC_LOG_V(DEBUG, TAG, "Adding header option: %s", buffer);
+                snprintf(buffer, sizeof(buffer), "%s: %s", option->optionName, option->optionData);
+                list = curl_slist_append(list, buffer);
+            }
+        }
+    }
+
+    /* Add content-type and accept header */
+    snprintf(buffer, sizeof(buffer), "Accept: %s", req->acceptFormat);
+    list = curl_slist_append(list, buffer);
+    snprintf(buffer, sizeof(buffer), "Content-Type: %s", req->payloadFormat);
+    curl_easy_setopt(e, CURLOPT_HTTPHEADER, list);
+
+    *easyHandle = e;
+    OIC_LOG_V(DEBUG, TAG, "%s OUT", __func__);
+    return OC_STACK_OK;
+}
+
+OCStackResult CHPPostHttpRequest(HttpRequest_t *req, CHPResponseCallback httpcb,
+                                 void *context)
+{
+    OIC_LOG_V(DEBUG, TAG, "%s IN", __func__);
+    VERIFY_NON_NULL_RET(req, TAG, "req", OC_STACK_INVALID_PARAM);
+    VERIFY_NON_NULL_RET(httpcb, TAG, "httpcb", OC_STACK_INVALID_PARAM);
+
+    CHPContext_t *ctxt = OICCalloc(1, sizeof(CHPContext_t));
+    if (!ctxt)
+    {
+        OIC_LOG(ERROR, TAG, "Memory failed!");
+        return OC_STACK_NO_MEMORY;
+    }
+
+    ctxt->cb = httpcb;
+    ctxt->context = context;
+    OCStackResult ret = CHPInitializeEasyHandle(&ctxt->easyHandle, req, ctxt);
+    if(ret != OC_STACK_OK)
+    {
+        OIC_LOG_V(ERROR, TAG, "Failed to initialize easy handle [%d]", ret);
+        OICFree(ctxt);
+        return ret;
+    }
+
+    // Add easy_handle to multi_handle
+    CHPParserLockMutex();
+    curl_multi_add_handle(g_multiHandle, ctxt->easyHandle);
+    g_activeConnections++;
+    CHPParserUnlockMutex();
+    // Notify refreshfd
+    ssize_t len = 0;
+    do
+    {
+        len = write(g_refreshFds[1], "w", 1);
+    } while ((len == -1) && (errno == EINTR));
+
+    if ((len == -1) && (errno != EINTR) && (errno != EPIPE))
+    {
+        OIC_LOG_V(DEBUG, TAG, "refresh failed: %s", strerror(errno));
+    }
+
+    OIC_LOG_V(DEBUG, TAG, "%s OUT", __func__);
+    return OC_STACK_OK;
+}
+
index 77f4a1e..41a73fa 100644 (file)
@@ -90,18 +90,26 @@ if target_os in ['android','linux']:
                env.get('SRC_DIR') + '/resource/c_common/oic_malloc/include',
                env.get('SRC_DIR') + '/resource/include',
                env.get('SRC_DIR') + '/resource/csdk/logger/include',
-               env.get('SRC_DIR') + '/resource/csdk/stack/include',
-               env.get('SRC_DIR') + '/resource/csdk/logger/include',
+               env.get('SRC_DIR') + '/resource/csdk/stack/include',
+               env.get('SRC_DIR') + '/resource/csdk/logger/include',
                env.get('SRC_DIR') + '/resource/csdk/security/include',
                env.get('SRC_DIR') + '/extlibs/cjson',
                env.get('SRC_DIR') + '/extlibs/sqlite3',
                env.get('SRC_DIR') + '/service/easy-setup/inc',
                'inc'])
        if env.get('SECURED') == '1':
+               with_upstream_libcoap = easy_setup_env.get('WITH_UPSTREAM_LIBCOAP')
+               if with_upstream_libcoap == '1':
+                       # For bring up purposes only, we manually copy the forked version to where the unforked version is downloaded.
+                       easy_setup_env.AppendUnique(CPPPATH = ['#extlibs/libcoap/libcoap/include'])
+               else:
+                       # For bring up purposes only, the forked version will live here.
+                       easy_setup_env.AppendUnique(CPPPATH = [env.get('SRC_DIR') + '/resource/csdk/connectivity/lib/libcoap-4.1.1/include'])
                easy_setup_env.AppendUnique(CPPPATH = [
                        env.get('SRC_DIR') + '/resource/csdk/security/provisioning/include',
+                       env.get('SRC_DIR') + '/resource/csdk/security/include/internal',
                        env.get('SRC_DIR') + '/resource/csdk/connectivity/api/',
-                       env.get('SRC_DIR') + '/resource/csdk/security/provisioning/include/internal',
+                       env.get('SRC_DIR') + '/resource/csdk/security/provisioning/include/internal',
                        env.get('SRC_DIR') + '/resource/csdk/security/provisioning/include/oxm'])
                if env.get('WITH_TCP') == True:
                        easy_setup_env.AppendUnique(LIBS = ['mbedtls', 'mbedx509', 'mbedcrypto'])
old mode 100644 (file)
new mode 100755 (executable)
index f2e545b..008828c
@@ -44,6 +44,18 @@ public class CloudProp {
 
     public void setCloudProp(String authCode, String authProvider, String ciServer)
     {
+        if(authCode == null)
+        {
+            authCode = "";
+        }
+        if(authProvider == null)
+        {
+            authProvider = "";
+        }
+        if(ciServer == null)
+        {
+            ciServer = "";
+        }
         try {
             mRep.setValue(ESConstants.OC_RSRVD_ES_AUTHCODE, authCode);
             mRep.setValue(ESConstants.OC_RSRVD_ES_AUTHPROVIDER, authProvider);
old mode 100644 (file)
new mode 100755 (executable)
index f8669c4..2cff252
@@ -44,6 +44,14 @@ public class DeviceProp {
 
     public void setWiFiProp(String ssid, String pwd, WIFI_AUTHTYPE authtype, WIFI_ENCTYPE enctype)
     {
+        if(ssid == null)
+        {
+            ssid = "";
+        }
+        if(pwd == null)
+        {
+            pwd = "";
+        }
         try
         {
             mRep.setValue(ESConstants.OC_RSRVD_ES_SSID, ssid);
@@ -57,6 +65,18 @@ public class DeviceProp {
 
     public void setDevConfProp(String language, String country, String location)
     {
+        if(language == null)
+        {
+            language = "";
+        }
+        if(country == null)
+        {
+            country = "";
+        }
+        if(location == null)
+        {
+            location = "";
+        }
         try {
             mRep.setValue(ESConstants.OC_RSRVD_ES_LANGUAGE, language);
             mRep.setValue(ESConstants.OC_RSRVD_ES_COUNTRY, country);
index cae9ec5..6d2216d 100755 (executable)
@@ -54,6 +54,12 @@ Java_org_iotivity_service_easysetup_mediator_EasySetup_nativeCreateRemoteEnrolle
     try
     {
         nativeRemoteEnrollee = EasySetup::getInstance()->createRemoteEnrollee(jniOcResource->getOCResource());
+        if (!nativeRemoteEnrollee)
+        {
+            ES_LOGE("Failed to create RemoteEnrollee object.");
+            return NULL;
+        }
+
         //create the java object
         jRemoteEnrollee = env->NewObject(g_cls_RemoteEnrollee, g_mid_RemoteEnrollee_ctor);
         if (!jRemoteEnrollee)
index 7078def..551f4a4 100755 (executable)
@@ -77,3 +77,4 @@ cmdBuildEasysetup=jdk_env.Gradle(target="EasySetupCore/objs",
 
 Depends(cmdBuildEasysetup, env.get('baseAAR'))
 
+env.AppendUnique(easysetupAAR = cmdBuildEasysetup)
\ No newline at end of file
index deeac85..c7fe9a8 100755 (executable)
@@ -123,15 +123,21 @@ namespace OIC
              */
             CloudProp()
             {
+                m_cloudID = "";
+                m_credID = -1;
             }
 
             CloudProp(const CloudProp& cloudProp) :
-                m_rep(cloudProp.toOCRepresentation()), m_cloudID(cloudProp.getCloudID())
+                                            m_rep(cloudProp.toOCRepresentation()),
+                                            m_cloudID(cloudProp.getCloudID()),
+                                            m_credID(cloudProp.getCredID())
             {
             }
 
             CloudProp(const CloudProp&& cloudProp) :
-                m_rep(std::move(cloudProp.toOCRepresentation())), m_cloudID(cloudProp.getCloudID())
+                                            m_rep(std::move(cloudProp.toOCRepresentation())),
+                                            m_cloudID(cloudProp.getCloudID()),
+                                            m_credID(cloudProp.getCredID())
             {
             }
 
@@ -417,9 +423,9 @@ namespace OIC
              */
             std::string getLocation() const
             {
-                if(m_rep.hasAttribute(OC_RSRVD_ES_MODELNUMBER))
+                if(m_rep.hasAttribute(OC_RSRVD_ES_LOCATION))
                 {
-                    return m_rep.getValue<std::string>(OC_RSRVD_ES_MODELNUMBER);
+                    return m_rep.getValue<std::string>(OC_RSRVD_ES_LOCATION);
                 }
                 return std::string("");
             }
index da65cb1..9d93eca 100755 (executable)
@@ -30,6 +30,7 @@
 #include "provisioningdatabasemanager.h"
 #include "oic_string.h"
 #include "utlist.h"
+#include "srmutility.h"
 
 namespace OIC
 {
@@ -105,35 +106,6 @@ namespace OIC
             uuidString = uuidArray;
         }
 
-        void EnrolleeSecurity::convertStringToUUID(OicUuid_t& uuid,
-                                                              const std::string uuidString)
-        {
-            size_t outBufSize = B64DECODE_OUT_SAFESIZE((uuidString.length() + 1));
-            uint8_t* outKey = (uint8_t*)OICCalloc(1, outBufSize);
-            uint32_t outKeySize = 0;
-            if(NULL == outKey)
-            {
-                OIC_LOG (ERROR, ENROLEE_SECURITY_TAG, "Failed to memoray allocation.");
-                throw ESBadRequestException ("Failed to memoray allocation.");
-            }
-
-            if(B64_OK == b64Decode((char*)uuidString.c_str(),
-                                    uuidString.length(),
-                                    outKey,
-                                    outBufSize,
-                                    &outKeySize))
-            {
-                memcpy(uuid.id, outKey, outKeySize);
-            }
-            else
-            {
-                OIC_LOG (ERROR, ENROLEE_SECURITY_TAG, "Failed to base64 decoding.");
-                throw ESBadRequestException ("Failed to base64 decoding.");
-            }
-
-            OICFree(outKey);
-        }
-
         void EnrolleeSecurity::ownershipTransferCb(OC::PMResultList_t *result, int hasError)
         {
             if (hasError)
@@ -329,6 +301,13 @@ namespace OIC
             return false;
         }
 
+
+        std::string EnrolleeSecurity::getUUID() const
+        {
+            return m_ocResource->sid();
+        };
+
+#if defined(__WITH_DTLS__) && defined(__WITH_TLS__)
         void EnrolleeSecurity::provisionSecurityForCloudServer(
             std::string cloudUuid, int credId)
         {
@@ -366,13 +345,15 @@ namespace OIC
                 throw ESException("Not found owned devices.");
             }
 
-            if(performACLProvisioningForCloudServer(ownedDevice, cloudUuid) != ESResult::ES_OK)
+            if(!cloudUuid.empty()
+                && performACLProvisioningForCloudServer(ownedDevice, cloudUuid) != ESResult::ES_OK)
             {
                 OIC_LOG(DEBUG, ENROLEE_SECURITY_TAG, "error performACLProvisioningForCloudServer");
                 throw ESException("error performACLProvisioningForCloudServer");
             }
 
-            if(performCertProvisioningForCloudServer(ownedDevice, credId) != ESResult::ES_OK)
+            if(credId != -1
+                && performCertProvisioningForCloudServer(ownedDevice, credId) != ESResult::ES_OK)
             {
                 OIC_LOG(DEBUG, ENROLEE_SECURITY_TAG, "error performCertProvisioningForCloudServer");
                 throw ESException("error performCertProvisioningForCloudServer");
@@ -429,7 +410,7 @@ namespace OIC
             }
 
             OicUuid_t uuid;
-            convertStringToUUID(uuid, cloudUuid);
+            ConvertStrToUuid(cloudUuid.c_str(), &uuid);
 
             // Create Acl for Cloud Server to be provisioned to Enrollee
             OicSecAcl_t* acl = createAcl(uuid);
@@ -461,11 +442,6 @@ namespace OIC
             return res;
         }
 
-        std::string EnrolleeSecurity::getUUID() const
-        {
-            return m_ocResource->sid();
-        };
-
         OicSecAcl_t* EnrolleeSecurity::createAcl(const OicUuid_t cloudUuid)
         {
             // allocate memory for |acl| struct
@@ -507,6 +483,7 @@ namespace OIC
             size_t arrLen = 1;
             rsrc->typeLen = arrLen;
             rsrc->types = (char**)OICCalloc(arrLen, sizeof(char*));
+            rsrc->interfaceLen = 1;
             rsrc->interfaces = (char**)OICCalloc(arrLen, sizeof(char*));
             rsrc->types[0] = OICStrdup("rt");   // ignore
             rsrc->interfaces[0] = OICStrdup("if");  // ignore
@@ -522,12 +499,12 @@ namespace OIC
         {
             if (hasError)
             {
-               OIC_LOG(DEBUG, ENROLEE_SECURITY_TAG, "Error in provisioning operation!");
+               OIC_LOG(DEBUG, ENROLEE_SECURITY_TAG, "Error in ACL provisioning operation!");
                aclResult = false;
             }
             else
             {
-               OIC_LOG(DEBUG, ENROLEE_SECURITY_TAG, "Received provisioning results: ");
+               OIC_LOG(DEBUG, ENROLEE_SECURITY_TAG, "Received ACL provisioning results: ");
 
                std::string devUuid;
                for (unsigned int i = 0; i < result->size(); i++)
@@ -546,12 +523,12 @@ namespace OIC
         {
             if (hasError)
             {
-               OIC_LOG(DEBUG, ENROLEE_SECURITY_TAG, "Error in provisioning operation!");
+               OIC_LOG(DEBUG, ENROLEE_SECURITY_TAG, "Error in Cert. provisioning operation!");
                aclResult = false;
             }
             else
             {
-               OIC_LOG(DEBUG, ENROLEE_SECURITY_TAG, "Received provisioning results: ");
+               OIC_LOG(DEBUG, ENROLEE_SECURITY_TAG, "Received Cert. provisioning results: ");
 
                std::string devUuid;
                for (unsigned int i = 0; i < result->size(); i++)
@@ -565,5 +542,6 @@ namespace OIC
             }
             m_cond.notify_all();
         }
+#endif //defined(__WITH_DTLS__) && defined(__WITH_TLS__)
     }
 }
old mode 100644 (file)
new mode 100755 (executable)
index 8ab91ed..644eddd
@@ -32,7 +32,7 @@ namespace OIC
 {
     namespace Service
     {
-        #define ENROLEE_SECURITY_TAG "ENROLEE_SECURITY"
+        #define ENROLEE_SECURITY_TAG "ENROLLEE_SECURITY"
         #define UUID_SIZE (16)
         #define UUID_STRING_SIZE (37)
 
@@ -57,8 +57,6 @@ namespace OIC
                 const SecurityPinCb securityPinCb,
                 const SecProvisioningDbPathCb secProvisioningDbPathCb);
             void provisionOwnership();
-            void provisionSecurityForCloudServer(
-                std::string cloudUuid, int credId);
             std::string getUUID() const;
 
         private:
@@ -73,13 +71,6 @@ namespace OIC
             std::atomic<bool>  aclResult;
             std::atomic<bool>  certResult;
 
-            ESResult performCertProvisioningForCloudServer(
-                std::shared_ptr< OC::OCSecureResource > ownedDevice,
-                int credId);
-            ESResult performACLProvisioningForCloudServer(
-                std::shared_ptr< OC::OCSecureResource > ownedDevice,
-                std::string& cloudUuid);
-
             std::shared_ptr< OC::OCSecureResource > m_securedResource;
             std::shared_ptr< OC::OCSecureResource > findEnrolleeSecurityResource(
                 OC::DeviceList_t &list);
@@ -89,11 +80,22 @@ namespace OIC
             void ownershipTransferCb(OC::PMResultList_t *result, int hasError);
             void convertUUIDToString(const uint8_t uuid[UUID_SIZE],
                                                 std::string& uuidString);
-            void convertStringToUUID(OicUuid_t& uuid, const std::string uuidString);
-            OicSecAcl_t* createAcl(const OicUuid_t cloudUuid);
 
+#if defined(__WITH_DTLS__) && defined(__WITH_TLS__)
+        public:
+            void provisionSecurityForCloudServer(
+                std::string cloudUuid, int credId);
+        private:
+            ESResult performCertProvisioningForCloudServer(
+                std::shared_ptr< OC::OCSecureResource > ownedDevice,
+                int credId);
+            ESResult performACLProvisioningForCloudServer(
+                std::shared_ptr< OC::OCSecureResource > ownedDevice,
+                std::string& cloudUuid);
+            OicSecAcl_t* createAcl(const OicUuid_t cloudUuid);
             void ACLProvisioningCb(PMResultList_t *result, int hasError);
             void CertProvisioningCb(PMResultList_t *result, int hasError);
+#endif //defined(__WITH_DTLS__) && defined(__WITH_TLS__)
         };
     }
 }
index 2bb1792..f5c8d7f 100755 (executable)
@@ -345,11 +345,6 @@ namespace OIC
         {
             ESResult result = ES_ERROR;
 
-            if (m_cloudResource != nullptr)
-            {
-                throw ESBadRequestException ("Already created");
-            }
-
             result = discoverResource();
 
             if (result == ES_ERROR)
@@ -414,15 +409,13 @@ namespace OIC
 #if defined(__WITH_DTLS__) && defined(__WITH_TLS__)
             try
             {
-                m_enrolleeSecurity = std::make_shared <EnrolleeSecurity> (m_ocResource, "");
-
-                if(cloudProp.getCloudID().empty())
+                if(!(cloudProp.getCloudID().empty() && cloudProp.getCredID() == -1))
                 {
-                    throw ESInvalidParameterException("Invalid Cloud Server UUID.");
-                }
+                    m_enrolleeSecurity = std::make_shared <EnrolleeSecurity> (m_ocResource, "");
 
-                m_enrolleeSecurity->provisionSecurityForCloudServer(cloudProp.getCloudID(),
-                                                                    cloudProp.getCredID());
+                    m_enrolleeSecurity->provisionSecurityForCloudServer(cloudProp.getCloudID(),
+                                                                        cloudProp.getCredID());
+                }
             }
 
             catch (const std::exception& e)
@@ -437,7 +430,7 @@ namespace OIC
                 m_cloudPropProvStatusCb(provStatus);
                 return;
             }
-#endif
+#endif //defined(__WITH_DTLS__) && defined(__WITH_TLS__)
 
             if (m_cloudResource == nullptr)
             {
index b20dc4e..76a902b 100644 (file)
@@ -77,7 +77,8 @@ help_vars.Add(EnumVariable('SECURED', 'Build with DTLS', '0', allowed_values=('0
 help_vars.Add(BoolVariable('UPLOAD', 'Upload binary ? (For Arduino)', require_upload))
 help_vars.Add(EnumVariable('ROUTING', 'Enable routing', 'EP', allowed_values=('GW', 'EP')))
 help_vars.Add(EnumVariable('BUILD_SAMPLE', 'Build with sample', 'ON', allowed_values=('ON', 'OFF')))
-
+help_vars.Add(BoolVariable('WITH_TCP', 'Build with TCP adapter', False))
+help_vars.Add(BoolVariable('WITH_CLOUD', 'Build including AccountManager class and Cloud Client sample', False))
 help_vars.AddVariables(('DEVICE_NAME', 'Network display name for device', 'OIC-DEVICE', None, None),)
 
 #ES_TARGET_ENROLLEE is for specifying what is our target enrollee (Arduino or rest of platforms which support Multicast)
index 1038ff1..149f05f 100644 (file)
@@ -19,7 +19,8 @@ with_cloud = env.get('WITH_CLOUD')
 print "Given Transport is %s" % transport
 print "Given OS is %s" % target_os
 print "Given es_target_enrollee is %s" % es_target_enrollee
-
+print "Given tcp option is %s" % with_tcp
+print "Given cloud option is %s" %with_cloud
 
 if target_os == 'tizen':
        command = "sh service/easy-setup/sampleapp/enrollee/tizen-sdb/EnrolleeSample/build/tizen/gbsbuild.sh %s %s %s %s %s %s %s %s" % (transport, secured, routing, release_mode, logging, es_target_enrollee, with_tcp, with_cloud)
index d869bbe..8e72b50 100644 (file)
@@ -39,6 +39,7 @@ cp -R ./extlibs/tinydtls $sourcedir/tmp/extlibs
 cp -LR ./extlibs/sqlite3 $sourcedir/tmp/extlibs
 cp -R ./extlibs/timer $sourcedir/tmp/extlibs
 cp -R ./extlibs/rapidxml $sourcedir/tmp/extlibs
+cp -R ./extlibs/libcoap $sourcedir/tmp/extlibs
 cp -R ./resource $sourcedir/tmp
 cp -R ./service $sourcedir/tmp
 cp ./extra_options.scons $sourcedir/tmp
index dda4b40..41d14d9 100644 (file)
@@ -3,7 +3,7 @@
 %{!?VERBOSE: %define VERBOSE 1}
 
 Name: com-oic-es-sample
-Version:    1.1.1
+Version:    1.2.0
 Release:    0
 Summary: Tizen adapter interfacesample application
 URL: http://slp-source.sec.samsung.net
old mode 100644 (file)
new mode 100755 (executable)
index 3f800e7..6f5b6f6
Binary files a/service/easy-setup/sampleapp/mediator/android/EasySetup/app/src/main/assets/oic_svr_db_client.dat and b/service/easy-setup/sampleapp/mediator/android/EasySetup/app/src/main/assets/oic_svr_db_client.dat differ
index bbb7614..98758ee 100755 (executable)
@@ -347,7 +347,7 @@ public class EasysetupActivity extends Activity
                 ModeType.CLIENT_SERVER,
                 "0.0.0.0", // bind to all available interfaces
                 0,
-                QualityOfService.LOW, filePath + OIC_CLIENT_JSON_DB_FILE);
+                QualityOfService.HIGH, filePath + OIC_CLIENT_JSON_DB_FILE);
         try {
             /*
              * Initialize DataBase
index 54d9624..021902c 100644 (file)
@@ -75,4 +75,4 @@ jdk_env['BUILD_DIR'] = env.get('BUILD_DIR')
 cmdBuildEasysetupApp=jdk_env.Gradle(target="EasySetup/app/apk", 
     source="EasySetup/app/src/main/java/org/iotivity/service/easysetup/EasysetupActivity.java")
 
-Depends(cmdBuildEasysetupApp, env.get('baseAAR'))
\ No newline at end of file
+Depends(cmdBuildEasysetupApp, env.get('easysetupAAR'))
\ No newline at end of file
index e89a344..3942a6e 100755 (executable)
@@ -244,6 +244,7 @@ void provisionCloudProperty()
     CloudProp cloudProp;
     cloudProp.setCloudProp("authCode", "authProvider", "ciServer");
     cloudProp.setCloudID("f002ae8b-c42c-40d3-8b8d-1927c17bd1b3");
+    cloudProp.setCredID(1);
 
     try
     {
old mode 100644 (file)
new mode 100755 (executable)
index 3f800e7..6f5b6f6
Binary files a/service/easy-setup/sampleapp/mediator/linux/richsdk_sample/oic_svr_db_client.dat and b/service/easy-setup/sampleapp/mediator/linux/richsdk_sample/oic_svr_db_client.dat differ
index ba2db6c..ab866e8 100755 (executable)
@@ -120,8 +120,8 @@ if target_os == 'linux':
 SConscript('examples/SConscript')
 
 # Go to build jni
-#if target_os == 'android':
-#    SConscript('android/SConscript')
+if target_os == 'android':
+    SConscript('android/SConscript')
 
 # Go to build c++ wrapper
 SConscript('cpp-wrapper/SConscript')
old mode 100644 (file)
new mode 100755 (executable)
index 3b23482..778e089
@@ -44,7 +44,11 @@ if not os.path.exists(android_home + '/platforms/android-21') or not os.path.exi
 
 
 def ensure_libs(target, source, env):
-    return target, [source, env.get('BUILD_DIR') + 'liboc.so', env.get('BUILD_DIR') + 'liboc_logger.so']
+    return target, [source, env.get('BUILD_DIR') + 'liboc.so',
+                            env.get('BUILD_DIR') + 'liboc_logger.so',
+                            env.get('BUILD_DIR') + 'libnotification_provider_wrapper.so',
+                            env.get('BUILD_DIR') + 'libnotification_consumer.so']
+
 
 jdk_env = Environment(ENV=os.environ)
 jdk_env['BUILDERS']['Gradle'] = Builder(action = env.get('ANDROID_GRADLE') + 
index d48e7e1..7641ccc 100755 (executable)
@@ -46,24 +46,6 @@ public class ConsumerService
         System.loadLibrary("notification_consumer_jni");
     }
 
-    public enum Response
-    {
-        ALLOW(1),
-        DENY(2),
-        TOPIC(3);
-        private int type;
-
-        private Response(int type)
-        {
-            this.type = type;
-        }
-
-        public int getResponseType()
-        {
-            return this.type;
-        }
-    };
-
     private static ConsumerService instance;
     static
     {
@@ -74,62 +56,38 @@ public class ConsumerService
         return instance;
     }
 
-    public ConsumerService()
-    {
-        Log.i (LOG_TAG, "ConsumerService()");
-    }
-
-    public void Start(
-        OnProviderDiscoveredListner onProviderDiscoveredListner,
-        OnProviderChangedListener onProviderChangedListener
+    public void start(
+        OnProviderDiscoveredListener onProviderDiscoveredListener
     ) throws NSException
     {
-        nativeStart(onProviderDiscoveredListner, onProviderChangedListener);
+        nativeStart(onProviderDiscoveredListener);
     }
 
-    public void Stop() throws NSException
+    public void stop() throws NSException
     {
         nativeStop();
     }
 
-    public void EnableRemoteService(String serverAddress) throws NSException
+    public void enableRemoteService(String serverAddress) throws NSException
     {
         nativeEnableRemoteService(serverAddress);
     }
 
-    public void RescanProvider() throws NSException
+    public void rescanProvider() throws NSException
     {
         nativeRescanProvider();
     }
 
-    public Provider GetProvider(String providerId) throws NSException
-    {
-        return nativeGetProvider(providerId);
-    }
-
-    public Message GetMessage(long  messageId) throws NSException
-    {
-        return nativeGetMessage(messageId);
-    }
-
-    public interface OnProviderDiscoveredListner
+    public interface OnProviderDiscoveredListener
     {
         public void onProviderDiscovered(Provider provider);
     }
 
-    public interface OnProviderChangedListener
-    {
-        public void onProviderChanged(Provider provider , Response response);
-    }
-
     private native void nativeStart (
-        OnProviderDiscoveredListner onProviderDiscoveredListner,
-        OnProviderChangedListener onProviderChangedListener
+        OnProviderDiscoveredListener onProviderDiscoveredListener
     ) throws NSException;
 
     private native void nativeStop() throws NSException;
     private native void nativeEnableRemoteService(String serverAddress) throws NSException;
     private native void nativeRescanProvider() throws NSException;
-    private native Provider nativeGetProvider(String providerId) throws NSException;
-    private native Message nativeGetMessage(long messageId) throws NSException;
 }
index 622a09b..69e410e 100755 (executable)
@@ -32,8 +32,26 @@ public class Provider
 {
     private static final String LOG_TAG = "ConsumerService_Provider";
 
+    public enum ProviderState
+    {
+        ALLOW(1),
+        DENY(2),
+        TOPIC(3),
+        STOPPED(12);
+        private int state;
+
+        private ProviderState(int state)
+        {
+            this.state = state;
+        }
+
+        public int getProviderState()
+        {
+            return this.state;
+        }
+    };
+
     public String mProviderId        = null;
-    TopicsList mTopicsList = new TopicsList();
     private long mNativeHandle       = 0;
 
     public Provider(String providerId)
@@ -48,35 +66,46 @@ public class Provider
         return mProviderId ;
     }
 
-    public TopicsList  getTopicsList()
+    public TopicsList getTopicList() throws NSException
+    {
+        return nativeGetTopicList();
+    }
+
+    public ProviderState getProviderState() throws NSException
     {
-        return mTopicsList ;
+        return nativeGetProviderState();
     }
 
-    public void Subscribe() throws NSException
+    public void subscribe() throws NSException
     {
         nativeSubscribe();
     }
 
-    public void Unsubscribe() throws NSException
+    public boolean isSubscribed () throws NSException
     {
-        nativeUnsubscribe();
+        return nativeIsSubscribed();
     }
 
-    public void SendSyncInfo(long messageId, SyncInfo.SyncType syncType) throws NSException
+    public void sendSyncInfo(long messageId, SyncInfo.SyncType syncType) throws NSException
     {
         nativeSendSyncInfo(messageId, syncType.ordinal());
     }
 
-    public void SetListener(OnMessageReceivedListner onMessageReceivedListner,
+    public void setListener(OnProviderStateListener onProviderStateListener,
+                            OnMessageReceivedListner onMessageReceivedListner,
                             OnSyncInfoReceivedListner onSyncInfoReceivedListner) throws NSException
     {
-        nativeSetListener(onMessageReceivedListner, onSyncInfoReceivedListner);
+        nativeSetListener(onProviderStateListener, onMessageReceivedListner, onSyncInfoReceivedListner);
     }
 
-    public int SelectInterestTopics(TopicsList topicsList) throws NSException
+    public int updateTopicList(TopicsList topicsList) throws NSException
     {
-        return nativeSelectInterestTopics(topicsList);
+        return nativeUpdateTopicList(topicsList);
+    }
+
+    public interface OnProviderStateListener
+    {
+        public void onProviderStateReceived(ProviderState state);
     }
 
     public interface OnMessageReceivedListner
@@ -90,11 +119,13 @@ public class Provider
     }
 
     private native void nativeSubscribe() throws NSException;
-    private native void nativeUnsubscribe() throws NSException;
     private native void nativeSendSyncInfo(long messageId, int syncType) throws NSException;
-    private native void nativeSetListener(
-        OnMessageReceivedListner onMessageReceivedListner,
-        OnSyncInfoReceivedListner onSyncInfoReceivedListner
-    ) throws NSException;
-    private native int nativeSelectInterestTopics(TopicsList topicsList) throws NSException;
+    private native void nativeSetListener(OnProviderStateListener onProviderStateListener,
+                                      OnMessageReceivedListner onMessageReceivedListner,
+                                      OnSyncInfoReceivedListner onSyncInfoReceivedListner) throws NSException;
+    public native TopicsList  nativeGetTopicList() throws NSException;
+    private native int nativeUpdateTopicList(TopicsList topicsList) throws NSException;
+    private native ProviderState nativeGetProviderState() throws NSException;
+    public native boolean  nativeIsSubscribed() throws NSException;
+
 }
index 37e2417..a711b2c 100644 (file)
@@ -33,33 +33,34 @@ public class Consumer
     {
         mConsumerId = consumerId;
     }
+
     public String getConsumerId( )
     {
         return mConsumerId;
     }
-    public int AcceptSubscription(Consumer consumer, boolean accepted) throws NSException
+
+    public int acceptSubscription(boolean accepted) throws NSException
     {
-        if (consumer != null)
-            return nativeAcceptSubscription(consumer, accepted);
-        return -1;
+        return nativeAcceptSubscription(mConsumerId, accepted);
     }
 
-    public int SelectTopic(String topicName) throws NSException
+    public int setTopic(String topicName) throws NSException
     {
-        return nativeSelectTopic(mConsumerId, topicName);
+        return nativeSetConsumerTopic(mConsumerId, topicName);
     }
-    public int UnselectTopic(String topicName) throws NSException
+
+    public int unsetTopic(String topicName) throws NSException
     {
-        return nativeUnselectTopic(mConsumerId, topicName);
+        return nativeUnsetConsumerTopic(mConsumerId, topicName);
     }
 
-    public TopicsList GetConsumerTopics() throws NSException
+    public TopicsList getConsumerTopicList() throws NSException
     {
-        return nativeGetConsumerTopics(mConsumerId);
+        return nativeGetConsumerTopicList(mConsumerId);
     }
 
-    public native int  nativeAcceptSubscription(Consumer consumer, boolean accepted);
-    public native int  nativeSelectTopic(String consumerId, String topicName);
-    public native int  nativeUnselectTopic(String consumerId, String topicName);
-    public native TopicsList  nativeGetConsumerTopics(String consumerId);
+    public native int  nativeAcceptSubscription(String  consumerId, boolean accepted) throws NSException;
+    public native int  nativeSetConsumerTopic(String consumerId, String topicName) throws NSException;
+    public native int  nativeUnsetConsumerTopic(String consumerId, String topicName) throws NSException;
+    public native TopicsList  nativeGetConsumerTopicList(String consumerId) throws NSException;
 }
\ No newline at end of file
index 9b695ad..428b022 100644 (file)
@@ -47,75 +47,84 @@ public class ProviderService
     {
         instance = new ProviderService();
     }
-    public interface OnSubscriptionListener
-    {
-        public void onConsumerSubscribed(Consumer consumer);
-    }
-    public interface OnSyncInfoListener
-    {
-        public void onMessageSynchronized(SyncInfo syncInfo);
-    }
 
     public static ProviderService getInstance()
     {
         return instance;
     }
-    public int Start(boolean policy,
-                     OnSubscriptionListener  subscriptionListener,
-                     OnSyncInfoListener  syncInfoListener) throws NSException
-    {
 
-        return nativeStart(policy, subscriptionListener, syncInfoListener);
+    public int start(OnConsumerSubscribedListener  subscribedListener,
+                     OnMessageSynchronizedListener  messageSynchronized,
+                     boolean subControllability, String userInfo) throws NSException
+    {
+        return nativeStart(subscribedListener, messageSynchronized,subControllability,userInfo);
     }
 
-    public int Stop() throws NSException
+    public int stop() throws NSException
     {
         return nativeStop();
     }
 
-    public int   SendMessage(Message message) throws NSException
+    public int   sendMessage(Message message) throws NSException
     {
         return nativeSendMessage(message);
     }
 
-    public void SendSyncInfo ( long messageId , SyncInfo.SyncType syncType) throws NSException
+    public void sendSyncInfo ( long messageId , SyncInfo.SyncType syncType) throws NSException
     {
         nativeSendSyncInfo(messageId, syncType.ordinal());
-        return;
     }
 
-    public int   EnableRemoteService(String servAdd) throws NSException
+    public Message createMessage () throws NSException
+    {
+        return nativeCreateMessage();
+    }
+
+    public int   enableRemoteService(String servAdd) throws NSException
     {
         return nativeEnableRemoteService(servAdd);
     }
 
-    public int  DisableRemoteService(String servAdd) throws NSException
+    public int  disableRemoteService(String servAdd) throws NSException
     {
         return nativeDisableRemoteService(servAdd);
     }
 
-    public int AddTopic(String topicName) throws NSException
+    public int registerTopic(String topicName) throws NSException
     {
-        return nativeAddTopic(topicName);
+        return nativeRegisterTopic(topicName);
     }
-    public int DeleteTopic(String topicName) throws NSException
+
+    public int unregisterTopic(String topicName) throws NSException
+    {
+        return nativeUnregisterTopic(topicName);
+    }
+
+    public TopicsList getRegisteredTopicList() throws NSException
+    {
+        return nativeGetRegisteredTopicList();
+    }
+
+    public interface OnConsumerSubscribedListener
     {
-        return nativeDeleteTopic(topicName);
+        public void onConsumerSubscribed(Consumer consumer);
     }
-    public TopicsList GetTopics() throws NSException
+
+    public interface OnMessageSynchronizedListener
     {
-        return nativeGetTopics();
+        public void onMessageSynchronized(SyncInfo syncInfo);
     }
 
-    public native int  nativeStart(boolean policy,
-                               OnSubscriptionListener   subscriptionListener,
-                               OnSyncInfoListener   syncInfoListener);
-    public native int  nativeStop();
-    public native int  nativeSendMessage(Message message);
-    public native void  nativeSendSyncInfo( long messageId , int type);
-    public native int  nativeEnableRemoteService(String servAdd);
-    public native int  nativeDisableRemoteService(String servAdd);
-    public native int  nativeAddTopic(String topicName);
-    public native int  nativeDeleteTopic(String topicName);
-    public native TopicsList  nativeGetTopics();
+    public native int  nativeStart(OnConsumerSubscribedListener    subscribedListener,
+                                                 OnMessageSynchronizedListener   messageSynchronized,
+                                                 boolean subControllability, String userInfo) throws NSException;
+    public native int  nativeStop() throws NSException;
+    public native int  nativeSendMessage(Message message) throws NSException;
+    public native void  nativeSendSyncInfo( long messageId , int type) throws NSException;
+    public native Message nativeCreateMessage() throws NSException;
+    public native int  nativeEnableRemoteService(String servAdd) throws NSException;
+    public native int  nativeDisableRemoteService(String servAdd) throws NSException;
+    public native int  nativeRegisterTopic(String topicName) throws NSException;
+    public native int  nativeUnregisterTopic(String topicName) throws NSException;
+    public native TopicsList  nativeGetRegisteredTopicList() throws NSException;
 }
index 88ed756..2b85992 100755 (executable)
@@ -24,8 +24,8 @@
 static JavaVM *g_jvm = NULL;\r
 \r
 static jobject g_obj_postListener = NULL;\r
-static jobject g_obj_discoverListener = NULL;\r
 static jobject g_obj_syncListener = NULL;\r
+static jobject g_obj_discoverListener = NULL;\r
 static jobject g_obj_acceptListener = NULL;\r
 \r
 jclass g_cls_Message;\r
@@ -35,7 +35,7 @@ jclass g_cls_SyncType;
 jclass g_cls_MediaContents;\r
 jclass g_cls_TopicState;\r
 jclass g_cls_Message_Type;\r
-jclass g_cls_Response;\r
+jclass g_cls_ProviderState;\r
 jclass g_cls_Topic;\r
 jclass g_cls_TopicsList;\r
 \r
@@ -66,33 +66,39 @@ static JNIEnv *GetJNIEnv(jint *ret)
     }\r
 }\r
 \r
-jobject getJavaResponse(JNIEnv *env, OIC::Service::NSResponse response)\r
+jobject getJavaProviderState(JNIEnv *env, OIC::Service::NSProviderState state)\r
 {\r
-    LOGD ("ConsumerService_getJavaResponse - IN");\r
-    switch (response)\r
+    LOGD ("ConsumerService_getJavaProviderState - IN");\r
+    switch (state)\r
     {\r
-        case OIC::Service::NSResponse::ALLOW:\r
+        case OIC::Service::NSProviderState::ALLOW:\r
+            {\r
+                static jfieldID fieldID = env->GetStaticFieldID(g_cls_ProviderState,\r
+                                          "ALLOW", "Lorg/iotivity/service/ns/consumer/Provider$ProviderState;");\r
+                return env->GetStaticObjectField(g_cls_ProviderState, fieldID);\r
+            }\r
+        case OIC::Service::NSProviderState::DENY:\r
             {\r
-                static jfieldID fieldID = env->GetStaticFieldID(g_cls_Response,\r
-                                          "ALLOW", "Lorg/iotivity/service/ns/consumer/ConsumerService$Response;");\r
-                return env->GetStaticObjectField(g_cls_Response, fieldID);\r
+                static jfieldID fieldID = env->GetStaticFieldID(g_cls_ProviderState,\r
+                                          "DENY", "Lorg/iotivity/service/ns/consumer/Provider$ProviderState;");\r
+                return env->GetStaticObjectField(g_cls_ProviderState, fieldID);\r
             }\r
-        case OIC::Service::NSResponse::DENY:\r
+        case OIC::Service::NSProviderState::TOPIC:\r
             {\r
-                static jfieldID fieldID = env->GetStaticFieldID(g_cls_Response,\r
-                                          "DENY", "Lorg/iotivity/service/ns/consumer/ConsumerService$Response;");\r
-                return env->GetStaticObjectField(g_cls_Response, fieldID);\r
+                static jfieldID fieldID = env->GetStaticFieldID(g_cls_ProviderState,\r
+                                          "TOPIC", "Lorg/iotivity/service/ns/consumer/Provider$ProviderState;");\r
+                return env->GetStaticObjectField(g_cls_ProviderState, fieldID);\r
             }\r
-        case OIC::Service::NSResponse::TOPIC:\r
+        case OIC::Service::NSProviderState::STOPPED:\r
             {\r
-                static jfieldID fieldID = env->GetStaticFieldID(g_cls_Response,\r
-                                          "TOPIC", "Lorg/iotivity/service/ns/consumer/ConsumerService$Response;");\r
-                return env->GetStaticObjectField(g_cls_Response, fieldID);\r
+                static jfieldID fieldID = env->GetStaticFieldID(g_cls_ProviderState,\r
+                                          "STOPPED", "Lorg/iotivity/service/ns/consumer/Provider$ProviderState;");\r
+                return env->GetStaticObjectField(g_cls_ProviderState, fieldID);\r
             }\r
         default:\r
             return NULL;\r
     }\r
-    LOGD ("ConsumerService_getJavaResponse - OUT");\r
+    LOGD ("ConsumerService_getJavaProviderState - OUT");\r
     return NULL;\r
 }\r
 \r
@@ -427,15 +433,6 @@ jobject getJavaProvider(JNIEnv *env, OIC::Service::NSProvider *provider)
     }\r
     env->SetLongField(obj_provider, nativeHandle, pProvider);\r
 \r
-    jfieldID fid_topic = env->GetFieldID(cls_provider, "mTopicsList",\r
-                                         "Lorg/iotivity/service/ns/common/TopicsList;");\r
-    if (!fid_topic)\r
-    {\r
-        LOGE("Failed to get TopicList for Provider");\r
-        return NULL;\r
-    }\r
-    jobject topicList = getJavaTopicsList(env, provider->getTopicList());\r
-    env->SetObjectField(obj_provider, fid_topic, topicList);\r
     env->DeleteLocalRef(cls_provider);\r
     LOGD ("ConsumerService_getJavaProvider - OUT");\r
     return obj_provider;\r
@@ -448,27 +445,27 @@ jobject getJavaMessageType(JNIEnv *env, OIC::Service::NSMessage::NSMessageType t
     {\r
         case OIC::Service::NSMessage::NSMessageType::NS_MESSAGE_ALERT:\r
             {\r
-                static jfieldID fieldID = env->GetStaticFieldID(g_cls_Message,\r
+                static jfieldID fieldID = env->GetStaticFieldID(g_cls_Message_Type,\r
                                           "ALERT", "Lorg/iotivity/service/ns/common/Message$MessageType;");\r
-                return env->GetStaticObjectField(g_cls_Message, fieldID);\r
+                return env->GetStaticObjectField(g_cls_Message_Type, fieldID);\r
             }\r
         case OIC::Service::NSMessage::NSMessageType::NS_MESSAGE_NOTICE:\r
             {\r
-                static jfieldID fieldID = env->GetStaticFieldID(g_cls_Message,\r
+                static jfieldID fieldID = env->GetStaticFieldID(g_cls_Message_Type,\r
                                           "NOTICE", "Lorg/iotivity/service/ns/common/Message$MessageType;");\r
-                return env->GetStaticObjectField(g_cls_Message, fieldID);\r
+                return env->GetStaticObjectField(g_cls_Message_Type, fieldID);\r
             }\r
         case OIC::Service::NSMessage::NSMessageType::NS_MESSAGE_EVENT:\r
             {\r
-                static jfieldID fieldID = env->GetStaticFieldID(g_cls_Message,\r
+                static jfieldID fieldID = env->GetStaticFieldID(g_cls_Message_Type,\r
                                           "EVENT", "Lorg/iotivity/service/ns/common/Message$MessageType;");\r
-                return env->GetStaticObjectField(g_cls_Message, fieldID);\r
+                return env->GetStaticObjectField(g_cls_Message_Type, fieldID);\r
             }\r
         case OIC::Service::NSMessage::NSMessageType::NS_MESSAGE_INFO:\r
             {\r
-                static jfieldID fieldID = env->GetStaticFieldID(g_cls_Message,\r
+                static jfieldID fieldID = env->GetStaticFieldID(g_cls_Message_Type,\r
                                           "INFO", "Lorg/iotivity/service/ns/common/Message$MessageType;");\r
-                return env->GetStaticObjectField(g_cls_Message, fieldID);\r
+                return env->GetStaticObjectField(g_cls_Message_Type, fieldID);\r
             }\r
         default:\r
             return NULL;\r
@@ -666,9 +663,9 @@ void onDiscoverProvider(OIC::Service::NSProvider *provider)
     return ;\r
 }\r
 \r
-void onProviderChanged(OIC::Service::NSProvider *provider, OIC::Service::NSResponse response)\r
+void onProviderState( OIC::Service::NSProviderState state)\r
 {\r
-    LOGD ("ConsumerService_onProviderChanged -IN");\r
+    LOGD ("ConsumerService_onProviderState -IN");\r
 \r
     jint envRet;\r
     JNIEnv *env = GetJNIEnv(&envRet);\r
@@ -681,10 +678,10 @@ void onProviderChanged(OIC::Service::NSProvider *provider, OIC::Service::NSRespo
         if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();\r
         return ;\r
     }\r
-    jobject obj_provider = getJavaProvider(env, provider);\r
-    if (!obj_provider)\r
+    jobject obj_state = getJavaProviderState(env, state);\r
+    if (!obj_state)\r
     {\r
-        LOGE ("Failed to Get Provider Object");\r
+        LOGE ("Failed to Get ProviderState Object");\r
         if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();\r
         return ;\r
     }\r
@@ -698,20 +695,19 @@ void onProviderChanged(OIC::Service::NSProvider *provider, OIC::Service::NSRespo
     }\r
     jmethodID mid = env->GetMethodID(\r
                         cls,\r
-                        "onProviderChanged",\r
-                        "(Lorg/iotivity/service/ns/consumer/Provider;Lorg/iotivity/service/ns/consumer/ConsumerService$Response;)V");\r
+                        "onProviderStateReceived",\r
+                        "(Lorg/iotivity/service/ns/consumer/Provider$ProviderState;)V");\r
     if (!mid)\r
     {\r
-        LOGE ("Failed to Get MethodID for onProviderChanged");\r
+        LOGE ("Failed to Get MethodID for onProviderState");\r
         if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();\r
         return ;\r
     }\r
-    jobject obj_response = getJavaResponse(env, response);\r
-    env->CallVoidMethod(jAcceptListener, mid, obj_provider, obj_response);\r
+    env->CallVoidMethod(jAcceptListener, mid, obj_state);\r
 \r
     env->DeleteLocalRef(jAcceptListener);\r
     if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();\r
-    LOGD ("ConsumerService_onProviderChanged -OUT");\r
+    LOGD ("ConsumerService_onProviderState -OUT");\r
     return ;\r
 \r
 }\r
@@ -849,32 +845,21 @@ void onSyncInfoReceived(OIC::Service::NSSyncInfo *sync)
 }\r
 \r
 JNIEXPORT void JNICALL Java_org_iotivity_service_ns_consumer_ConsumerService_nativeStart\r
-(JNIEnv *env, jobject jObj, jobject jDiscoverListener, jobject jAccpetListener)\r
+(JNIEnv *env, jobject jObj, jobject jDiscoverListener)\r
 {\r
     LOGD ("ConsumerService_StartConsumer - IN");\r
-    if (!jDiscoverListener || !jAccpetListener)\r
+    if (!jDiscoverListener)\r
     {\r
         ThrowNSException(NS_ERROR, "Listener cannot be null");\r
         return ;\r
     }\r
-\r
     if (g_obj_discoverListener != NULL)\r
     {\r
         env->DeleteGlobalRef(g_obj_discoverListener);\r
     }\r
-    if (g_obj_acceptListener != NULL)\r
-    {\r
-        env->DeleteGlobalRef(g_obj_acceptListener);\r
-    }\r
-\r
     g_obj_discoverListener = (jobject) env->NewGlobalRef(jDiscoverListener);\r
-    g_obj_acceptListener = (jobject) env->NewGlobalRef(jAccpetListener);\r
 \r
-    OIC::Service::NSConsumerService::ConsumerConfig cfg;\r
-    cfg.m_discoverCb = onDiscoverProvider;\r
-    cfg.m_changedCb = onProviderChanged;\r
-\r
-    OIC::Service::NSConsumerService::getInstance()->Start(cfg);\r
+    OIC::Service::NSConsumerService::getInstance()->start(onDiscoverProvider);\r
     LOGD ("ConsumerService_StartConsumer - OUT");\r
     return;\r
 \r
@@ -886,14 +871,14 @@ JNIEXPORT void JNICALL Java_org_iotivity_service_ns_consumer_ConsumerService_nat
     LOGD ("ConsumerService_StopConsumer - IN");\r
 \r
     env->DeleteGlobalRef(g_obj_postListener);\r
-    env->DeleteGlobalRef(g_obj_discoverListener);\r
     env->DeleteGlobalRef(g_obj_syncListener);\r
+    env->DeleteGlobalRef(g_obj_discoverListener);\r
     env->DeleteGlobalRef(g_obj_acceptListener);\r
     g_obj_postListener = NULL;\r
-    g_obj_discoverListener = NULL;\r
     g_obj_syncListener = NULL;\r
+    g_obj_discoverListener = NULL;\r
     g_obj_acceptListener = NULL;\r
-    OIC::Service::NSConsumerService::getInstance()->Stop();\r
+    OIC::Service::NSConsumerService::getInstance()->stop();\r
     LOGD ("ConsumerService_StopConsumer - OUT");\r
     return;\r
 }\r
@@ -910,7 +895,7 @@ Java_org_iotivity_service_ns_consumer_ConsumerService_nativeEnableRemoteService
     }\r
     const char *serverAddress = env->GetStringUTFChars(jServerAddress, 0);\r
     OIC::Service::NSResult res =\r
-        OIC::Service::NSConsumerService::getInstance()->EnableRemoteService(std::string(serverAddress));\r
+        OIC::Service::NSConsumerService::getInstance()->enableRemoteService(std::string(serverAddress));\r
     env->ReleaseStringUTFChars(jServerAddress, serverAddress);\r
     LOGD ("ConsumerService_EnableRemoteService - OUT");\r
     return (jint) res;\r
@@ -920,87 +905,12 @@ JNIEXPORT void JNICALL Java_org_iotivity_service_ns_consumer_ConsumerService_nat
 (JNIEnv *env, jobject jObj)\r
 {\r
     LOGD ("ConsumerService_RescanProvider - IN");\r
-    OIC::Service::NSConsumerService::getInstance()->RescanProvider();\r
+    OIC::Service::NSConsumerService::getInstance()->rescanProvider();\r
     LOGD ("ConsumerService_RescanProvider - OUT");\r
     return;\r
 \r
 }\r
 \r
-JNIEXPORT jobject JNICALL Java_org_iotivity_service_ns_consumer_ConsumerService_nativeGetProvider\r
-(JNIEnv *env, jobject jObj, jstring jProviderId)\r
-{\r
-    LOGD ("ConsumerService_GetProvider - IN");\r
-    if (!jProviderId)\r
-    {\r
-        ThrowNSException(NS_ERROR, "ProviderId cannot be null");\r
-        return NULL;\r
-    }\r
-\r
-    const char *providerId = env->GetStringUTFChars(jProviderId, 0);\r
-    LOGD ("java_ProviderId : %s\n", providerId);\r
-\r
-    OIC::Service::NSProvider *provider =\r
-        OIC::Service::NSConsumerService::getInstance()->getProvider(std::string(providerId));\r
-    if (provider == nullptr)\r
-    {\r
-        ThrowNSException(NS_ERROR, "Provider with Given Id doesn't exist");\r
-        return NULL;\r
-    }\r
-    LOGD ("native_ProviderId : %s\n", provider->getProviderId().c_str());\r
-\r
-    jProviderId = env->NewStringUTF(provider->getProviderId().c_str());\r
-    jlong pProvider = (long)provider;\r
-\r
-    jclass cls_provider = (jclass) (env->NewLocalRef(g_cls_Provider));\r
-    if (!cls_provider)\r
-    {\r
-        LOGE ("Failed to Get ObjectClass for Provider");\r
-        ThrowNSException(NS_ERROR, "Couldn't find objectClass for Provider");\r
-        return NULL;\r
-    }\r
-    jmethodID mid_provider = env->GetMethodID(\r
-                                 cls_provider, "<init>", "(Ljava/lang/String;)V");\r
-    if (!mid_provider)\r
-    {\r
-        LOGE ("Failed to Get MethodID for Provider<init>");\r
-        ThrowNSException(NS_ERROR, "Couldn't find MethodID for Provider<init>");\r
-        return NULL;\r
-    }\r
-    jobject obj_provider = env->NewObject(cls_provider, mid_provider,\r
-                                          jProviderId);\r
-\r
-    jfieldID nativeHandle = env->GetFieldID(cls_provider, "mNativeHandle", "J");\r
-    if (!nativeHandle)\r
-    {\r
-        ThrowNSException(NS_ERROR, "Failed to get nativeHandle for Provider");\r
-        return NULL;\r
-    }\r
-    env->SetLongField(obj_provider, nativeHandle, pProvider);\r
-\r
-    env->DeleteLocalRef(cls_provider);\r
-    env->ReleaseStringUTFChars(jProviderId, providerId);\r
-    LOGD ("ConsumerService_GetProvider - OUT");\r
-    return obj_provider;\r
-}\r
-\r
-JNIEXPORT jobject JNICALL Java_org_iotivity_service_ns_consumer_ConsumerService_nativeGetMessage\r
-(JNIEnv *env, jobject jObj, jlong jMsgId)\r
-{\r
-    LOGI("JNIConsumerService: nativeGetMessage - IN");\r
-\r
-    OIC::Service::NSMessage *msg  =\r
-        OIC::Service::NSConsumerService::getInstance()->getMessage((uint64_t)jMsgId);\r
-    if (msg == nullptr)\r
-    {\r
-        ThrowNSException(NS_ERROR, "Message doesn't exist");\r
-        return NULL;\r
-    }\r
-\r
-    jobject obj_msg = getJavaMessage(env, msg);\r
-\r
-    LOGI("JNIConsumerService: nativeGetMessage - OUT");\r
-    return obj_msg;\r
-}\r
 JNIEXPORT void JNICALL Java_org_iotivity_service_ns_consumer_Provider_nativeSubscribe\r
 (JNIEnv *env, jobject jObj)\r
 {\r
@@ -1040,46 +950,6 @@ JNIEXPORT void JNICALL Java_org_iotivity_service_ns_consumer_Provider_nativeSubs
     return;\r
 }\r
 \r
-JNIEXPORT void JNICALL Java_org_iotivity_service_ns_consumer_Provider_nativeUnsubscribe\r
-(JNIEnv *env, jobject jObj)\r
-{\r
-    LOGD ("Provider_Unsubscribe - IN");\r
-\r
-    jclass providerClass = env->GetObjectClass(jObj);\r
-    if (!providerClass)\r
-    {\r
-        ThrowNSException(NS_ERROR, "Failed to Get ObjectClass for Provider");\r
-        return ;\r
-    }\r
-\r
-    jfieldID nativeHandle = env->GetFieldID(providerClass, "mNativeHandle", "J");\r
-    if (!nativeHandle)\r
-    {\r
-        ThrowNSException(NS_ERROR, "Failed to get nativeHandle for Provider");\r
-        return ;\r
-    }\r
-    jlong jProvider = env->GetLongField(jObj, nativeHandle);\r
-    if (jProvider)\r
-    {\r
-        LOGD ("calling unSubscribe on mNativeHandle");\r
-        OIC::Service::NSProvider *provider = (OIC::Service::NSProvider *) (jProvider);\r
-        provider->unSubscribe();\r
-    }\r
-    else\r
-    {\r
-        OIC::Service::NSProvider *provider = getNativeProvider(env, jObj);\r
-        if (provider == nullptr)\r
-        {\r
-            ThrowNSException(NS_ERROR, "Provider with Given Id doesn't exist");\r
-            return;\r
-        }\r
-        LOGD ("calling unSubscribe on ProviderID");\r
-        provider->unSubscribe();\r
-    }\r
-    LOGD ("Provider_Unsubscribe - IN");\r
-    return;\r
-}\r
-\r
 JNIEXPORT void JNICALL Java_org_iotivity_service_ns_consumer_Provider_nativeSendSyncInfo\r
 (JNIEnv *env, jobject jObj, jlong jMessageId, jint jSyncType)\r
 {\r
@@ -1113,7 +983,7 @@ JNIEXPORT void JNICALL Java_org_iotivity_service_ns_consumer_Provider_nativeSend
     {\r
         LOGD ("calling SendSyncInfo on mNativeHandle");\r
         OIC::Service::NSProvider *provider = (OIC::Service::NSProvider *) (jProvider);\r
-        provider->SendSyncInfo(messageId, (OIC::Service::NSSyncInfo::NSSyncType)jSyncType);\r
+        provider->sendSyncInfo(messageId, (OIC::Service::NSSyncInfo::NSSyncType)jSyncType);\r
     }\r
     else\r
     {\r
@@ -1124,7 +994,7 @@ JNIEXPORT void JNICALL Java_org_iotivity_service_ns_consumer_Provider_nativeSend
             return;\r
         }\r
         LOGD ("calling SendSyncInfo on ProviderID");\r
-        provider->SendSyncInfo(messageId, (OIC::Service::NSSyncInfo::NSSyncType)jSyncType);\r
+        provider->sendSyncInfo(messageId, (OIC::Service::NSSyncInfo::NSSyncType)jSyncType);\r
     }\r
     LOGD ("Provider_SendSyncInfo - OUT");\r
     return;\r
@@ -1132,10 +1002,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_service_ns_consumer_Provider_nativeSend
 \r
 \r
 JNIEXPORT void JNICALL Java_org_iotivity_service_ns_consumer_Provider_nativeSetListener\r
-(JNIEnv *env, jobject jObj, jobject jPostListener, jobject jSyncListener)\r
+(JNIEnv *env, jobject jObj, jobject jAcceptListener, jobject jPostListener, jobject jSyncListener)\r
 {\r
     LOGD ("Provider_SetListener - IN");\r
-    if (!jPostListener || !jSyncListener)\r
+    if (!jPostListener || !jSyncListener || !jAcceptListener)\r
     {\r
         ThrowNSException(NS_ERROR, "Listener cannot be null");\r
         return ;\r
@@ -1158,6 +1028,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_service_ns_consumer_Provider_nativeSetL
     if (jProvider)\r
     {\r
         LOGD ("calling SetListener on mNativeHandle");\r
+        if (g_obj_acceptListener != NULL)\r
+        {\r
+            env->DeleteGlobalRef(g_obj_acceptListener);\r
+        }\r
         if (g_obj_postListener != NULL)\r
         {\r
             env->DeleteGlobalRef(g_obj_postListener);\r
@@ -1166,11 +1040,12 @@ JNIEXPORT void JNICALL Java_org_iotivity_service_ns_consumer_Provider_nativeSetL
         {\r
             env->DeleteGlobalRef(g_obj_syncListener);\r
         }\r
+        g_obj_acceptListener = (jobject) env->NewGlobalRef(jAcceptListener);\r
         g_obj_postListener = (jobject) env->NewGlobalRef(jPostListener);\r
         g_obj_syncListener = (jobject) env->NewGlobalRef(jSyncListener);\r
 \r
         OIC::Service::NSProvider *provider = (OIC::Service::NSProvider *) (jProvider);\r
-        provider->setListener(onMessagePosted, onSyncInfoReceived);\r
+        provider->setListener(onProviderState, onMessagePosted, onSyncInfoReceived);\r
     }\r
     else\r
     {\r
@@ -1181,6 +1056,10 @@ JNIEXPORT void JNICALL Java_org_iotivity_service_ns_consumer_Provider_nativeSetL
             return;\r
         }\r
         LOGD ("calling SetListener on ProviderID");\r
+        if (g_obj_acceptListener != NULL)\r
+        {\r
+            env->DeleteGlobalRef(g_obj_acceptListener);\r
+        }\r
         if (g_obj_postListener != NULL)\r
         {\r
             env->DeleteGlobalRef(g_obj_postListener);\r
@@ -1189,22 +1068,71 @@ JNIEXPORT void JNICALL Java_org_iotivity_service_ns_consumer_Provider_nativeSetL
         {\r
             env->DeleteGlobalRef(g_obj_syncListener);\r
         }\r
+        g_obj_acceptListener = (jobject) env->NewGlobalRef(jAcceptListener);\r
         g_obj_postListener = (jobject) env->NewGlobalRef(jPostListener);\r
         g_obj_syncListener = (jobject) env->NewGlobalRef(jSyncListener);\r
 \r
-        provider->setListener(onMessagePosted, onSyncInfoReceived);\r
+        provider->setListener(onProviderState, onMessagePosted, onSyncInfoReceived);\r
     }\r
     LOGD ("Provider_SetListener - OUT");\r
     return;\r
 }\r
 \r
-JNIEXPORT jint JNICALL Java_org_iotivity_service_ns_consumer_Provider_nativeSelectInterestTopics\r
+JNIEXPORT jobject JNICALL Java_org_iotivity_service_ns_consumer_Provider_nativeGetTopicList\r
+(JNIEnv *env, jobject jObj)\r
+{\r
+    LOGD("Provider_nativeGetTopicList - IN");\r
+    jclass providerClass = env->GetObjectClass(jObj);\r
+    if (!providerClass)\r
+    {\r
+        ThrowNSException(NS_ERROR, "Failed to Get ObjectClass for Provider");\r
+        return NULL;\r
+    }\r
+\r
+    jfieldID nativeHandle = env->GetFieldID(providerClass, "mNativeHandle", "J");\r
+    if (!nativeHandle)\r
+    {\r
+        ThrowNSException(NS_ERROR, "Failed to get nativeHandle for Provider");\r
+        return NULL;\r
+    }\r
+    jlong jProvider = env->GetLongField(jObj, nativeHandle);\r
+    OIC::Service::NSTopicsList *topicList;\r
+    if (jProvider)\r
+    {\r
+        LOGD ("calling subscribe on mNativeHandle");\r
+        OIC::Service::NSProvider *provider = (OIC::Service::NSProvider *) (jProvider);\r
+        topicList = provider->getTopicList();\r
+    }\r
+    else\r
+    {\r
+        OIC::Service::NSProvider *provider = getNativeProvider(env, jObj);\r
+        if (provider == nullptr)\r
+        {\r
+            ThrowNSException(NS_ERROR, "Provider with Given Id doesn't exist");\r
+            return NULL;\r
+        }\r
+        LOGD ("calling subscribe on ProviderID");\r
+        topicList = provider->getTopicList();\r
+    }\r
+    if (topicList == nullptr)\r
+    {\r
+        ThrowNSException(NS_ERROR, "Topic List doesn't exist");\r
+        return NULL;\r
+    }\r
+\r
+    jobject obj_topicList = getJavaTopicsList(env, topicList);\r
+\r
+    LOGD("Provider_nativeGetTopicList - OUT");\r
+    return obj_topicList;\r
+}\r
+\r
+JNIEXPORT jint JNICALL Java_org_iotivity_service_ns_consumer_Provider_nativeUpdateTopicList\r
 (JNIEnv *env, jobject jObj, jobject jTopicsList)\r
 {\r
-    LOGD("Provider_SelectInterestTopics -IN");\r
+    LOGD("Provider_nativeUpdateTopicList -IN");\r
     if (!jTopicsList)\r
     {\r
-        LOGI("Fail to select Interest Topics - Topic List is null");\r
+        LOGI("Fail to update Interest Topics - Topic List is null");\r
         ThrowNSException(NS_ERROR, "TopicList cannot be null");\r
         return (jint) OIC::Service::NSResult::ERROR;\r
     }\r
@@ -1234,7 +1162,7 @@ JNIEXPORT jint JNICALL Java_org_iotivity_service_ns_consumer_Provider_nativeSele
     {\r
         LOGD ("calling subscribe on mNativeHandle");\r
         OIC::Service::NSProvider *provider = (OIC::Service::NSProvider *) (jProvider);\r
-        result = provider->selectInterestTopics(nsTopicsList);\r
+        result = provider->updateTopicList(nsTopicsList);\r
     }\r
     else\r
     {\r
@@ -1245,15 +1173,95 @@ JNIEXPORT jint JNICALL Java_org_iotivity_service_ns_consumer_Provider_nativeSele
             return (jint) OIC::Service::NSResult::ERROR;\r
         }\r
         LOGD ("calling subscribe on ProviderID");\r
-        result = provider->selectInterestTopics(nsTopicsList);\r
+        result = provider->updateTopicList(nsTopicsList);\r
     }\r
     if (result !=  OIC::Service::NSResult::OK)\r
     {\r
-        LOGI("Fail to select Interest Topics");\r
+        LOGI("Fail to Update Interest Topics");\r
     }\r
-    LOGD("Provider_SelectInterestTopics -OUT");\r
+    LOGD("Provider_nativeUpdateTopicList -OUT");\r
     return (jint) result;\r
 }\r
+\r
+JNIEXPORT jobject JNICALL Java_org_iotivity_service_ns_consumer_Provider_nativeGetProviderState\r
+(JNIEnv *env, jobject jObj)\r
+{\r
+    LOGD("Provider_nativeGetProviderState - IN");\r
+    jclass providerClass = env->GetObjectClass(jObj);\r
+    if (!providerClass)\r
+    {\r
+        ThrowNSException(NS_ERROR, "Failed to Get ObjectClass for Provider");\r
+        return NULL;\r
+    }\r
+\r
+    jfieldID nativeHandle = env->GetFieldID(providerClass, "mNativeHandle", "J");\r
+    if (!nativeHandle)\r
+    {\r
+        ThrowNSException(NS_ERROR, "Failed to get nativeHandle for Provider");\r
+        return NULL;\r
+    }\r
+    jlong jProvider = env->GetLongField(jObj, nativeHandle);\r
+    OIC::Service::NSProviderState state;\r
+    if (jProvider)\r
+    {\r
+        LOGD ("calling getProviderState on mNativeHandle");\r
+        OIC::Service::NSProvider *provider = (OIC::Service::NSProvider *) (jProvider);\r
+        state = provider->getProviderState();\r
+    }\r
+    else\r
+    {\r
+        OIC::Service::NSProvider *provider = getNativeProvider(env, jObj);\r
+        if (provider == nullptr)\r
+        {\r
+            ThrowNSException(NS_ERROR, "Provider with Given Id doesn't exist");\r
+            return NULL;\r
+        }\r
+        LOGD ("calling getProviderState on ProviderID");\r
+        state = provider->getProviderState();\r
+    }\r
+    jobject obj_state = getJavaProviderState(env,state);\r
+\r
+    LOGD("Provider_nativeGetProviderState - OUT");\r
+    return obj_state;\r
+}\r
+\r
+JNIEXPORT jboolean JNICALL Java_org_iotivity_service_ns_consumer_Provider_nativeIsSubscribed\r
+(JNIEnv *env, jobject jObj)\r
+{\r
+    LOGD("nativeIsSubscribed - IN");\r
+    jclass providerClass = env->GetObjectClass(jObj);\r
+    if (!providerClass)\r
+    {\r
+        ThrowNSException(NS_ERROR, "Failed to Get ObjectClass for Provider");\r
+        return (jboolean)false;\r
+    }\r
+\r
+    jfieldID nativeHandle = env->GetFieldID(providerClass, "mNativeHandle", "J");\r
+    if (!nativeHandle)\r
+    {\r
+        ThrowNSException(NS_ERROR, "Failed to get nativeHandle for Provider");\r
+        return (jboolean)false;\r
+    }\r
+    jlong jProvider = env->GetLongField(jObj, nativeHandle);\r
+    if (jProvider)\r
+    {\r
+        LOGD ("calling isSubscribe on mNativeHandle");\r
+        OIC::Service::NSProvider *provider = (OIC::Service::NSProvider *) (jProvider);\r
+        return (jboolean) provider->isSubscribed();\r
+    }\r
+    else\r
+    {\r
+        OIC::Service::NSProvider *provider = getNativeProvider(env, jObj);\r
+        if (provider == nullptr)\r
+        {\r
+            ThrowNSException(NS_ERROR, "Provider with Given Id doesn't exist");\r
+            return (jboolean)false;\r
+        }\r
+        LOGD ("calling isSubscribe on ProviderID");\r
+        return (jboolean) provider->isSubscribed();\r
+    }\r
+}\r
+\r
 // JNI OnLoad\r
 JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *jvm, void *reserved)\r
 {\r
@@ -1378,17 +1386,17 @@ JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *jvm, void *reserved)
         return JNI_ERR;\r
     }\r
 \r
-    jclass localResponse = env->FindClass(\r
-                               "org/iotivity/service/ns/consumer/ConsumerService$Response");\r
-    if (!localResponse)\r
+    jclass localProviderState = env->FindClass(\r
+                               "org/iotivity/service/ns/consumer/Provider$ProviderState");\r
+    if (!localProviderState)\r
     {\r
-        LOGE("Failed to get localResponse  Type class");\r
+        LOGE("Failed to get localProviderState  Type class");\r
         return JNI_ERR;\r
     }\r
-    g_cls_Response = (jclass) (env->NewGlobalRef(localResponse));\r
-    if (!g_cls_Response)\r
+    g_cls_ProviderState = (jclass) (env->NewGlobalRef(localProviderState));\r
+    if (!g_cls_ProviderState)\r
     {\r
-        LOGE("Failed to set Global Response Type reference");\r
+        LOGE("Failed to set Global ProviderState Type reference");\r
         return JNI_ERR;\r
     }\r
 \r
@@ -1412,7 +1420,7 @@ JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *jvm, void *reserved)
     env->DeleteLocalRef(localMediaContents);\r
     env->DeleteLocalRef(localTopicState);\r
     env->DeleteLocalRef(localMessageType);\r
-    env->DeleteLocalRef(localResponse);\r
+    env->DeleteLocalRef(localProviderState);\r
     env->DeleteLocalRef(localTopic);\r
     env->DeleteLocalRef(localTopicsList);\r
 \r
@@ -1437,7 +1445,7 @@ JNIEXPORT void JNICALL JNI_OnUnload(JavaVM *jvm, void *reserved)
     env->DeleteGlobalRef(g_cls_MediaContents);\r
     env->DeleteGlobalRef(g_cls_TopicState);\r
     env->DeleteGlobalRef(g_cls_Message_Type);\r
-    env->DeleteGlobalRef(g_cls_Response);\r
+    env->DeleteGlobalRef(g_cls_ProviderState);\r
     env->DeleteGlobalRef(g_cls_Topic);\r
     env->DeleteGlobalRef(g_cls_TopicsList);\r
 }\r
index 4fae3eb..97ae3d8 100755 (executable)
@@ -31,10 +31,10 @@ extern "C" {
 /*\r
  * Class:     org_iotivity_service_ns_consumer_ConsumerService\r
  * Method:    nativeStart\r
- * Signature: (Lorg/iotivity/service/ns/consumer/ConsumerService/OnProviderDiscoveredListner;Lorg/iotivity/service/ns/consumer/ConsumerService/OnSubscriptionAcceptedListener;)V\r
+ * Signature: (Lorg/iotivity/service/ns/consumer/ConsumerService/OnProviderDiscoveredListener;)V\r
  */\r
 JNIEXPORT void JNICALL Java_org_iotivity_service_ns_consumer_ConsumerService_nativeStart\r
-(JNIEnv *, jobject, jobject, jobject);\r
+(JNIEnv *, jobject, jobject);\r
 \r
 /*\r
  * Class:     org_iotivity_service_ns_consumer_ConsumerService\r
@@ -62,22 +62,6 @@ JNIEXPORT void JNICALL Java_org_iotivity_service_ns_consumer_ConsumerService_nat
 (JNIEnv *, jobject);\r
 \r
 /*\r
- * Class:     org_iotivity_service_ns_consumer_ConsumerService\r
- * Method:    nativeGetProvider\r
- * Signature: (Ljava/lang/String;)Lorg/iotivity/service/ns/consumer/Provider;\r
- */\r
-JNIEXPORT jobject JNICALL Java_org_iotivity_service_ns_consumer_ConsumerService_nativeGetProvider\r
-(JNIEnv *, jobject, jstring);\r
-\r
-/*\r
- * Class:     org_iotivity_service_ns_consumer_ConsumerService\r
- * Method:    nativeGetMessage\r
- * Signature: (J)Lorg/iotivity/service/ns/common/Message;\r
- */\r
-JNIEXPORT jobject JNICALL Java_org_iotivity_service_ns_consumer_ConsumerService_nativeGetMessage\r
-(JNIEnv *, jobject, jlong);\r
-\r
-/*\r
  * Class:     org_iotivity_service_ns_consumer_Provider\r
  * Method:    nativeSubscribe\r
  * Signature: ()V\r
@@ -87,14 +71,6 @@ JNIEXPORT void JNICALL Java_org_iotivity_service_ns_consumer_Provider_nativeSubs
 \r
 /*\r
  * Class:     org_iotivity_service_ns_consumer_Provider\r
- * Method:    nativeUnsubscribe\r
- * Signature: ()V\r
- */\r
-JNIEXPORT void JNICALL Java_org_iotivity_service_ns_consumer_Provider_nativeUnsubscribe\r
-(JNIEnv *, jobject);\r
-\r
-/*\r
- * Class:     org_iotivity_service_ns_consumer_Provider\r
  * Method:    nativeSendSyncInfo\r
  * Signature: (JI)V\r
  */\r
@@ -104,19 +80,43 @@ JNIEXPORT void JNICALL Java_org_iotivity_service_ns_consumer_Provider_nativeSend
 /*\r
  * Class:     org_iotivity_service_ns_consumer_Provider\r
  * Method:    nativeSetListener\r
- * Signature: (Lorg/iotivity/service/ns/consumer/Provider/OnMessageReceivedListner;Lorg/iotivity/service/ns/consumer/Provider/OnSyncInfoReceivedListner;)V\r
+ * Signature: (Lorg/iotivity/service/ns/consumer/Provider/OnProviderStateListener;Lorg/iotivity/service/ns/consumer/Provider/OnMessageReceivedListner;Lorg/iotivity/service/ns/consumer/Provider/OnSyncInfoReceivedListner;)V\r
  */\r
 JNIEXPORT void JNICALL Java_org_iotivity_service_ns_consumer_Provider_nativeSetListener\r
-(JNIEnv *, jobject, jobject, jobject);\r
+(JNIEnv *, jobject, jobject, jobject, jobject);\r
 \r
 /*\r
  * Class:     org_iotivity_service_ns_consumer_Provider\r
- * Method:    nativeSelectInterestTopics\r
+ * Method:    nativeGetTopicList\r
+ * Signature: ()Lorg/iotivity/service/ns/common/TopicsList;\r
+ */\r
+JNIEXPORT jobject JNICALL Java_org_iotivity_service_ns_consumer_Provider_nativeGetTopicList\r
+(JNIEnv *, jobject);\r
+\r
+/*\r
+ * Class:     org_iotivity_service_ns_consumer_Provider\r
+ * Method:    nativeUpdateTopicList\r
  * Signature: (Lorg/iotivity/service/ns/common/TopicsList;)I\r
  */\r
-JNIEXPORT jint JNICALL Java_org_iotivity_service_ns_consumer_Provider_nativeSelectInterestTopics\r
+JNIEXPORT jint JNICALL Java_org_iotivity_service_ns_consumer_Provider_nativeUpdateTopicList\r
 (JNIEnv *, jobject, jobject);\r
 \r
+/*\r
+ * Class:     org_iotivity_service_ns_consumer_Provider\r
+ * Method:    nativeGetProviderState\r
+ * Signature: ()Lorg/iotivity/service/ns/consumer/Provider$ProviderState;\r
+ */\r
+JNIEXPORT jobject JNICALL Java_org_iotivity_service_ns_consumer_Provider_nativeGetProviderState\r
+(JNIEnv *, jobject);\r
+\r
+/*\r
+ * Class:     org_iotivity_service_ns_consumer_Provider\r
+ * Method:    nativeIsSubscribed\r
+ * Signature: ()Z\r
+ */\r
+JNIEXPORT jboolean JNICALL Java_org_iotivity_service_ns_consumer_Provider_nativeIsSubscribed\r
+(JNIEnv *, jobject);\r
+\r
 #ifdef __cplusplus\r
 }\r
 #endif\r
index f8ee789..f1a744a 100644 (file)
@@ -242,7 +242,7 @@ OIC::Service::NSMessage *getNativeMessage(JNIEnv *env, jobject jMsg)
     LOGD("iconImage: %s\n", iconImage);
 
     OIC::Service::NSMediaContents *media = new OIC::Service::NSMediaContents(std::string(iconImage));
-    OIC::Service::NSMessage *nsMsg = OIC::Service::NSProviderService::getInstance()->CreateMessage();
+    OIC::Service::NSMessage *nsMsg = OIC::Service::NSProviderService::getInstance()->createMessage();
 
     nsMsg->setType(type);
     nsMsg->setTime(std::string(time));
@@ -286,6 +286,181 @@ OIC::Service::NSMessage *getNativeMessage(JNIEnv *env, jobject jMsg)
 
 }
 
+jobject getJavaMessageType(JNIEnv *env, OIC::Service::NSMessage::NSMessageType type)
+{
+    LOGD ("JNIProviderService: getJavaMessageType - IN");
+    switch (type)
+    {
+        case OIC::Service::NSMessage::NSMessageType::NS_MESSAGE_ALERT:
+            {
+                static jfieldID fieldID = env->GetStaticFieldID(g_cls_Message_Type,
+                                          "ALERT", "Lorg/iotivity/service/ns/common/Message$MessageType;");
+                return env->GetStaticObjectField(g_cls_Message_Type, fieldID);
+            }
+        case OIC::Service::NSMessage::NSMessageType::NS_MESSAGE_NOTICE:
+            {
+                static jfieldID fieldID = env->GetStaticFieldID(g_cls_Message_Type,
+                                          "NOTICE", "Lorg/iotivity/service/ns/common/Message$MessageType;");
+                return env->GetStaticObjectField(g_cls_Message_Type, fieldID);
+            }
+        case OIC::Service::NSMessage::NSMessageType::NS_MESSAGE_EVENT:
+            {
+                static jfieldID fieldID = env->GetStaticFieldID(g_cls_Message_Type,
+                                          "EVENT", "Lorg/iotivity/service/ns/common/Message$MessageType;");
+                return env->GetStaticObjectField(g_cls_Message_Type, fieldID);
+            }
+        case OIC::Service::NSMessage::NSMessageType::NS_MESSAGE_INFO:
+            {
+                static jfieldID fieldID = env->GetStaticFieldID(g_cls_Message_Type,
+                                          "INFO", "Lorg/iotivity/service/ns/common/Message$MessageType;");
+                return env->GetStaticObjectField(g_cls_Message_Type, fieldID);
+            }
+        default:
+            return NULL;
+    }
+    LOGD ("JNIProviderService: getJavaMessageType - OUT");
+    return NULL;
+}
+
+jobject getJavaMessage(JNIEnv *env, OIC::Service::NSMessage *message)
+{
+    LOGD ("JNIProviderService: getJavaMessage - IN");
+
+    LOGD ("id : %llu\n", message->getMessageId());
+    LOGD ("title : %s\n", message->getTitle().c_str());
+    LOGD ("content : %s\n", message->getContentText().c_str());
+    LOGD ("source : %s\n", message->getSourceName().c_str());
+
+    jlong jMessageId = (jlong) message->getMessageId();
+    jstring jProviderId = env->NewStringUTF(message->getProviderId().c_str());
+    jstring jTitle = env->NewStringUTF(message->getTitle().c_str());
+    jstring jContentText = env->NewStringUTF(message->getContentText().c_str());
+    jstring jSourceName = env->NewStringUTF(message->getSourceName().c_str());
+    jstring jTopic = env->NewStringUTF(message->getTopic().c_str());
+
+    jstring jTime = env->NewStringUTF(message->getTime().c_str());
+    jlong jTTL = (jlong) message->getTTL();
+
+    jlong pMessage = (long) message;
+
+    jclass cls_message = (jclass) (env->NewLocalRef(g_cls_Message));
+    if (!cls_message)
+    {
+        LOGE ("Failed to Get ObjectClass for Message");
+        return NULL ;
+    }
+    jmethodID mid_message = env->GetMethodID(
+                                cls_message, "<init>",
+                                "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V");
+    if (!mid_message)
+    {
+        LOGE ("Failed to Get MethodID for Message<init>");
+        return NULL;
+    }
+    jobject obj_message = env->NewObject(cls_message, mid_message,
+                                         jTitle, jContentText, jSourceName);
+    if (!obj_message)
+    {
+        LOGE ("Failed to Get Java Object for Message");
+        return NULL;
+    }
+    jfieldID fid_nativeHandle = env->GetFieldID(cls_message, "mNativeHandle", "J");
+    if (!fid_nativeHandle)
+    {
+        LOGE("Failed to get nativeHandle for Message");
+        return NULL;
+    }
+    env->SetLongField(obj_message, fid_nativeHandle, pMessage);
+
+    jfieldID fid_messageId = env->GetFieldID(cls_message, "mMessageId", "J");
+    if (!fid_messageId)
+    {
+        LOGE("Failed to get field MessageID for Message");
+        return NULL;
+    }
+    env->SetLongField(obj_message, fid_messageId, jMessageId);
+
+    jfieldID fid_providerId = env->GetFieldID(cls_message, "mProviderId", "Ljava/lang/String;");
+    if (!fid_providerId)
+    {
+        LOGE("Failed to get field ProviderID for Message");
+        return NULL;
+    }
+    env->SetObjectField(obj_message, fid_providerId, jProviderId);
+
+    jfieldID fid_time = env->GetFieldID(cls_message, "mTime", "Ljava/lang/String;");
+    if (!fid_time)
+    {
+        LOGE("Failed to get field Time for Message");
+        return NULL;
+    }
+    env->SetObjectField(obj_message, fid_time, jTime);
+
+    jfieldID fid_ttl = env->GetFieldID(cls_message, "mTTL", "J");
+    if (!fid_ttl)
+    {
+        LOGE("Failed to get field TTL for Message");
+        return NULL;
+    }
+    env->SetLongField(obj_message, fid_ttl, jTTL);
+
+    jfieldID fid_topic = env->GetFieldID(cls_message, "mTopic", "Ljava/lang/String;");
+    if (!fid_topic)
+    {
+        LOGE("Failed to get mTopic for Message");
+        return NULL;
+    }
+    env->SetObjectField(obj_message, fid_topic, jTopic);
+
+    OIC::Service::NSMediaContents *mediaCont = message->getMediaContents();
+    if (mediaCont != nullptr)
+    {
+        jstring jIconImage = env->NewStringUTF(mediaCont->getIconImage().c_str());
+        jclass cls_mediaContents = (jclass) (env->NewLocalRef(g_cls_MediaContents));
+        if (!cls_mediaContents)
+        {
+            LOGE ("Failed to Get ObjectClass for MediaContents");
+            return NULL;
+        }
+        jmethodID mid_mediaContents = env->GetMethodID(
+                                          cls_mediaContents, "<init>", "(Ljava/lang/String;)V");
+        if (!mid_mediaContents)
+        {
+            LOGE ("Failed to Get MethodID for MediaContents<init>");
+            return NULL;
+        }
+        jobject obj_mediaContents = env->NewObject(cls_mediaContents, mid_mediaContents,
+                                    jIconImage);
+
+        jfieldID fid_mediaContents = env->GetFieldID(cls_message, "mMediaContents",
+                                     "Lorg/iotivity/service/ns/common/MediaContents;");
+        if (!fid_mediaContents)
+        {
+            LOGE("Failed to get field mediaContents for Message");
+            return NULL;
+        }
+        env->SetObjectField(obj_message, fid_mediaContents, obj_mediaContents);
+
+    }
+
+    jobject jType = getJavaMessageType(env, message->getType());
+    if (jType)
+    {
+        jfieldID fid_type = env->GetFieldID(cls_message, "mType",
+                                            "Lorg/iotivity/service/ns/common/Message$MessageType;");
+        if (!fid_type)
+        {
+            LOGE("Failed to get field Type for Message");
+            return NULL;
+        }
+        env->SetObjectField(obj_message, fid_type, jType);
+    }
+
+    env->DeleteLocalRef(cls_message);
+    LOGD ("JNIProviderService: getJavaMessage - OUT");
+    return obj_message;
+}
+
 jobject getJavaTopicState(JNIEnv *env, OIC::Service::NSTopic::NSTopicState nsState)
 {
     LOGD("JNIProviderService: getJavaTopicState - IN");
@@ -540,7 +715,7 @@ void onSyncInfoListenerCb(OIC::Service::NSSyncInfo *sync)
     }
     jmethodID mid = env->GetMethodID(
                         cls,
-                        "onSyncInfoReceived",
+                        "onMessageSynchronized",
                         "(Lorg/iotivity/service/ns/common/SyncInfo;)V");
     if (!mid)
     {
@@ -559,9 +734,8 @@ void onSyncInfoListenerCb(OIC::Service::NSSyncInfo *sync)
 
 }
 
-JNIEXPORT jint JNICALL Java_org_iotivity_service_ns_provider_ProviderService_nativeStart(
-    JNIEnv *env, jobject jObj, jboolean jPolicy, jobject jSubscriptionListener,
-    jobject jSyncListener)
+JNIEXPORT jint JNICALL Java_org_iotivity_service_ns_provider_ProviderService_nativeStart
+(JNIEnv *env, jobject jObj, jobject jSubscriptionListener, jobject jSyncListener, jboolean jPolicy, jstring jUserInfo)
 {
     LOGD("JNIProviderService: nativeStart - IN");
     if (!jSubscriptionListener || !jSyncListener)
@@ -588,9 +762,15 @@ JNIEXPORT jint JNICALL Java_org_iotivity_service_ns_provider_ProviderService_nat
     OIC::Service::NSProviderService::ProviderConfig cfg;
     cfg.m_subscribeRequestCb =  onSubscribeListenerCb;
     cfg.m_syncInfoCb =  onSyncInfoListenerCb;
-    cfg.policy = (bool) jPolicy;
+    cfg.subControllability = (bool) jPolicy;
+    if (!jUserInfo)
+    {
+        const char *info = env->GetStringUTFChars( jUserInfo, NULL);
+        std::string userInfo(info);
+        cfg.userInfo = userInfo;
+    }
 
-    OIC::Service::NSResult result = OIC::Service::NSProviderService::getInstance()->Start(cfg);
+    OIC::Service::NSResult result = OIC::Service::NSProviderService::getInstance()->start(cfg);
     if (result != OIC::Service::NSResult::OK)
     {
         LOGE("Fail to start NSProviderService");
@@ -601,12 +781,12 @@ JNIEXPORT jint JNICALL Java_org_iotivity_service_ns_provider_ProviderService_nat
     return (jint) result;
 }
 
-JNIEXPORT jint JNICALL Java_org_iotivity_service_ns_provider_ProviderService_nativeStop(
-    JNIEnv *env, jobject jObj)
+JNIEXPORT jint JNICALL Java_org_iotivity_service_ns_provider_ProviderService_nativeStop
+(JNIEnv *env, jobject jObj)
 {
     LOGD("JNIProviderService: nativeStop - IN");
 
-    OIC::Service::NSResult result = OIC::Service::NSProviderService::getInstance()->Stop();
+    OIC::Service::NSResult result = OIC::Service::NSProviderService::getInstance()->stop();
     if (result !=  OIC::Service::NSResult::OK)
     {
         LOGD("Fail to stop NSProvider service");
@@ -622,8 +802,8 @@ JNIEXPORT jint JNICALL Java_org_iotivity_service_ns_provider_ProviderService_nat
     return (jint) result;
 }
 
-JNIEXPORT jint JNICALL Java_org_iotivity_service_ns_provider_ProviderService_nativeSendMessage(
-    JNIEnv *env, jobject jObj, jobject jMsg)
+JNIEXPORT jint JNICALL Java_org_iotivity_service_ns_provider_ProviderService_nativeSendMessage
+(JNIEnv *env, jobject jObj, jobject jMsg)
 {
     LOGD("JNIProviderService: nativeSendMessage - IN");
     if (!jMsg)
@@ -639,7 +819,7 @@ JNIEXPORT jint JNICALL Java_org_iotivity_service_ns_provider_ProviderService_nat
         return (jint) OIC::Service::NSResult::ERROR;
     }
 
-    OIC::Service::NSResult result = OIC::Service::NSProviderService::getInstance()->SendMessage(nsMsg);
+    OIC::Service::NSResult result = OIC::Service::NSProviderService::getInstance()->sendMessage(nsMsg);
     if (result !=  OIC::Service::NSResult::OK)
     {
         LOGD("Fail to send NSProvider Message");
@@ -648,19 +828,39 @@ JNIEXPORT jint JNICALL Java_org_iotivity_service_ns_provider_ProviderService_nat
     return (jint) result;
 }
 
-JNIEXPORT void JNICALL Java_org_iotivity_service_ns_provider_ProviderService_nativeSendSyncInfo(
-    JNIEnv *env, jobject jObj, jlong messageId , jint syncState)
+JNIEXPORT void JNICALL Java_org_iotivity_service_ns_provider_ProviderService_nativeSendSyncInfo
+(JNIEnv *env, jobject jObj, jlong messageId , jint syncState)
 {
     LOGD("JNIProviderService: nativeSendSyncInfo - IN");
-    OIC::Service::NSProviderService::getInstance()->SendSyncInfo( messageId,
+    OIC::Service::NSProviderService::getInstance()->sendSyncInfo( messageId,
             (OIC::Service::NSSyncInfo::NSSyncType) syncState);
     LOGD("JNIProviderService: nativeSendSyncInfo - OUT");
     return;
 }
 
-JNIEXPORT jint JNICALL
-Java_org_iotivity_service_ns_provider_ProviderService_nativeEnableRemoteService(JNIEnv *env,
-        jobject jObj, jstring jstr)
+JNIEXPORT jobject JNICALL Java_org_iotivity_service_ns_provider_ProviderService_nativeCreateMessage
+(JNIEnv *env, jobject jObj)
+{
+    LOGD("JNIProviderService: nativeCreateMessage - IN");
+    OIC::Service::NSMessage* message =
+                      OIC::Service::NSProviderService::getInstance()->createMessage();
+    if(message == nullptr)
+    {
+        ThrowNSException(NS_ERROR, "Couldn't get Native Message");
+        return NULL;
+    }
+    jobject jMsg =  getJavaMessage(env, message);
+    if(!jMsg)
+    {
+        ThrowNSException(NS_ERROR, "Couldn't create Java Message");
+        return NULL;
+    }
+    LOGD("JNIProviderService: nativeCreateMessage - OUT");
+    return jMsg;
+}
+
+JNIEXPORT jint JNICALL Java_org_iotivity_service_ns_provider_ProviderService_nativeEnableRemoteService
+(JNIEnv *env,jobject jObj, jstring jstr)
 {
     LOGD("JNIProviderService: nativeEnableRemoteService - IN");
     if (!jstr)
@@ -672,7 +872,7 @@ Java_org_iotivity_service_ns_provider_ProviderService_nativeEnableRemoteService(
     const char *address = env->GetStringUTFChars( jstr, NULL);
     std::string servAddress(address);
     OIC::Service::NSResult result  =
-        OIC::Service::NSProviderService::getInstance()->EnableRemoteService(
+        OIC::Service::NSProviderService::getInstance()->enableRemoteService(
             servAddress);
     if (result !=  OIC::Service::NSResult::OK)
     {
@@ -683,9 +883,8 @@ Java_org_iotivity_service_ns_provider_ProviderService_nativeEnableRemoteService(
     return (jint) result;
 }
 
-JNIEXPORT jint JNICALL
-Java_org_iotivity_service_ns_provider_ProviderService_nativeDisableRemoteService(JNIEnv *env,
-        jobject jObj, jstring jstr)
+JNIEXPORT jint JNICALL Java_org_iotivity_service_ns_provider_ProviderService_nativeDisableRemoteService
+(JNIEnv *env,jobject jObj, jstring jstr)
 {
     LOGD("JNIProviderService: nativeDisableRemoteService - IN");
     if (!jstr)
@@ -697,7 +896,7 @@ Java_org_iotivity_service_ns_provider_ProviderService_nativeDisableRemoteService
     const char *address = env->GetStringUTFChars( jstr, NULL);
     std::string servAddress(address);
     OIC::Service::NSResult result  =
-        OIC::Service::NSProviderService::getInstance()->DisableRemoteService(
+        OIC::Service::NSProviderService::getInstance()->disableRemoteService(
             servAddress);
     if (result !=  OIC::Service::NSResult::OK)
     {
@@ -708,10 +907,10 @@ Java_org_iotivity_service_ns_provider_ProviderService_nativeDisableRemoteService
     return (jint) result;
 }
 
-JNIEXPORT jint JNICALL Java_org_iotivity_service_ns_provider_ProviderService_nativeAddTopic
+JNIEXPORT jint JNICALL Java_org_iotivity_service_ns_provider_ProviderService_nativeRegisterTopic
 (JNIEnv *env, jobject jObj, jstring jTopicName)
 {
-    LOGD("JNIProviderService: nativeAddTopic - IN");
+    LOGD("JNIProviderService: nativeRegisterTopic - IN");
     if (!jTopicName)
     {
         ThrowNSException(NS_ERROR, "Topic Name Can't be NULL");
@@ -719,20 +918,20 @@ JNIEXPORT jint JNICALL Java_org_iotivity_service_ns_provider_ProviderService_nat
     }
     const char *name = env->GetStringUTFChars( jTopicName, NULL);
     std::string topicName(name);
-    OIC::Service::NSResult result  = OIC::Service::NSProviderService::getInstance()->AddTopic(
+    OIC::Service::NSResult result  = OIC::Service::NSProviderService::getInstance()->registerTopic(
                                          topicName);
     if (result !=  OIC::Service::NSResult::OK)
     {
-        LOGE("Fail to Add Topic");
+        LOGE("Fail to Register Topic");
     }
     env->ReleaseStringUTFChars(jTopicName, name);
-    LOGD("JNIProviderService: nativeAddTopic - OUT");
+    LOGD("JNIProviderService: nativeRegisterTopic - OUT");
     return (jint) result;
 }
-JNIEXPORT jint JNICALL Java_org_iotivity_service_ns_provider_ProviderService_nativeDeleteTopic
+JNIEXPORT jint JNICALL Java_org_iotivity_service_ns_provider_ProviderService_nativeUnregisterTopic
 (JNIEnv *env, jobject jObj, jstring jTopicName)
 {
-    LOGD("JNIProviderService: nativeDeleteTopic - IN");
+    LOGD("JNIProviderService: nativeUnregisterTopic - IN");
     if (!jTopicName)
     {
         ThrowNSException(NS_ERROR, "Topic Name Can't be NULL");
@@ -740,24 +939,24 @@ JNIEXPORT jint JNICALL Java_org_iotivity_service_ns_provider_ProviderService_nat
     }
     const char *name = env->GetStringUTFChars( jTopicName, NULL);
     std::string topicName(name);
-    OIC::Service::NSResult result  = OIC::Service::NSProviderService::getInstance()->DeleteTopic(
+    OIC::Service::NSResult result  = OIC::Service::NSProviderService::getInstance()->unregisterTopic(
                                          topicName);
     if (result !=  OIC::Service::NSResult::OK)
     {
-        LOGE("Fail to Add Topic");
+        LOGE("Fail to Unregister Topic");
     }
     env->ReleaseStringUTFChars(jTopicName, name);
-    LOGD("JNIProviderService: nativeDeleteTopic - OUT");
+    LOGD("JNIProviderService: nativeUnregisterTopic - OUT");
     return (jint) result;
 }
 
-JNIEXPORT jobject JNICALL Java_org_iotivity_service_ns_provider_ProviderService_nativeGetTopics
+JNIEXPORT jobject JNICALL Java_org_iotivity_service_ns_provider_ProviderService_nativeGetRegisteredTopicList
 (JNIEnv *env, jobject jObj)
 {
-    LOGD("JNIProviderService: nativeGetTopics - IN");
+    LOGD("JNIProviderService: nativeGetRegisteredTopicList - IN");
 
     OIC::Service::NSTopicsList *topicList  =
-        OIC::Service::NSProviderService::getInstance()->GetTopics();
+        OIC::Service::NSProviderService::getInstance()->getRegisteredTopicList();
     if (topicList == nullptr)
     {
         ThrowNSException(NS_ERROR, "Topic List doesn't exist");
@@ -766,56 +965,36 @@ JNIEXPORT jobject JNICALL Java_org_iotivity_service_ns_provider_ProviderService_
 
     jobject obj_topicList = getJavaTopicsList(env, topicList);
 
-    LOGD("JNIProviderService: nativeGetTopics - OUT");
+    LOGD("JNIProviderService: nativeGetRegisteredTopicList - OUT");
     return obj_topicList;
 }
 
-JNIEXPORT jint JNICALL Java_org_iotivity_service_ns_provider_Consumer_nativeAcceptSubscription(
-    JNIEnv *env,  jobject jObj, jobject jConsumer, jboolean jAccepted)
+JNIEXPORT jint JNICALL Java_org_iotivity_service_ns_provider_Consumer_nativeAcceptSubscription
+(JNIEnv *env,  jobject jObj, jstring jConsumerId, jboolean jAccepted)
 {
     LOGD("JNIProviderService: nativeAcceptSubscription - IN");
-
-    jclass consumerClass =  env->GetObjectClass( jConsumer);
-    if (!consumerClass)
-    {
-        ThrowNSException(NS_ERROR, "Failed to Get ObjectClass for Consumer");
-        return (jint) OIC::Service::NSResult::ERROR;
-    }
-
-    // Consumer ID
-    jfieldID fid_id =  env->GetFieldID(consumerClass, "mConsumerId",  "Ljava/lang/String;");
-    if (fid_id == NULL)
-    {
-        LOGE("Error: jfieldID for mConsumerId  is null");
-        ThrowNSException(NS_ERROR, "ConsumerId not found");
-        return (jint) OIC::Service::NSResult::ERROR;
-    }
-
-    jstring jconId = (jstring)env->GetObjectField( jConsumer, fid_id);
-    if (!jconId)
+    if (!jConsumerId)
     {
-        ThrowNSException(NS_ERROR, "ProviderId cannot be null");
+        ThrowNSException(NS_ERROR, "ConsumerId Can't be NULL");
         return (jint) OIC::Service::NSResult::ERROR;
     }
-    const char *conId = env->GetStringUTFChars( jconId, NULL);
-    std::string consumerId(conId);
-    env->ReleaseStringUTFChars(jconId, conId);
-
+    const char *id = env->GetStringUTFChars( jConsumerId, NULL);
+    std::string consumerId(id);
     LOGD("Consumer ID: %s\n", consumerId.c_str());
 
     OIC::Service::NSConsumer *consumer =
         OIC::Service::NSProviderService::getInstance()->getConsumer(consumerId);
     if (consumer)
-        return (jint) consumer->acceptSubscription(consumer,  (bool)jAccepted);
+        return (jint) consumer->acceptSubscription((bool)jAccepted);
 
     LOGE("Couldn't find consumer");
     LOGD("JNIProviderService: nativeAcceptSubscription - OUT");
     return (jint) OIC::Service::NSResult::ERROR;
 }
-JNIEXPORT jint JNICALL Java_org_iotivity_service_ns_provider_Consumer_nativeSelectTopic
+JNIEXPORT jint JNICALL Java_org_iotivity_service_ns_provider_Consumer_nativeSetConsumerTopic
 (JNIEnv *env, jobject jObj, jstring jConsumerId, jstring jTopicName)
 {
-    LOGD("JNIProviderService: nativeSelectTopic - IN");
+    LOGD("JNIProviderService: nativeSetConsumerTopic - IN");
     if (!jConsumerId || !jTopicName)
     {
         ThrowNSException(NS_ERROR, "Topic Name or ConsumerId Can't be NULL");
@@ -832,7 +1011,7 @@ JNIEXPORT jint JNICALL Java_org_iotivity_service_ns_provider_Consumer_nativeSele
         ThrowNSException(NS_ERROR, "Consumer does exists");
         return (jint) OIC::Service::NSResult::ERROR;
     }
-    OIC::Service::NSResult result  = nsConsumer->selectTopic(topicName);
+    OIC::Service::NSResult result  = nsConsumer->setTopic(topicName);
 
     if (result !=  OIC::Service::NSResult::OK)
     {
@@ -840,13 +1019,13 @@ JNIEXPORT jint JNICALL Java_org_iotivity_service_ns_provider_Consumer_nativeSele
     }
     env->ReleaseStringUTFChars(jTopicName, name);
     env->ReleaseStringUTFChars(jConsumerId, id);
-    LOGD("JNIProviderService: nativeSelectTopic - OUT");
+    LOGD("JNIProviderService: nativeSetConsumerTopic - OUT");
     return (jint) result;
 }
-JNIEXPORT jint JNICALL Java_org_iotivity_service_ns_provider_Consumer_nativeUnselectTopic
+JNIEXPORT jint JNICALL Java_org_iotivity_service_ns_provider_Consumer_nativeUnsetConsumerTopic
 (JNIEnv *env, jobject jObj, jstring jConsumerId, jstring jTopicName)
 {
-    LOGD("JNIProviderService: nativeUnselectTopic - IN");
+    LOGD("JNIProviderService: nativeUnsetConsumerTopic - IN");
     if (!jConsumerId || !jTopicName)
     {
         ThrowNSException(NS_ERROR, "Topic Name or ConsumerId Can't be NULL");
@@ -863,7 +1042,7 @@ JNIEXPORT jint JNICALL Java_org_iotivity_service_ns_provider_Consumer_nativeUnse
         ThrowNSException(NS_ERROR, "Consumer does exists");
         return (jint) OIC::Service::NSResult::ERROR;
     }
-    OIC::Service::NSResult result  = nsConsumer->unselectTopic(topicName);
+    OIC::Service::NSResult result  = nsConsumer->unsetTopic(topicName);
 
     if (result !=  OIC::Service::NSResult::OK)
     {
@@ -871,14 +1050,14 @@ JNIEXPORT jint JNICALL Java_org_iotivity_service_ns_provider_Consumer_nativeUnse
     }
     env->ReleaseStringUTFChars(jTopicName, name);
     env->ReleaseStringUTFChars(jConsumerId, id);
-    LOGD("JNIProviderService: nativeUnselectTopic - OUT");
+    LOGD("JNIProviderService: nativeUnsetConsumerTopic - OUT");
     return (jint) result;
 }
 
-JNIEXPORT jobject JNICALL Java_org_iotivity_service_ns_provider_Consumer_nativeGetConsumerTopics
+JNIEXPORT jobject JNICALL Java_org_iotivity_service_ns_provider_Consumer_nativeGetConsumerTopicList
 (JNIEnv *env, jobject jObj, jstring jConsumerId)
 {
-    LOGD("JNIProviderService: nativeGetConsumerTopics - IN");
+    LOGD("JNIProviderService: nativeGetConsumerTopicList - IN");
     if (!jConsumerId)
     {
         ThrowNSException(NS_ERROR, "Topic Name or ConsumerId Can't be NULL");
@@ -894,14 +1073,14 @@ JNIEXPORT jobject JNICALL Java_org_iotivity_service_ns_provider_Consumer_nativeG
         return NULL;
     }
     env->ReleaseStringUTFChars(jConsumerId, id);
-    OIC::Service::NSTopicsList *topicList  = nsConsumer->getConsumerTopics();
+    OIC::Service::NSTopicsList *topicList  = nsConsumer->getConsumerTopicList();
     if (topicList == nullptr)
     {
         ThrowNSException(NS_ERROR, "Topic List doesn't exist");
         return NULL;
     }
     jobject obj_topicList = getJavaTopicsList(env, topicList);
-    LOGD("JNIProviderService: nativeGetConsumerTopics - OUT");
+    LOGD("JNIProviderService: nativeGetConsumerTopicList - OUT");
     return obj_topicList;
 }
 
index bc7779e..64b7b8b 100644 (file)
@@ -30,10 +30,10 @@ extern "C" {
 /*
  * Class:     org_iotivity_service_ns_provider_ProviderService
  * Method:    nativeStart
- * Signature: (ZLorg/iotivity/service/ns/provider/ProviderService/OnSubscriptionListener;Lorg/iotivity/service/ns/provider/ProviderService/OnSyncInfoListener;)I
+ * Signature: (Lorg/iotivity/service/ns/provider/ProviderService/OnConsumerSubscribedListener;Lorg/iotivity/service/ns/provider/ProviderService/OnMessageSynchronizedListener;ZLjava/lang/String;)I
  */
 JNIEXPORT jint JNICALL Java_org_iotivity_service_ns_provider_ProviderService_nativeStart
-(JNIEnv *, jobject, jboolean, jobject, jobject);
+(JNIEnv *, jobject, jobject, jobject, jboolean, jstring);
 
 /*
  * Class:     org_iotivity_service_ns_provider_ProviderService
@@ -61,11 +61,18 @@ JNIEXPORT void JNICALL Java_org_iotivity_service_ns_provider_ProviderService_nat
 
 /*
  * Class:     org_iotivity_service_ns_provider_ProviderService
+ * Method:    nativeCreateMessage
+ * Signature: ()Lorg/iotivity/service/ns/common/Message;
+ */
+JNIEXPORT jobject JNICALL Java_org_iotivity_service_ns_provider_ProviderService_nativeCreateMessage
+(JNIEnv *, jobject);
+
+/*
+ * Class:     org_iotivity_service_ns_provider_ProviderService
  * Method:    nativeEnableRemoteService
  * Signature: (Ljava/lang/String;)I
  */
-JNIEXPORT jint JNICALL
-Java_org_iotivity_service_ns_provider_ProviderService_nativeEnableRemoteService
+JNIEXPORT jint JNICALL Java_org_iotivity_service_ns_provider_ProviderService_nativeEnableRemoteService
 (JNIEnv *, jobject, jstring);
 
 /*
@@ -73,68 +80,64 @@ Java_org_iotivity_service_ns_provider_ProviderService_nativeEnableRemoteService
  * Method:    nativeDisableRemoteService
  * Signature: (Ljava/lang/String;)I
  */
-JNIEXPORT jint JNICALL
-Java_org_iotivity_service_ns_provider_ProviderService_nativeDisableRemoteService
+JNIEXPORT jint JNICALL Java_org_iotivity_service_ns_provider_ProviderService_nativeDisableRemoteService
 (JNIEnv *, jobject, jstring);
 
 /*
  * Class:     org_iotivity_service_ns_provider_ProviderService
- * Method:    nativeAddTopic
+ * Method:    nativeRegisterTopic
  * Signature: (Ljava/lang/String;)I
  */
-JNIEXPORT jint JNICALL
-Java_org_iotivity_service_ns_provider_ProviderService_nativeAddTopic
+JNIEXPORT jint JNICALL Java_org_iotivity_service_ns_provider_ProviderService_nativeRegisterTopic
 (JNIEnv *, jobject, jstring);
 
 /*
  * Class:     org_iotivity_service_ns_provider_ProviderService
- * Method:    nativeDeleteTopic
+ * Method:    nativeUnregisterTopic
  * Signature: (Ljava/lang/String;)I
  */
-JNIEXPORT jint JNICALL
-Java_org_iotivity_service_ns_provider_ProviderService_nativeDeleteTopic
+JNIEXPORT jint JNICALL Java_org_iotivity_service_ns_provider_ProviderService_nativeUnregisterTopic
 (JNIEnv *, jobject, jstring);
 
 /*
  * Class:     org_iotivity_service_ns_provider_ProviderService
- * Method:    nativeGetTopics
+ * Method:    nativeGetRegisteredTopicList
  * Signature: ()Lorg/iotivity/service/ns/common/TopicsList;
  */
-JNIEXPORT jobject JNICALL
-Java_org_iotivity_service_ns_provider_ProviderService_nativeGetTopics
+JNIEXPORT jobject JNICALL Java_org_iotivity_service_ns_provider_ProviderService_nativeGetRegisteredTopicList
 (JNIEnv *, jobject);
 
 /*
  * Class:     org_iotivity_service_ns_provider_Consumer
  * Method:    nativeAcceptSubscription
- * Signature: (Lorg/iotivity/service/ns/provider/Consumer;Z)I
+ * Signature: (Ljava/lang/String;Z)I
  */
 JNIEXPORT jint JNICALL Java_org_iotivity_service_ns_provider_Consumer_nativeAcceptSubscription
-(JNIEnv *, jobject, jobject, jboolean);
+(JNIEnv *, jobject, jstring, jboolean);
 
 /*
  * Class:     org_iotivity_service_ns_provider_Consumer
- * Method:    nativeSelectTopic
+ * Method:    nativeSetConsumerTopic
  * Signature: (Ljava/lang/String;Ljava/lang/String;)I
  */
-JNIEXPORT jint JNICALL Java_org_iotivity_service_ns_provider_Consumer_nativeSelectTopic
+JNIEXPORT jint JNICALL Java_org_iotivity_service_ns_provider_Consumer_nativeSetConsumerTopic
 (JNIEnv *, jobject, jstring, jstring);
 
 /*
  * Class:     org_iotivity_service_ns_provider_Consumer
- * Method:    nativeUnselectTopic
+ * Method:    nativeUnsetConsumerTopic
  * Signature: (Ljava/lang/String;Ljava/lang/String;)I
  */
-JNIEXPORT jint JNICALL Java_org_iotivity_service_ns_provider_Consumer_nativeUnselectTopic
+JNIEXPORT jint JNICALL Java_org_iotivity_service_ns_provider_Consumer_nativeUnsetConsumerTopic
 (JNIEnv *, jobject, jstring, jstring);
 
 /*
  * Class:     org_iotivity_service_ns_provider_Consumer
- * Method:    nativeGetConsumerTopics
+ * Method:    nativeGetConsumerTopicList
  * Signature: (Ljava/lang/String;)Lorg/iotivity/service/ns/common/TopicsList;
  */
 JNIEXPORT jobject JNICALL
-Java_org_iotivity_service_ns_provider_Consumer_nativeGetConsumerTopics
+Java_org_iotivity_service_ns_provider_Consumer_nativeGetConsumerTopicList
 (JNIEnv *, jobject, jstring);
 
 #ifdef __cplusplus
index 3bb455f..b9005a0 100755 (executable)
@@ -18,6 +18,9 @@
 #
 #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
+Import('env')
+target_os = env.get('TARGET_OS')
+
 # build producer notification wrapper
 SConscript('provider/SConscript')
 
@@ -27,5 +30,3 @@ SConscript('consumer/SConscript')
 # Go to build sample apps using wrapper
 SConscript('examples/linux/SConscript')
 
-# Go to build Unit test
-#SConscript('unittest/SConscript')
\ No newline at end of file
index 28780e0..2f58fc4 100755 (executable)
@@ -37,7 +37,7 @@ namespace OIC
             if (msg != nullptr)\r
             {\r
                 m_messageId = msg->messageId;\r
-                m_providerId = msg->providerId;\r
+                m_providerId.assign(msg->providerId, NS_UTILS_UUID_STRING_SIZE - 1);\r
 \r
                 m_type = (NSMessageType)msg->type;\r
 \r
@@ -65,6 +65,45 @@ namespace OIC
             }\r
         }\r
 \r
+        NSMessage::NSMessage(const NSMessage &msg)\r
+        {\r
+            m_messageId = msg.getMessageId();\r
+            m_providerId = msg.getProviderId();\r
+\r
+            m_type = msg.getType();\r
+            m_time = msg.getTime();\r
+            m_ttl = msg.getTTL();\r
+            m_title = msg.getTitle();\r
+            m_contentText = msg.getContentText();\r
+            m_sourceName = msg.getSourceName();\r
+\r
+            if (msg.getMediaContents() != nullptr)\r
+                m_mediaContents = new NSMediaContents(msg.getMediaContents()->getIconImage());\r
+            else\r
+                m_mediaContents = new NSMediaContents();\r
+            m_topic = msg.getTopic();\r
+        }\r
+\r
+        NSMessage &NSMessage::operator=(const NSMessage &msg)\r
+        {\r
+            this->m_messageId = msg.getMessageId();\r
+            this->m_providerId = msg.getProviderId();\r
+\r
+            this->m_type = msg.getType();\r
+            this->m_time = msg.getTime();\r
+            this->m_ttl = msg.getTTL();\r
+            this->m_title = msg.getTitle();\r
+            this->m_contentText = msg.getContentText();\r
+            this->m_sourceName = msg.getSourceName();\r
+\r
+            if (msg.getMediaContents() != nullptr)\r
+                this->m_mediaContents = new NSMediaContents(msg.getMediaContents()->getIconImage());\r
+            else\r
+                this->m_mediaContents = new NSMediaContents();\r
+            this->m_topic = msg.getTopic();\r
+            return *this;\r
+        }\r
+\r
         NSMessage::~NSMessage()\r
         {\r
             if (m_mediaContents != nullptr)\r
index 3c4d8c6..f29c607 100755 (executable)
@@ -64,6 +64,21 @@ namespace OIC
                 NSMessage(::NSMessage *msg);\r
 \r
                 /**\r
+                     * Copy Constructor of NSMessage.\r
+                     *\r
+                     * @param msg - NSMessage to initialize.\r
+                     */\r
+                NSMessage(const NSMessage &msg);\r
+\r
+                /**\r
+                     * Copy assignment operator of NSMessage.\r
+                     *\r
+                     * @param msg -  NSMessage to initialize.\r
+                     * @return NSMessage object reference\r
+                     */\r
+                NSMessage &operator=(const NSMessage &msg);\r
+\r
+                /**\r
                         * Destructor of NSMessage.\r
                         */\r
                 ~NSMessage();\r
@@ -134,7 +149,7 @@ namespace OIC
                 /**\r
                      * This method is for setting Title from the Notification service Message.\r
                      *\r
-                     * @param Title as string.\r
+                     * @param title as string.\r
                      */\r
                 void setTitle(const std::string &title);\r
 \r
@@ -148,7 +163,7 @@ namespace OIC
                 /**\r
                      * This method is for setting contentText from the Notification service Message.\r
                      *\r
-                     * @param contentText as string.\r
+                     * @param contextText as string.\r
                      */\r
                 void setContentText(const std::string &contextText);\r
 \r
index 5b9ab58..5f6a114 100755 (executable)
@@ -33,7 +33,7 @@ namespace OIC
             if (syncInfo != nullptr)\r
             {\r
                 m_messageId = syncInfo->messageId;\r
-                m_providerId = syncInfo->providerId;\r
+                m_providerId.assign(syncInfo->providerId, NS_UTILS_UUID_STRING_SIZE - 1);\r
                 m_state = (NSSyncType) syncInfo->state;\r
             }\r
         }\r
index 12abc81..9dddcd8 100755 (executable)
@@ -37,6 +37,22 @@ namespace OIC
             }
 
         }
+        NSTopicsList::NSTopicsList(const NSTopicsList &topicsList)
+        {
+            for (auto it : topicsList.getTopicsList())
+            {
+                addTopic(it->getTopicName(), it->getState());
+            }
+        }
+
+        NSTopicsList &NSTopicsList::operator=(const NSTopicsList &topicsList)
+        {
+            for (auto it : topicsList.getTopicsList())
+            {
+                this->addTopic(it->getTopicName(), it->getState());
+            }
+            return *this;
+        }
 
         NSTopicsList::~NSTopicsList()
         {
@@ -61,7 +77,7 @@ namespace OIC
             }
         }
 
-        std::list<NSTopic *> NSTopicsList::getTopicsList()
+        std::list<NSTopic *> NSTopicsList::getTopicsList() const
         {
             return m_topicsList;
         }
index 9274826..f868bd2 100755 (executable)
@@ -56,6 +56,21 @@ namespace OIC
                 NSTopicsList(::NSTopicLL *topics);
 
                 /**
+                     * Copy Constructor of NSTopicsList.
+                     *
+                     * @param topicsList - NSTopicsList to initialize.
+                     */
+                NSTopicsList(const NSTopicsList &topicsList);
+
+                /**
+                     * Copy assignment operator of NSTopicsList.
+                     *
+                     * @param topicsList -  NSTopicsList to initialize.
+                     * @return NSTopicsList object reference
+                     */
+                NSTopicsList &operator=(const NSTopicsList &topicsList);
+
+                /**
                      * Destructor of NSTopicsList.
                      */
                 ~NSTopicsList();
@@ -80,7 +95,7 @@ namespace OIC
                      *
                      * @return topic as NSTopics Linked list.
                      */
-                std::list<NSTopic *> getTopicsList();
+                std::list<NSTopic *> getTopicsList() const;
 
             private:
                 std::list<NSTopic *> m_topicsList;
index 99c0c3d..2c1ea66 100755 (executable)
@@ -27,6 +27,7 @@
 #ifndef _NS_UTILS_H_
 #define _NS_UTILS_H_
 
+/** NS_UTILS_UUID_STRING_SIZE - UUID string size*/
 #define NS_UTILS_UUID_STRING_SIZE 37
 
 namespace OIC
@@ -43,13 +44,24 @@ namespace OIC
         };
 
         /**
-             * NSResponse code of notification service
+             * NSProviderState of notification service
              */
-        enum class NSResponse
+        enum class NSProviderState
         {
             ALLOW = 1,
             DENY = 2,
             TOPIC = 3,
+            STOPPED = 12
+        };
+        
+        /**
+             * NSProviderSubscribedState of notification service
+             */
+        enum class NSProviderSubscribedState
+        {
+            DENY = 0,
+            DISCOVERED = 1,
+            SUBSCRIBED = 2
         };
     }
 }
index 9244922..e476623 100755 (executable)
@@ -79,14 +79,19 @@ if env.get('WITH_CLOUD') == True:
 ######################################################################
 # Source files and Targets
 ######################################################################
+Import('notificationCommonStaticObjs')
+Import('notificationCommonSharedObjs')
 
 notification_consumer_src = [
-       env.Glob('src/*.cpp'),env.Glob('../common/*.cpp')]
+       env.Glob('src/*.cpp'),notificationCommonSharedObjs]
 
 consumersdk = notification_env.SharedLibrary('notification_consumer_wrapper', notification_consumer_src)
 notification_env.InstallTarget(consumersdk, 'libnotification_consumer_wrapper')
 notification_env.UserInstallTargetLib(consumersdk, 'libnotification_consumer_wrapper')
 
+notification_consumer_src = [
+       env.Glob('src/*.cpp'),notificationCommonStaticObjs]
+
 consumersdk = notification_env.StaticLibrary('notification_consumer_wrapper', notification_consumer_src)
 notification_env.InstallTarget(consumersdk, 'libnotification_consumer_wrapper')
 notification_env.UserInstallTargetLib(consumersdk, 'libnotification_consumer_wrapper')
index 0b1c197..f60dd57 100755 (executable)
@@ -53,26 +53,6 @@ namespace OIC
                 typedef void (*ProviderDiscoveredCallback)(NSProvider *);\r
 \r
                 /**\r
-                     * Invoked when the provider state is changed\r
-                     * @param[in] provider  Provider which has the notification resource\r
-                     * @param[in] response  Response which has the provider state\r
-                     */\r
-                typedef void (* ProviderChangedCallback)(NSProvider *, NSResponse);\r
-\r
-                /**\r
-                     * @struct   ConsumerConfig\r
-                     * @brief Consumer sets this callback function configuration for registering callbacks\r
-                     *\r
-                     */\r
-                typedef struct\r
-                {\r
-                    /** m_discoverCb - ProviderDiscoveredCallback callback listener.*/\r
-                    ProviderDiscoveredCallback m_discoverCb;\r
-                    /** m_changedCb - ProviderChangedCallback callback listener.*/\r
-                    ProviderChangedCallback m_changedCb;\r
-                } ConsumerConfig;\r
-\r
-                /**\r
                       * API for getting the Instance of NSConsumerService class\r
                       *\r
                       * @return Instance of the "NSConsumerService" class\r
@@ -81,27 +61,32 @@ namespace OIC
 \r
                 /**\r
                       * Initialize notification service for consumer\r
-                      * @param[in]  config   ConsumerConfig Callback function pointers to onDiscoverd,\r
-                      * OnAccepted, OnMessageReceived and OnSyncInfoReceived functions\r
+                      * @param providerDiscovered Callback function pointers to ProviderDiscoveredCallback,\r
                       */\r
-                void Start(ConsumerConfig config);\r
+                void start(ProviderDiscoveredCallback providerDiscovered);\r
 \r
                 /**\r
                       * Terminate notification service for consumer\r
                       */\r
-                void Stop();\r
+                void stop();\r
 \r
                 /**\r
                      * Request to discover to remote address as parameter.\r
-                     * @param[in]  server address combined with IP address and port number using delimiter :\r
+                     * @param[in]  serverAddress combined with IP address and port number using delimiter :\r
                      * @return  NSResult code of Consumer Service\r
                      */\r
-                NSResult EnableRemoteService(const std::string &serverAddress);\r
+                NSResult enableRemoteService(const std::string &serverAddress);\r
 \r
                 /**\r
                       * Request discovery manually\r
                       */\r
-                void RescanProvider();\r
+                void rescanProvider();\r
+\r
+                /**\r
+                      *  get the callback for ProviderDiscovered\r
+                      * @return ProviderDiscoveredCallback callbak set\r
+                      */\r
+                ProviderDiscoveredCallback getProviderDiscoveredCb();\r
 \r
                 /**\r
                       *  request to get NSProvider pointer\r
@@ -111,20 +96,6 @@ namespace OIC
                       */\r
                 NSProvider *getProvider(const std::string &id);\r
 \r
-\r
-                /**\r
-                     * Request NSMessage that is matched by message id\r
-                     * @param[in]  messageId  the id of message that user wants to get\r
-                     * @return NSMessage\r
-                     */\r
-                NSMessage *getMessage(uint64_t messageId);\r
-\r
-                /**\r
-                      *  get consumer config values\r
-                      * @return ConsumerConfig callbaks set\r
-                      */\r
-                ConsumerConfig getConsumerConfig();\r
-\r
                 /**\r
                       *  get list of providers acceted.\r
                       * @return m_acceptedProviders -list of accepted providers\r
@@ -132,7 +103,7 @@ namespace OIC
                 std::list<NSProvider *> &getAcceptedProviders();\r
 \r
             private :\r
-                ConsumerConfig m_config;\r
+                ProviderDiscoveredCallback m_providerDiscoveredCb;\r
                 std::list<NSProvider *> m_acceptedProviders;\r
 \r
             private :\r
index a556ae2..7ddc0c5 100755 (executable)
@@ -45,6 +45,13 @@ namespace OIC
         class NSProvider\r
         {\r
             public:\r
+\r
+                /**\r
+                     * Invoked when the provider state is changed\r
+                     * @param[in] providerState  NSProviderState of the notification resource\r
+                     */\r
+                typedef void (* ProviderStateCallback)(NSProviderState);\r
+\r
                 /**\r
                      * Consumer use this callback function to receive notification message from provider\r
                      * synchronization\r
@@ -62,7 +69,9 @@ namespace OIC
                 /**\r
                       * Constructor of NSProvider.\r
                       */\r
-                NSProvider(): m_topicList(new NSTopicsList()), m_messageCb(NULL), m_syncInfoCb(NULL) {}\r
+                NSProvider(): m_topicList(new NSTopicsList()), m_state(NSProviderState::DENY),\r
+                    m_subscribedState(NSProviderSubscribedState::DENY),\r
+                    m_stateCb(NULL), m_messageCb(NULL), m_syncInfoCb(NULL) {}\r
 \r
                 /**\r
                       * Constructor of NSProvider.\r
@@ -70,7 +79,9 @@ namespace OIC
                       * @param providerId - providerId of the Notification.\r
                       */\r
                 NSProvider(const std::string &providerId) : m_providerId(providerId),\r
-                    m_topicList(new NSTopicsList()), m_messageCb(NULL), m_syncInfoCb(NULL) {}\r
+                    m_topicList(new NSTopicsList()), m_state(NSProviderState::DENY),\r
+                    m_subscribedState(NSProviderSubscribedState::DENY),\r
+                    m_stateCb(NULL), m_messageCb(NULL), m_syncInfoCb(NULL)  {}\r
 \r
                 /**\r
                       * Constructor of NSProvider.\r
@@ -79,7 +90,9 @@ namespace OIC
                       * @param topicList - NSTopicsList of interested Topics.\r
                       */\r
                 NSProvider(const std::string &providerId, NSTopicsList *topicList) : m_providerId(\r
-                        providerId), m_topicList(topicList), m_messageCb(NULL), m_syncInfoCb(NULL) {}\r
+                        providerId), m_topicList(topicList), m_state(NSProviderState::DENY),\r
+                    m_subscribedState(NSProviderSubscribedState::DENY),\r
+                    m_stateCb(NULL), m_messageCb(NULL), m_syncInfoCb(NULL)  {}\r
 \r
                 /**\r
                       * Constructor of NSProvider.\r
@@ -88,6 +101,20 @@ namespace OIC
                       */\r
                 NSProvider(::NSProvider *provider);\r
 \r
+                /**\r
+                     * Copy Constructor of NSProvider.\r
+                     *\r
+                     * @param provider - NSProvider to initialize.\r
+                     */\r
+                NSProvider(const NSProvider &provider);\r
+\r
+                /**\r
+                     * Copy assignment operator of NSProvider.\r
+                     *\r
+                     * @param provider -  NSProvider to initialize.\r
+                     * @return NSProvider object reference\r
+                     */\r
+                NSProvider &operator=(const NSProvider &provider);\r
 \r
                 /**\r
                       * Destructor of NSProvider.\r
@@ -109,16 +136,38 @@ namespace OIC
                 NSTopicsList *getTopicList() const;\r
 \r
                 /**\r
+                     * Update Topic list that is wanted to be subscribed from provider\r
+                     *\r
+                     * @param topicList - NSTopicsList of interested Topics.\r
+                     * @return NSResult\r
+                     */\r
+                NSResult updateTopicList(NSTopicsList *topicList);\r
+\r
+                /**\r
+                      * This method is for getting ProviderState from the Notification service provider.\r
+                      *\r
+                      * @return ProviderState as NSProviderState.\r
+                      */\r
+                NSProviderState getProviderState() const;\r
+\r
+                /**\r
+                      * This method is for getting SubscribedState from the Notification service provider.\r
+                      *\r
+                      * @return subscribedState as NSProviderSubscribedState.\r
+                      */\r
+                NSProviderSubscribedState getProviderSubscribedState() const;\r
+\r
+                /**\r
                       * This method is for requesting subscription of Notification service.\r
                       *\r
                       */\r
                 void subscribe();\r
 \r
                 /**\r
-                      * This method is for requesting unsubscription of Notification service.\r
+                      * This method is for requesting subscription status from Provider of Notification service.\r
                       *\r
                       */\r
-                void unSubscribe();\r
+                bool isSubscribed();\r
 \r
                 /**\r
                       * This method is for Sending SyncInfo of Notification service.\r
@@ -126,38 +175,60 @@ namespace OIC
                       * @param messageId - id of type message.\r
                       * @param type - NSSyncType of Notification service.\r
                       */\r
-                void SendSyncInfo(uint64_t messageId, NSSyncInfo::NSSyncType type);\r
+                void sendSyncInfo(uint64_t messageId, NSSyncInfo::NSSyncType type);\r
 \r
                 /**\r
                       * This method is for registering for listeners of Notification .\r
                       *\r
+                      * @param stateHandle - ProviderStateCallback callback.\r
                       * @param messageHandle - MessageReceivedCallback callback.\r
                       * @param syncHandle - SyncInfoReceivedCallback callback\r
                       */\r
-                void setListener(MessageReceivedCallback messageHandle,\r
+                void setListener(ProviderStateCallback stateHandle,\r
+                                 MessageReceivedCallback messageHandle,\r
                                  SyncInfoReceivedCallback syncHandle);\r
 \r
                 /**\r
-                     * Select Topic list that is wanted to subscribe from provider\r
-                     *\r
-                     * @param topicList - NSTopicsList of interested Topics.\r
-                     * @return NSResult\r
-                     */\r
-                NSResult selectInterestTopics(NSTopicsList *topicList);\r
+                      * This method is for getting the registered cb of Provider State received.\r
+                      *\r
+                      * @return stateCb - ProviderStateCallback .\r
+                      */\r
+                ProviderStateCallback getProviderStateReceivedCb() const;\r
 \r
                 /**\r
                       * This method is for getting the registered cb of Notification message received.\r
                       *\r
                       * @return messageCb - MessageReceivedCallback .\r
                       */\r
-                MessageReceivedCallback getMessageReceivedCb();\r
+                MessageReceivedCallback getMessageReceivedCb() const;\r
 \r
                 /**\r
                       * This method is for getting the registered cb of Notification SyncInfo received.\r
                       *\r
                       * @return syncInfoCb - SyncInfoReceivedCallback .\r
                       */\r
-                SyncInfoReceivedCallback getSyncInfoReceivedCb();\r
+                SyncInfoReceivedCallback getSyncInfoReceivedCb() const;\r
+\r
+                /**\r
+                      * This method is for setting NSTopic List for the Notification service provider.\r
+                      *\r
+                      * @param topicsList  as NSTopicsList pointer.\r
+                      */\r
+                void setTopicList(NSTopicsList *topicsList);\r
+\r
+                /**\r
+                     * This method is for setting ProviderState for the Notification service provider.\r
+                     *\r
+                     * @param providerState as NSProviderState.\r
+                     */\r
+                void setProviderState(const NSProviderState &providerState);\r
+\r
+                /**\r
+                     * This method is for setting subscribedState for the Notification service provider.\r
+                     *\r
+                     * @param subscribedState as NSProviderSubscribedState.\r
+                     */\r
+                void setProviderSubscribedState(const NSProviderSubscribedState &subscribedState);\r
 \r
             private:\r
                 ::NSProvider *getNSProvider();\r
@@ -165,9 +236,12 @@ namespace OIC
             private:\r
                 std::string m_providerId;\r
                 NSTopicsList *m_topicList;\r
+                NSProviderState m_state;\r
+                NSProviderSubscribedState m_subscribedState;\r
+\r
+                ProviderStateCallback m_stateCb;\r
                 MessageReceivedCallback m_messageCb;\r
                 SyncInfoReceivedCallback m_syncInfoCb;\r
-\r
         };\r
     }\r
 }\r
index f3ee775..ec11649 100755 (executable)
@@ -30,71 +30,103 @@ namespace OIC
 {\r
     namespace Service\r
     {\r
-        void onNSProviderDiscovered(::NSProvider *provider)\r
+        void onProviderStateReceived(::NSProvider *provider, ::NSProviderState state)\r
         {\r
-            NS_LOG(DEBUG, "onNSProviderDiscovered - IN");\r
-            NSProvider *nsProvider = new NSProvider(provider);\r
-            if (NSConsumerService::getInstance()->getConsumerConfig().m_discoverCb != NULL)\r
-            {\r
-                NS_LOG(DEBUG, "initiating the callback");\r
-                NSConsumerService::getInstance()->getConsumerConfig().m_discoverCb(nsProvider);\r
-            }\r
-            delete nsProvider;\r
-            NS_LOG(DEBUG, "onNSProviderDiscovered - OUT");\r
-        }\r
-\r
-        void onNSProviderChanged(::NSProvider *provider, ::NSResponse response)\r
-        {\r
-            NS_LOG(DEBUG, "onNSProviderChanged - IN");\r
+            NS_LOG(DEBUG, "onNSProviderStateChanged - IN");\r
             NS_LOG_V(DEBUG, "provider Id : %s", provider->providerId);\r
-            NS_LOG_V(DEBUG, "response : %d", (int)response);\r
+            NS_LOG_V(DEBUG, "state : %d", (int)state);\r
 \r
             NSProvider *nsProvider = new NSProvider(provider);\r
-            auto changeCallback = NSConsumerService::getInstance()->getConsumerConfig().m_changedCb;\r
-            if (response == NS_ALLOW)\r
+            NSProvider *oldProvider = NSConsumerService::getInstance()->getProvider(\r
+                                          nsProvider->getProviderId());\r
+\r
+            if (oldProvider == nullptr)\r
             {\r
-                NSConsumerService::getInstance()->getAcceptedProviders().push_back(nsProvider);\r
-                if (changeCallback != NULL)\r
+                NS_LOG(DEBUG, "Provider with same Id do not exist. updating Data for New Provider");\r
+                auto discoveredCallback = NSConsumerService::getInstance()->getProviderDiscoveredCb();\r
+                nsProvider->setProviderState((NSProviderState)state);\r
+                auto topicLL = NSConsumerGetTopicList(provider->providerId);\r
+                nsProvider->setTopicList(new NSTopicsList(topicLL));\r
+                if (state == NS_DISCOVERED)\r
                 {\r
-                    NS_LOG(DEBUG, "initiating the callback for Response : ALLOW");\r
-                    changeCallback(nsProvider, (NSResponse) response);\r
+                    nsProvider->setProviderSubscribedState(NSProviderSubscribedState::DISCOVERED);\r
+                    if (discoveredCallback != NULL)\r
+                    {\r
+                        NS_LOG(DEBUG, "initiating the Discovered callback : NS_DISCOVERED, policy false");\r
+                        discoveredCallback(nsProvider);\r
+                    }\r
                 }\r
-            }\r
-            else if (response == NS_DENY)\r
-            {\r
-                NSConsumerService::getInstance()->getAcceptedProviders().remove(nsProvider);\r
-                if (changeCallback != NULL)\r
+                else if (state == NS_ALLOW)\r
                 {\r
-                    NS_LOG(DEBUG, "initiating the callback for Response : NS_DENY");\r
-                    changeCallback(nsProvider, (NSResponse) response);\r
+                    nsProvider->setProviderSubscribedState(NSProviderSubscribedState::SUBSCRIBED);\r
+                    if (discoveredCallback != NULL)\r
+                    {\r
+                        NS_LOG(DEBUG, "initiating the Discovered callback : NS_ALLOW, policy true");\r
+                        discoveredCallback(nsProvider);\r
+                    }\r
                 }\r
-                delete nsProvider;\r
+                NSConsumerService::getInstance()->getAcceptedProviders().push_back(nsProvider);\r
             }\r
-            else if (response == NS_TOPIC)\r
+            else\r
             {\r
-                NSProvider *oldProvider = NSConsumerService::getInstance()->getProvider(\r
-                                              nsProvider->getProviderId());\r
-                if (oldProvider != nullptr)\r
+                NS_LOG(DEBUG, "Provider with same Id exists. updating the old Provider data");\r
+                auto changeCallback = oldProvider->getProviderStateReceivedCb();\r
+                oldProvider->setProviderState((NSProviderState)state);\r
+                delete nsProvider;\r
+                if (state == NS_ALLOW)\r
                 {\r
-                    NS_LOG(DEBUG, "Provider with same Id exists. updating the Topics data");\r
-                    nsProvider->setListener(oldProvider->getMessageReceivedCb(), oldProvider->getSyncInfoReceivedCb());\r
+                    oldProvider->setProviderSubscribedState(NSProviderSubscribedState::SUBSCRIBED);\r
+                    if (changeCallback != NULL)\r
+                    {\r
+                        NS_LOG(DEBUG, "initiating the callback for Response : NS_ALLOW");\r
+                        changeCallback((NSProviderState)state);\r
+                    }\r
+                }\r
+                else if (state == NS_DENY)\r
+                {\r
+                    oldProvider->setProviderSubscribedState(NSProviderSubscribedState::DENY);\r
                     NSConsumerService::getInstance()->getAcceptedProviders().remove(oldProvider);\r
-                    NSConsumerService::getInstance()->getAcceptedProviders().push_back(nsProvider);\r
                     if (changeCallback != NULL)\r
                     {\r
-                        NS_LOG(DEBUG, "initiating the callback for Response : NS_TOPIC");\r
-                        changeCallback(nsProvider, (NSResponse) response);\r
+                        NS_LOG(DEBUG, "initiating the callback for Response : NS_DENY");\r
+                        changeCallback((NSProviderState)state);\r
                     }\r
                     delete oldProvider;\r
                 }\r
+                else if (state == NS_TOPIC)\r
+                {\r
+                    auto topicLL = NSConsumerGetTopicList(provider->providerId);\r
+                    oldProvider->setTopicList(new NSTopicsList(topicLL));\r
+                    if (changeCallback != NULL)\r
+                    {\r
+                        NS_LOG(DEBUG, "initiating the callback for Response : NS_TOPIC");\r
+                        changeCallback((NSProviderState)state);\r
+                    }\r
+                }\r
+                else if (state == NS_STOPPED)\r
+                {\r
+                    oldProvider->setProviderSubscribedState(NSProviderSubscribedState::DENY);\r
+                    NSConsumerService::getInstance()->getAcceptedProviders().remove(oldProvider);\r
+                    NS_LOG(DEBUG, "initiating the State callback : NS_STOPPED");\r
+                    if (changeCallback != NULL)\r
+                    {\r
+                        NS_LOG(DEBUG, "initiating the callback for Response : NS_STOPPED");\r
+                        changeCallback((NSProviderState)state);\r
+                    }\r
+                }\r
             }\r
-            NS_LOG(DEBUG, "onNSProviderChanged - OUT");\r
+            NS_LOG(DEBUG, "onNSProviderStateChanged - OUT");\r
         }\r
 \r
         void onNSMessageReceived(::NSMessage *message)\r
         {\r
             NS_LOG(DEBUG, "onNSMessageReceived - IN");\r
+            NS_LOG_V(DEBUG, "message->providerId : %s", message->providerId);\r
+\r
             NSMessage *nsMessage = new NSMessage(message);\r
+\r
+            NS_LOG_V(DEBUG, "getAcceptedProviders Size : %d", (int)\r
+                     NSConsumerService::getInstance()->getAcceptedProviders().size());\r
             for (auto it : NSConsumerService::getInstance()->getAcceptedProviders())\r
             {\r
                 if (it->getProviderId() == nsMessage->getProviderId())\r
@@ -137,8 +169,7 @@ namespace OIC
 \r
         NSConsumerService::NSConsumerService()\r
         {\r
-            m_config.m_discoverCb = NULL;\r
-            m_config.m_changedCb = NULL;\r
+            m_providerDiscoveredCb = NULL;\r
         }\r
 \r
         NSConsumerService::~NSConsumerService()\r
@@ -149,56 +180,68 @@ namespace OIC
             }\r
             getAcceptedProviders().clear();\r
         }\r
+\r
         NSConsumerService *NSConsumerService::getInstance()\r
         {\r
             static  NSConsumerService s_instance;\r
             return &s_instance;\r
         }\r
 \r
-        void NSConsumerService::Start(NSConsumerService::ConsumerConfig config)\r
+        void NSConsumerService::start(NSConsumerService::ProviderDiscoveredCallback providerDiscovered)\r
         {\r
-            NS_LOG(DEBUG, "Start - IN");\r
-            m_config = config;\r
+            NS_LOG(DEBUG, "start - IN");\r
+            m_providerDiscoveredCb = providerDiscovered;\r
             NSConsumerConfig nsConfig;\r
-            nsConfig.discoverCb = onNSProviderDiscovered;\r
-            nsConfig.changedCb = onNSProviderChanged;\r
+            nsConfig.changedCb = onProviderStateReceived;\r
             nsConfig.messageCb = onNSMessageReceived;\r
             nsConfig.syncInfoCb = onNSSyncInfoReceived;\r
 \r
             NSStartConsumer(nsConfig);\r
-            NS_LOG(DEBUG, "Start - OUT");\r
+            NS_LOG(DEBUG, "start - OUT");\r
             return;\r
         }\r
 \r
-        void NSConsumerService::Stop()\r
+        void NSConsumerService::stop()\r
         {\r
-            NS_LOG(DEBUG, "Stop - IN");\r
+            NS_LOG(DEBUG, "stop - IN");\r
             NSStopConsumer();\r
-            NS_LOG(DEBUG, "Stop - OUT");\r
+            for (auto it : getAcceptedProviders())\r
+            {\r
+                delete it;\r
+            }\r
+            getAcceptedProviders().clear();\r
+            NS_LOG(DEBUG, "stop - OUT");\r
             return;\r
         }\r
 \r
-        NSResult NSConsumerService::EnableRemoteService(const std::string &serverAddress)\r
+        NSResult NSConsumerService::enableRemoteService(const std::string &serverAddress)\r
         {\r
-            NS_LOG(DEBUG, "EnableRemoteService - IN");\r
+            NS_LOG(DEBUG, "enableRemoteService - IN");\r
+            NS_LOG_V(DEBUG, "Server Address : %s", serverAddress.c_str());\r
             NSResult result = NSResult::ERROR;\r
 #ifdef WITH_CLOUD\r
             result = (NSResult) NSConsumerEnableRemoteService(OICStrdup(serverAddress.c_str()));\r
 #else\r
             NS_LOG(ERROR, "Remote Services feature is not enabled in the Build");\r
+            (void) serverAddress;\r
 #endif\r
-            NS_LOG(DEBUG, "EnableRemoteService - OUT");\r
+            NS_LOG(DEBUG, "enableRemoteService - OUT");\r
             return result;\r
         }\r
 \r
-        void NSConsumerService::RescanProvider()\r
+        void NSConsumerService::rescanProvider()\r
         {\r
-            NS_LOG(DEBUG, "RescanProvider - IN");\r
+            NS_LOG(DEBUG, "rescanProvider - IN");\r
             NSRescanProvider();\r
-            NS_LOG(DEBUG, "RescanProvider - OUT");\r
+            NS_LOG(DEBUG, "rescanProvider - OUT");\r
             return;\r
         }\r
 \r
+        NSConsumerService::ProviderDiscoveredCallback NSConsumerService::getProviderDiscoveredCb()\r
+        {\r
+            return m_providerDiscoveredCb;\r
+        }\r
+\r
         NSProvider *NSConsumerService::getProvider(const std::string &id)\r
         {\r
             for (auto it : getAcceptedProviders())\r
@@ -213,24 +256,7 @@ namespace OIC
             return NULL;\r
         }\r
 \r
-        NSMessage *NSConsumerService::getMessage(uint64_t messageId)\r
-        {\r
-            NS_LOG(DEBUG, "getMessage - IN");\r
-            ::NSMessage *message = NSConsumerGetMessage(messageId);\r
-            NSMessage *nsMessage = new NSMessage(message);\r
-\r
-            delete message->mediaContents;\r
-            delete message;\r
-            NS_LOG(DEBUG, "getMessage - OUT");\r
-            return nsMessage;\r
-        }\r
-\r
-        NSConsumerService::ConsumerConfig NSConsumerService::getConsumerConfig()\r
-        {\r
-            return m_config;\r
-        }\r
-\r
-        std::list<NSProvider *>& NSConsumerService::getAcceptedProviders()\r
+        std::list<NSProvider *> &NSConsumerService::getAcceptedProviders()\r
         {\r
             return m_acceptedProviders;\r
         }\r
index ce90f51..648f9c6 100755 (executable)
@@ -24,6 +24,7 @@
 #include "NSConstants.h"\r
 #include "NSCommon.h"\r
 #include "oic_string.h"\r
+#include "oic_malloc.h"\r
 \r
 namespace OIC\r
 {\r
@@ -33,42 +34,60 @@ namespace OIC
         {\r
             ::NSProvider *provider = new ::NSProvider;\r
             OICStrcpy(provider->providerId, NS_UTILS_UUID_STRING_SIZE, m_providerId.c_str());\r
+            return provider;\r
+        }\r
+\r
+        NSProvider::NSProvider(::NSProvider *provider)\r
+        {\r
+            m_stateCb = NULL;\r
+            m_messageCb = NULL;\r
+            m_syncInfoCb = NULL;\r
+            m_state = NSProviderState::DENY;\r
+            m_subscribedState = NSProviderSubscribedState::DENY;\r
 \r
-            provider->topicLL = NULL;\r
+            m_topicList = new NSTopicsList();\r
 \r
-            if (m_topicList != nullptr)\r
+            if (provider != nullptr)\r
+            {\r
+                m_providerId.assign(provider->providerId, NS_UTILS_UUID_STRING_SIZE - 1);\r
+            }\r
+        }\r
+\r
+        NSProvider::NSProvider(const NSProvider &provider)\r
+        {\r
+            m_providerId = provider.getProviderId();\r
+            m_topicList = new NSTopicsList();\r
+            auto topicsList = provider.getTopicList();\r
+            if (topicsList != nullptr)\r
             {\r
-                for (auto it : m_topicList->getTopicsList())\r
+                for (auto it : topicsList->getTopicsList())\r
                 {\r
-                    ::NSTopicLL *topic = new ::NSTopicLL;\r
-                    OICStrcpy(topic->topicName, it->getTopicName().length(),\r
-                              it->getTopicName().c_str());\r
-                    topic->state = (::NSTopicState)it->getState();\r
-                    topic->next = NULL;\r
-                    if (provider->topicLL == NULL)\r
-                        provider->topicLL = topic;\r
-                    else\r
-                    {\r
-                        topic->next = provider->topicLL;\r
-                        provider->topicLL = topic;\r
-                    }\r
+                    getTopicList()->addTopic(it->getTopicName(), it->getState());\r
                 }\r
             }\r
-            return provider;\r
+            setListener(provider.getProviderStateReceivedCb(), provider.getMessageReceivedCb(),\r
+                        provider.getSyncInfoReceivedCb());\r
+            setProviderState(provider.getProviderState());\r
+            setProviderSubscribedState(provider.getProviderSubscribedState());\r
         }\r
 \r
-        NSProvider::NSProvider(::NSProvider *provider)\r
+        NSProvider &NSProvider::operator=(const NSProvider &provider)\r
         {\r
-            m_messageCb = NULL;\r
-            m_syncInfoCb = NULL;\r
-            if (provider != nullptr)\r
+            this->m_providerId = provider.getProviderId();\r
+            this->m_topicList = new NSTopicsList();\r
+            auto topicsList = provider.getTopicList();\r
+            if (topicsList != nullptr)\r
             {\r
-                m_providerId = provider->providerId;\r
-                if (provider->topicLL != nullptr)\r
-                    m_topicList = new NSTopicsList(provider->topicLL);\r
-                else\r
-                    m_topicList = new NSTopicsList();\r
+                for (auto it : topicsList->getTopicsList())\r
+                {\r
+                    this->getTopicList()->addTopic(it->getTopicName(), it->getState());\r
+                }\r
             }\r
+            this->setListener(provider.getProviderStateReceivedCb(), provider.getMessageReceivedCb(),\r
+                              provider.getSyncInfoReceivedCb());\r
+            this->setProviderState(provider.getProviderState());\r
+            this->setProviderSubscribedState(provider.getProviderSubscribedState());\r
+            return *this;\r
         }\r
 \r
         NSProvider::~NSProvider()\r
@@ -84,24 +103,97 @@ namespace OIC
 \r
         NSTopicsList *NSProvider::getTopicList() const\r
         {\r
+            NS_LOG(DEBUG, "getTopicList - IN");\r
             return m_topicList;\r
         }\r
 \r
+        NSResult NSProvider::updateTopicList(NSTopicsList *topicList)\r
+        {\r
+            NS_LOG(DEBUG, "updateTopicList - IN");\r
+            if (topicList == nullptr)\r
+                return NSResult::ERROR;\r
+//            for (auto it : topicList->getTopicsList())\r
+//            {\r
+//                NS_LOG_V(DEBUG, "Topic Name : %s", it->getTopicName().c_str());\r
+//                NS_LOG_V(DEBUG, "Topic State : %d", (int) it->getState());\r
+//            }\r
+            NS_LOG(DEBUG, "Creating TopicLL from TopicList");\r
+            NSTopicLL *topicLL = NULL;\r
+            for (auto it : topicList->getTopicsList())\r
+            {\r
+                NSTopicLL *topic = (NSTopicLL *) OICMalloc(sizeof(NSTopicLL));\r
+                if (topic == nullptr)\r
+                {\r
+                    NS_LOG(ERROR, "new NSTopicLL failed");\r
+                    return NSResult::ERROR;\r
+                }\r
+                topic->topicName = NULL;\r
+                topic->topicName = OICStrdup(it->getTopicName().c_str());\r
+                topic->state = (::NSTopicState)it->getState();\r
+                topic->next = NULL;\r
+                if (topicLL == NULL)\r
+                {\r
+                    topicLL = topic;\r
+                }\r
+                else\r
+                {\r
+                    NSTopicLL *iter = topicLL;\r
+                    NSTopicLL *prev = NULL;\r
+                    while (iter)\r
+                    {\r
+                        prev = iter;\r
+                        iter = (NSTopicLL *) iter->next;\r
+                    }\r
+                    prev->next = topic;\r
+                    topic->next = NULL;\r
+                }\r
+            }\r
+            if (topicLL)\r
+            {\r
+                NSTopicLL *iter = topicLL;\r
+                while (iter)\r
+                {\r
+                    NS_LOG_V(DEBUG, "Topic Name : %s", iter->topicName);\r
+                    NS_LOG_V(DEBUG, "Topic State : %d", (int) iter->state);\r
+                    iter = iter->next;\r
+                }\r
+            }\r
+            NS_LOG_V(DEBUG, "calling Lower layer UpdateTopicList for Provider Id : %s",\r
+                     getProviderId().c_str());\r
+            NSResult result = (NSResult) NSConsumerUpdateTopicList(getProviderId().c_str(), topicLL);\r
+            NS_LOG(DEBUG, "updateTopicList - OUT");\r
+            return result;\r
+        }\r
+\r
+        NSProviderState NSProvider::getProviderState() const\r
+        {\r
+            NS_LOG_V(DEBUG, "getProviderState  state : %d", (int)m_state);\r
+            return m_state;\r
+        }\r
+\r
+        NSProviderSubscribedState NSProvider::getProviderSubscribedState() const\r
+        {\r
+            NS_LOG_V(DEBUG, "getProviderSubscribedState  state : %d", (int)m_subscribedState);\r
+            return m_subscribedState;\r
+        }\r
+\r
         void NSProvider::subscribe()\r
         {\r
-            NS_LOG(DEBUG, "subscribe - IN");\r
-            NSSubscribe(getNSProvider());\r
-            NS_LOG(DEBUG, "subscribe - OUT");\r
+            NS_LOG(DEBUG, "Subscribe - IN");\r
+            NSSubscribe(getProviderId().c_str());\r
+            NS_LOG(DEBUG, "Subscribe - OUT");\r
         }\r
 \r
-        void NSProvider::unSubscribe()\r
+        bool NSProvider::isSubscribed()\r
         {\r
-            NS_LOG(DEBUG, "unSubscribe - IN");\r
-            NSUnsubscribe(getNSProvider());\r
-            NS_LOG(DEBUG, "unSubscribe - OUT");\r
+            NS_LOG(DEBUG, "isSubscribed - IN");\r
+            NS_LOG_V(DEBUG, "Subscribed state : %d", (int)getProviderSubscribedState());\r
+            if (getProviderSubscribedState() == NSProviderSubscribedState::SUBSCRIBED)\r
+                return true;\r
+            return false;\r
         }\r
 \r
-        void NSProvider::SendSyncInfo(uint64_t messageId, NSSyncInfo::NSSyncType type)\r
+        void NSProvider::sendSyncInfo(uint64_t messageId, NSSyncInfo::NSSyncType type)\r
         {\r
             NS_LOG(DEBUG, "SendSyncInfo - IN");\r
             NSConsumerSendSyncInfo(m_providerId.c_str(), messageId, (::NSSyncType)type);\r
@@ -109,32 +201,47 @@ namespace OIC
             return;\r
         }\r
 \r
-        void NSProvider::setListener(NSProvider::MessageReceivedCallback messageHandle,\r
+        void NSProvider::setListener(NSProvider::ProviderStateCallback stateHandle,\r
+                                     NSProvider::MessageReceivedCallback messageHandle,\r
                                      NSProvider::SyncInfoReceivedCallback syncHandle)\r
         {\r
+            NS_LOG(DEBUG, "setListener - IN");\r
+            m_stateCb = stateHandle;\r
             m_messageCb = messageHandle;\r
             m_syncInfoCb = syncHandle;\r
+            NS_LOG(DEBUG, "setListener - OUT");\r
         }\r
 \r
-        NSResult NSProvider::selectInterestTopics(NSTopicsList *topicList)\r
+        NSProvider::ProviderStateCallback NSProvider::getProviderStateReceivedCb() const\r
         {\r
-            NS_LOG(DEBUG, "selectInterestTopics - IN");\r
-            NSProvider *provider = new NSProvider(getProviderId(), topicList);\r
-            NSResult result = (NSResult) NSConsumerSelectInterestTopics(\r
-                                  provider->getNSProvider());\r
-            delete provider;\r
-            NS_LOG(DEBUG, "selectInterestTopics - OUT");\r
-            return result;\r
+            return m_stateCb;\r
         }\r
 \r
-        NSProvider::MessageReceivedCallback NSProvider::getMessageReceivedCb()\r
+        NSProvider::MessageReceivedCallback NSProvider::getMessageReceivedCb() const\r
         {\r
             return m_messageCb;\r
         }\r
 \r
-        NSProvider::SyncInfoReceivedCallback NSProvider::getSyncInfoReceivedCb()\r
+        NSProvider::SyncInfoReceivedCallback NSProvider::getSyncInfoReceivedCb() const\r
         {\r
             return m_syncInfoCb;\r
         }\r
+\r
+        void NSProvider::setTopicList(NSTopicsList *topicsList)\r
+        {\r
+            if (m_topicList != nullptr)\r
+                delete m_topicList;\r
+            m_topicList = topicsList;\r
+        }\r
+\r
+        void NSProvider::setProviderState(const NSProviderState &providerState)\r
+        {\r
+            m_state = providerState;\r
+        }\r
+\r
+        void NSProvider::setProviderSubscribedState(const NSProviderSubscribedState &subscribedState)\r
+        {\r
+            m_subscribedState = subscribedState;\r
+        }\r
     }\r
 }\r
index 3b7e48f..98d8853 100755 (executable)
@@ -44,7 +44,9 @@ void onNotificationPostedCb(OIC::Service::NSMessage *notification)
     std::cout << "topic : " <<  notification->getTopic() << std::endl;\r
 \r
     auto provider = NSConsumerService::getInstance()->getProvider(notification->getProviderId());\r
-    provider->SendSyncInfo(notification->getMessageId(), OIC::Service::NSSyncInfo::NSSyncType::NS_SYNC_READ);\r
+    if (provider != nullptr)\r
+        provider->sendSyncInfo(notification->getMessageId(),\r
+                               OIC::Service::NSSyncInfo::NSSyncType::NS_SYNC_READ);\r
 }\r
 \r
 void onNotificationSyncCb(OIC::Service::NSSyncInfo *sync)\r
@@ -53,32 +55,49 @@ void onNotificationSyncCb(OIC::Service::NSSyncInfo *sync)
     std::cout << "Sync STATE : " << (int) sync->getState() << std::endl;\r
 }\r
 \r
-void onDiscoverNotificationCb(OIC::Service::NSProvider *provider)\r
-{\r
-    std::cout << "notification resource discovered" << std::endl;\r
-    provider->subscribe();\r
-    std::cout << "startSubscribing" << std::endl;\r
-}\r
-\r
-void onProviderChangedCb(OIC::Service::NSProvider *provider, OIC::Service::NSResponse response)\r
+void onProviderStateChangedCb(OIC::Service::NSProviderState state)\r
 {\r
-    std::cout << "Subscription accepted" << std::endl;\r
-    std::cout << "subscribed provider Id : " << provider->getProviderId() << std::endl;\r
-    if (response == OIC::Service::NSResponse::ALLOW)\r
+    std::cout << "onProviderStateChangedCb" << std::endl;\r
+    if (state == OIC::Service::NSProviderState::ALLOW)\r
     {\r
-        provider->setListener(onNotificationPostedCb, onNotificationSyncCb);\r
-        if (mainProvider.empty())\r
-            mainProvider = provider->getProviderId();\r
+        std::cout << "Provider Subscription Accepted" << std::endl;\r
     }\r
-    else if (response == OIC::Service::NSResponse::TOPIC)\r
+    else if (state == OIC::Service::NSProviderState::DENY)\r
     {\r
-        std::cout << "Provider Topic Updated" << std::endl;\r
-        for (auto it : provider->getTopicList()->getTopicsList())\r
+        std::cout << "Provider Subscription Denied" << std::endl;\r
+    }\r
+    else if (state == OIC::Service::NSProviderState::TOPIC)\r
+    {\r
+        OIC::Service::NSProvider *provider = NSConsumerService::getInstance()->getProvider(mainProvider);\r
+        if (provider != nullptr)\r
         {\r
-            std::cout << "Topic Name: " << it->getTopicName() << std::endl;\r
-            std::cout << "Topic state: " << (int) it->getState() << std::endl;\r
+            auto topicList = provider->getTopicList();\r
+            if (topicList != nullptr)\r
+                for (auto it : topicList->getTopicsList())\r
+                {\r
+                    std::cout << "Topic Name: " << it->getTopicName() << std::endl;\r
+                    std::cout << "Topic state: " << (int) it->getState() << std::endl;\r
+                }\r
         }\r
     }\r
+    else if (state == OIC::Service::NSProviderState::STOPPED)\r
+    {\r
+        std::cout << "Provider Stopped" << std::endl;\r
+    }\r
+}\r
+\r
+void onDiscoverNotificationCb(OIC::Service::NSProvider *provider)\r
+{\r
+    std::cout << "notification resource discovered" << std::endl;\r
+    std::cout << "SetListeners for callbacks" << std::endl;\r
+    provider->setListener(onProviderStateChangedCb, onNotificationPostedCb, onNotificationSyncCb);\r
+    if (!provider->isSubscribed())\r
+    {\r
+        std::cout << "startSubscribing" << std::endl;\r
+        provider->subscribe();\r
+    }\r
+    if (mainProvider.empty())\r
+        mainProvider = provider->getProviderId();\r
 }\r
 \r
 void *OCProcessThread(void *ptr)\r
@@ -109,10 +128,6 @@ int main(void)
         return 0;\r
     }\r
 \r
-    NSConsumerService::ConsumerConfig cfg;\r
-    cfg.m_discoverCb = onDiscoverNotificationCb;\r
-    cfg.m_changedCb = onProviderChangedCb;\r
-\r
     pthread_create(&OCThread, NULL, OCProcessThread, NULL);\r
 \r
     std::cout << "Start notification consumer service" << std::endl;\r
@@ -122,8 +137,8 @@ int main(void)
 \r
         std::cout << "1. Start Consumer" << std::endl;\r
         std::cout << "2. Stop Consumer" << std::endl;\r
-        std::cout << "3. getInterestTopics" << std::endl;\r
-        std::cout << "4. selectInterestTopics" << std::endl;\r
+        std::cout << "3. GetTopicList" << std::endl;\r
+        std::cout << "4. UpdateTopicList" << std::endl;\r
 #ifdef WITH_CLOUD\r
         std::cout << "5. Enable  NS Consumer RemoteService" << std::endl;\r
 #endif\r
@@ -135,15 +150,15 @@ int main(void)
         {\r
             case 1:\r
                 std::cout << "1. Start the Notification Consumer" << std::endl;\r
-                NSConsumerService::getInstance()->Start(cfg);\r
+                NSConsumerService::getInstance()->start(onDiscoverNotificationCb);\r
                 break;\r
             case 2:\r
                 std::cout << "2. Stop the Notification Consumer" << std::endl;\r
-                NSConsumerService::getInstance()->Stop();\r
+                NSConsumerService::getInstance()->stop();\r
                 break;\r
             case 3:\r
                 {\r
-                    std::cout <<  "getInterestTopics" << std::endl;\r
+                    std::cout <<  "GetTopicList" << std::endl;\r
                     OIC::Service::NSProvider *provider = NSConsumerService::getInstance()->getProvider(mainProvider);\r
                     if (provider != nullptr)\r
                     {\r
@@ -159,16 +174,16 @@ int main(void)
                 break;\r
             case 4:\r
                 {\r
-                    std::cout <<  "selectInterestTopics" << std::endl;\r
+                    std::cout <<  "UpdateTopicList" << std::endl;\r
                     OIC::Service::NSProvider *provider = NSConsumerService::getInstance()->getProvider(mainProvider);\r
                     if (provider != nullptr)\r
                     {\r
                         NSTopicsList *topicList = new NSTopicsList();\r
-                        topicList->addTopic("OCF_TOPIC1", NSTopic::NSTopicState::UNSUBSCRIBED);\r
-                        topicList->addTopic("OCF_TOPIC2", NSTopic::NSTopicState::UNSUBSCRIBED);\r
+                        topicList->addTopic("OCF_TOPIC1", NSTopic::NSTopicState::SUBSCRIBED);\r
+                        topicList->addTopic("OCF_TOPIC2", NSTopic::NSTopicState::SUBSCRIBED);\r
                         topicList->addTopic("OCF_TOPIC3", NSTopic::NSTopicState::UNSUBSCRIBED);\r
 \r
-                        provider->selectInterestTopics(topicList);\r
+                        provider->updateTopicList(topicList);\r
                     }\r
                 }\r
                 break;\r
@@ -178,7 +193,7 @@ int main(void)
                     std::cout << "5. Enable NS Consumer RemoteService" << std::endl;\r
                     std::cout << "Input the Server Address :";\r
                     std::cin >> REMOTE_SERVER_ADDRESS;\r
-                    NSConsumerService::getInstance()->EnableRemoteService(REMOTE_SERVER_ADDRESS);\r
+                    NSConsumerService::getInstance()->enableRemoteService(REMOTE_SERVER_ADDRESS);\r
                     break;\r
                 }\r
 #endif\r
index 8f7e637..ffef86b 100755 (executable)
@@ -67,7 +67,7 @@ void subscribeRequestCallback(OIC::Service::NSConsumer *consumer)
     std::cout << "Consumer Device ID: " << consumer->getConsumerId() << std::endl;\r
     if (mainConsumer.empty())\r
         mainConsumer = consumer->getConsumerId();\r
-    consumer->acceptSubscription(consumer, true);\r
+    consumer->acceptSubscription(true);\r
 }\r
 \r
 void syncCallback(OIC::Service::NSSyncInfo *sync)\r
@@ -100,12 +100,12 @@ int main()
         std::cout << "3. SendMessage " << std::endl;\r
         std::cout << "4. SendSyncInfo" << std::endl;\r
 \r
-        std::cout << "5. AddTopic" << std::endl;\r
-        std::cout << "6. DeleteTopic" << std::endl;\r
-        std::cout << "7. SelectTopic" << std::endl;\r
-        std::cout << "8. UnselectTopic" << std::endl;\r
-        std::cout << "9. GetConsumerTopics" << std::endl;\r
-        std::cout << "10. GetTopics" << std::endl;\r
+        std::cout << "5. RegisterTopic" << std::endl;\r
+        std::cout << "6. UnregisterTopic" << std::endl;\r
+        std::cout << "7. SetTopic" << std::endl;\r
+        std::cout << "8. UnsetTopic" << std::endl;\r
+        std::cout << "9. GetConsumerTopicList" << std::endl;\r
+        std::cout << "10. GetRegisteredTopicList" << std::endl;\r
 #ifdef WITH_CLOUD\r
         std::cout << "11. Enable NS Provider RemoteService" << std::endl;\r
         std::cout << "12. Disable NS Provider RemoteService" << std::endl;\r
@@ -125,9 +125,9 @@ int main()
                     NSProviderService::ProviderConfig cfg;\r
                     cfg.m_subscribeRequestCb = subscribeRequestCallback;\r
                     cfg.m_syncInfoCb = syncCallback;\r
-                    cfg.policy = true;\r
+                    cfg.subControllability = true;\r
 \r
-                    NSProviderService::getInstance()->Start(cfg);\r
+                    NSProviderService::getInstance()->start(cfg);\r
                     break;\r
                 }\r
             case 2:\r
@@ -136,15 +136,16 @@ int main()
                     NSProviderService::ProviderConfig cfg;\r
                     cfg.m_subscribeRequestCb = subscribeRequestCallback;\r
                     cfg.m_syncInfoCb = syncCallback;\r
-                    cfg.policy = false;\r
+                    cfg.subControllability = false;\r
 \r
-                    NSProviderService::getInstance()->Start(cfg);\r
+                    NSProviderService::getInstance()->start(cfg);\r
                     break;\r
                 }\r
             case 3:\r
                 {\r
                     std::cout << "SendMessage" << std::endl;\r
 \r
+                    std::string dummy;\r
                     std::string title;\r
                     std::string body;\r
                     std::string topic;\r
@@ -152,19 +153,20 @@ int main()
                     std::cout << "id : " << ++id << std::endl;\r
                     std::cout << "title : ";\r
 \r
-                    std::cin >> title;\r
+                    std::getline(std::cin, dummy);\r
+                    std::getline(std::cin, title);\r
 \r
                     std::cout << "body : ";\r
-                    std::cin >> body;\r
+                    std::getline(std::cin, body);\r
 \r
                     std::cout << "topic : ";\r
-                    std::cin >> topic;\r
+                    std::getline(std::cin, topic);\r
 \r
                     std::cout << "app - mTitle : " << title << std::endl;\r
                     std::cout << "app - mContentText : " << body << std::endl;\r
                     std::cout << "app - mTopic : " << topic << std::endl;\r
 \r
-                    OIC::Service::NSMessage *msg = NSProviderService::getInstance()->CreateMessage();\r
+                    OIC::Service::NSMessage *msg = NSProviderService::getInstance()->createMessage();\r
 \r
                     msg->setType(OIC::Service::NSMessage::NSMessageType::NS_MESSAGE_INFO);\r
                     msg->setTitle(title.c_str());\r
@@ -172,53 +174,53 @@ int main()
                     msg->setSourceName("OCF");\r
                     msg->setTopic(topic);\r
                     mainMessageId = msg->getMessageId();\r
+                    std::cout << "ProviderID for Message : " << msg->getProviderId() << std::endl;\r
 \r
-                    NSProviderService::getInstance()->SendMessage(msg);\r
+                    NSProviderService::getInstance()->sendMessage(msg);\r
 \r
                     break;\r
                 }\r
             case 4:\r
                 {\r
                     std::cout <<  "SendSyncInfo" << std::endl;\r
-                    NSProviderService::getInstance()->SendSyncInfo(mainMessageId,\r
+                    NSProviderService::getInstance()->sendSyncInfo(mainMessageId,\r
                             OIC::Service::NSSyncInfo::NSSyncType::NS_SYNC_READ);\r
                     break;\r
                 }\r
 \r
             case 5:\r
-                std::cout <<  "AddTopic" << std::endl;\r
-                NSProviderService::getInstance()->AddTopic("OCF_TOPIC1");\r
-                NSProviderService::getInstance()->AddTopic("OCF_TOPIC2");\r
-                NSProviderService::getInstance()->AddTopic("OCF_TOPIC3");\r
-                NSProviderService::getInstance()->AddTopic("OCF_TOPIC4");\r
+                std::cout <<  "RegisterTopic" << std::endl;\r
+                NSProviderService::getInstance()->registerTopic("OCF_TOPIC1");\r
+                NSProviderService::getInstance()->registerTopic("OCF_TOPIC2");\r
+                NSProviderService::getInstance()->registerTopic("OCF_TOPIC3");\r
+                NSProviderService::getInstance()->registerTopic("OCF_TOPIC4");\r
                 break;\r
 \r
             case 6:\r
-                std::cout <<  "DeleteTopic" << std::endl;\r
-                NSProviderService::getInstance()->DeleteTopic("OCF_TOPIC2");\r
+                std::cout <<  "UnregisterTopic" << std::endl;\r
+                NSProviderService::getInstance()->unregisterTopic("OCF_TOPIC2");\r
                 break;\r
 \r
             case 7:\r
                 {\r
-                    std::cout <<  "SelectTopic" << std::endl;\r
+                    std::cout <<  "SetTopic" << std::endl;\r
                     OIC::Service::NSConsumer *consumer = NSProviderService::getInstance()->getConsumer(mainConsumer);\r
                     if (consumer != nullptr)\r
                     {\r
-                        consumer->selectTopic("OCF_TOPIC1");\r
-                        consumer->selectTopic("OCF_TOPIC2");\r
-                        consumer->selectTopic("OCF_TOPIC3");\r
-                        consumer->selectTopic("OCF_TOPIC4");\r
+                        consumer->setTopic("OCF_TOPIC1");\r
+                        consumer->setTopic("OCF_TOPIC2");\r
+                        consumer->setTopic("OCF_TOPIC3");\r
                         std::cout <<  "SelectTopic completed" << std::endl;\r
                     }\r
                     break;\r
                 }\r
             case 8:\r
                 {\r
-                    std::cout <<  "UnSelectTopic" << std::endl;\r
+                    std::cout <<  "UnsetTopic" << std::endl;\r
                     OIC::Service::NSConsumer *consumer = NSProviderService::getInstance()->getConsumer(mainConsumer);\r
                     if (consumer != nullptr)\r
                     {\r
-                        consumer->unselectTopic("OCF_TOPIC1");\r
+                        consumer->unsetTopic("OCF_TOPIC1");\r
                         std::cout <<  "UnSelectTopic completed" << std::endl;\r
                     }\r
                     break;\r
@@ -227,11 +229,11 @@ int main()
 \r
             case 9:\r
                 {\r
-                    std::cout <<  "GetConsumerTopics" << std::endl;\r
+                    std::cout <<  "GetConsumerTopicList" << std::endl;\r
                     OIC::Service::NSConsumer *consumer = NSProviderService::getInstance()->getConsumer(mainConsumer);\r
                     if (consumer != nullptr)\r
                     {\r
-                        auto nsTopics = consumer->getConsumerTopics();\r
+                        auto nsTopics = consumer->getConsumerTopicList();\r
                         if (nsTopics != nullptr)\r
                         {\r
                             for (auto it : nsTopics->getTopicsList())\r
@@ -242,15 +244,15 @@ int main()
                             }\r
                             delete nsTopics;\r
                         }\r
-                        std::cout <<  "GetConsumerTopics completed" << std::endl;\r
+                        std::cout <<  "GetConsumerTopicList completed" << std::endl;\r
                     }\r
                 }\r
                 break;\r
 \r
             case 10:\r
                 {\r
-                    std::cout <<  "GetTopics" << std::endl;\r
-                    auto nsTopics = NSProviderService::getInstance()->GetTopics();\r
+                    std::cout <<  "GetRegisteredTopicList" << std::endl;\r
+                    auto nsTopics = NSProviderService::getInstance()->getRegisteredTopicList();\r
                     for (auto it : nsTopics->getTopicsList())\r
                     {\r
 \r
@@ -266,22 +268,22 @@ int main()
                     std::cout << "11. Enable NS Provider RemoteService" << std::endl;\r
                     std::cout << "Input the Server Address :";\r
                     std::cin >> REMOTE_SERVER_ADDRESS;\r
-                    NSProviderService::getInstance()->EnableRemoteService(REMOTE_SERVER_ADDRESS);\r
+                    NSProviderService::getInstance()->enableRemoteService(REMOTE_SERVER_ADDRESS);\r
                     break;\r
                 }\r
             case 12:\r
                 {\r
                     std::cout << "12. Disable NS Provider RemoteService" << std::endl;\r
                     std::cout << "Input the Server Address :";\r
-                    NSProviderService::getInstance()->DisableRemoteService(REMOTE_SERVER_ADDRESS);\r
+                    NSProviderService::getInstance()->disableRemoteService(REMOTE_SERVER_ADDRESS);\r
                     break;\r
                 }\r
 #endif\r
             case 13:\r
-                NSProviderService::getInstance()->Stop();\r
+                NSProviderService::getInstance()->stop();\r
                 break;\r
             case 0:\r
-                NSProviderService::getInstance()->Stop();\r
+                NSProviderService::getInstance()->stop();\r
                 isExit = true;\r
                 break;\r
             default:\r
index 0ead67f..040dd21 100755 (executable)
@@ -78,14 +78,33 @@ if env.get('WITH_CLOUD') == True:
 ######################################################################
 # Source files and Targets
 ######################################################################
+notificationCommonStaticObjs = [
+       notification_env.Object('../common/NSMediaContents.cpp'),
+       notification_env.Object('../common/NSMessage.cpp'),
+       notification_env.Object('../common/NSSyncInfo.cpp'),
+       notification_env.Object('../common/NSTopic.cpp'),
+       notification_env.Object('../common/NSTopicsList.cpp')]
+
+notificationCommonSharedObjs = [
+       notification_env.SharedObject('../common/NSMediaContents.cpp'),
+       notification_env.SharedObject('../common/NSMessage.cpp'),
+       notification_env.SharedObject('../common/NSSyncInfo.cpp'),
+       notification_env.SharedObject('../common/NSTopic.cpp'),
+       notification_env.SharedObject('../common/NSTopicsList.cpp')]
 
 notification_provider_src = [
-       env.Glob('src/*.cpp'),env.Glob('../common/*.cpp')]
+       env.Glob('src/*.cpp'),notificationCommonSharedObjs]
 
 providersdk = notification_env.SharedLibrary('notification_provider_wrapper', notification_provider_src)
 notification_env.InstallTarget(providersdk, 'libnotification_provider_wrapper')
 notification_env.UserInstallTargetLib(providersdk, 'libnotification_provider_wrapper')
 
+notification_provider_src = [
+       env.Glob('src/*.cpp'),notificationCommonStaticObjs]
+
 providersdk = notification_env.StaticLibrary('notification_provider_wrapper', notification_provider_src)
 notification_env.InstallTarget(providersdk, 'libnotification_provider_wrapper')
 notification_env.UserInstallTargetLib(providersdk, 'libnotification_provider_wrapper')
+
+Export('notificationCommonStaticObjs')
+Export('notificationCommonSharedObjs')
index c71c666..5a3b8c2 100755 (executable)
@@ -79,30 +79,29 @@ namespace OIC
                 /**\r
                       * This method is for setting icon image for the Notification service media contents.\r
                       *\r
-                      * @param consumer - NSConsumer.\r
                       * @param accepted - as bool.\r
                       */\r
-                int acceptSubscription(NSConsumer *consumer, bool accepted);\r
+                int acceptSubscription(bool accepted);\r
 \r
                 /**\r
                      * Select a topic name for a consumer\r
                      * @param[in]  topicName Topic name to select\r
                      * @return :: OK or result code of NSResult\r
                      */\r
-                NSResult selectTopic(const std::string &topicName);\r
+                NSResult setTopic(const std::string &topicName);\r
 \r
                 /**\r
                      * Unselect a topic from the topic list for consumer\r
                      * @param[in]  topicName Topic name to unselect\r
                      * @return :: OK or result code of NSResult\r
                      */\r
-                NSResult unselectTopic(const std::string &topicName);\r
+                NSResult unsetTopic(const std::string &topicName);\r
 \r
                 /**\r
                      * Request topic list with selection state for the consumer\r
                      * @return :: Topic list\r
                      */\r
-                NSTopicsList *getConsumerTopics();\r
+                NSTopicsList *getConsumerTopicList();\r
 \r
             private:\r
                 ::NSConsumer *getNSConsumer();\r
index 06326dc..033b7e3 100755 (executable)
@@ -63,7 +63,9 @@ namespace OIC
                 /**\r
                       * @struct   ProviderConfig\r
                       * @brief Provider sets this following configuration for registering callbacks and configs\r
-                      *\r
+                      *  Set the subControllability, for notification servcie refering to following\r
+                      *  if subControllability, is true, provider decides to allow or deny for all the subscribing consumers.\r
+                      *  Otherwise(subControllability, is false) consumer decides to request subscription to discovered providers.\r
                       */\r
                 typedef struct\r
                 {\r
@@ -72,12 +74,9 @@ namespace OIC
                     /** m_syncInfoCb - MessageSynchronizedCallback callback listener.*/\r
                     MessageSynchronizedCallback m_syncInfoCb;\r
 \r
-                    /* Set the policy for notification servcie refering to following\r
-                                 * if policy is true, provider decides to allow or deny for all the subscribing consumers.\r
-                                 * Otherwise(policy is false) consumer decides to request subscription to discovered providers.\r
-                                 */\r
-                    bool policy;\r
-                    /* User Information */\r
+                    /** subControllability - for setting the subscription controllability for Consumer */\r
+                    bool subControllability;\r
+                    /** userInfo - user defined information */\r
                     std::string userInfo;\r
                 } ProviderConfig;\r
 \r
@@ -90,39 +89,38 @@ namespace OIC
 \r
                 /**\r
                       * Initialize notification service for provider\r
-                      * @param[in]  policy   Accepter\r
                       * @param[in]  config   ProviderConfig Callback function pointers to onConsumerSubscribed,\r
                       * and onMessageSynchronized function listeners\r
                       * @return :: result code of Provider Service\r
                       */\r
-                NSResult Start(ProviderConfig config);\r
+                NSResult start(ProviderConfig config);\r
 \r
                 /**\r
                       * Terminate notification service for provider\r
                       * @return :: result code of Provider Service\r
                       */\r
-                NSResult Stop();\r
+                NSResult stop();\r
 \r
                 /**\r
                       * Request to publish resource to cloud server\r
-                      * @param[in]  server address combined with IP address and port number using delimiter :\r
+                      * @param[in]  serverAddress combined with IP address and port number using delimiter :\r
                       * @return  result code of Provider Service\r
                       */\r
-                NSResult EnableRemoteService(const std::string &serverAddress);\r
+                NSResult enableRemoteService(const std::string &serverAddress);\r
 \r
                 /**\r
                       * Request to cancel remote service using cloud server\r
-                      * @param[in]  server address combined with IP address and port number using delimiter :\r
+                      * @param[in]  serverAddress combined with IP address and port number using delimiter :\r
                       * @return  result code of Provider Service\r
                       */\r
-                NSResult DisableRemoteService(const std::string &serverAddress);\r
+                NSResult disableRemoteService(const std::string &serverAddress);\r
 \r
                 /**\r
                       * Send notification message to all subscribers\r
                       * @param[in]  msg  Notification message including id, title, contentText\r
                       * @return :: result code of Provider Service\r
                       */\r
-                NSResult SendMessage(NSMessage *msg);\r
+                NSResult sendMessage(NSMessage *msg);\r
 \r
 \r
                 /**\r
@@ -130,41 +128,33 @@ namespace OIC
                       * @param[in]  messageId  Notification message to synchronize the status\r
                       * @param[in]  type  NotificationSyncType of the SyncInfo message\r
                       */\r
-                void SendSyncInfo(uint64_t messageId, NSSyncInfo::NSSyncType type);\r
+                void sendSyncInfo(uint64_t messageId, NSSyncInfo::NSSyncType type);\r
 \r
                 /**\r
                      * Initialize NSMessage class, service sets message id and provider(device) id\r
-                     * @return ::NSMessage *\r
+                     * @return NSMessage *\r
                      */\r
-                NSMessage *CreateMessage();\r
-\r
-                /**\r
-                      *  request to get NSConsumer pointer\r
-                      * @param id -id as string\r
-                      *\r
-                      * @return pointer to NSConsumer\r
-                      */\r
-                NSConsumer *getConsumer(const std::string &id);\r
+                NSMessage *createMessage();\r
 \r
                 /**\r
                      * Add topic to topic list which is located in provider service storage\r
                      * @param[in]  topicName Topic name to add\r
                      * @return :: OK or result code of NSResult\r
                      */\r
-                NSResult AddTopic(const std::string &topicName);\r
+                NSResult registerTopic(const std::string &topicName);\r
 \r
                 /**\r
                      * Delete topic from topic list\r
                      * @param[in]  topicName Topic name to delete\r
                      * @return :: OK or result code of NSResult\r
                      */\r
-                NSResult DeleteTopic(const std::string &topicName);\r
+                NSResult unregisterTopic(const std::string &topicName);\r
 \r
                 /**\r
                      * Request topics list already registered by provider user\r
                      * @return :: Topic list\r
                      */\r
-                NSTopicsList *GetTopics();\r
+                NSTopicsList *getRegisteredTopicList();\r
 \r
                 /**\r
                       *  get Provider config values\r
@@ -173,6 +163,14 @@ namespace OIC
                 ProviderConfig getProviderConfig();\r
 \r
                 /**\r
+                      *  request to get NSConsumer pointer\r
+                      * @param id -id as string\r
+                      *\r
+                      * @return pointer to NSConsumer\r
+                      */\r
+                NSConsumer *getConsumer(const std::string &id);\r
+\r
+                /**\r
                       *  get list of Consumers accepted.\r
                       * @return m_acceptedConsumers -list of accepted Consumers\r
                       */\r
index 58a0fae..a81f875 100755 (executable)
@@ -40,7 +40,7 @@ namespace OIC
         {\r
             if (consumer != nullptr)\r
             {\r
-                m_consumerId = consumer->consumerId;\r
+                m_consumerId.assign(consumer->consumerId, NS_UTILS_UUID_STRING_SIZE - 1);\r
             }\r
         }\r
 \r
@@ -49,40 +49,39 @@ namespace OIC
             return m_consumerId;\r
         }\r
 \r
-        int NSConsumer::acceptSubscription(NSConsumer *consumer, bool accepted)\r
+        int NSConsumer::acceptSubscription(bool accepted)\r
         {\r
             NS_LOG(DEBUG, "acceptSubscription - IN");\r
-            if (consumer != nullptr)\r
-                return NSAcceptSubscription(consumer->getNSConsumer(), accepted);\r
+            NSResult result = (NSResult) NSAcceptSubscription(getConsumerId().c_str(), accepted);\r
             NS_LOG(DEBUG, "acceptSubscription - OUT");\r
-            return NS_ERROR;\r
+            return (int) result;\r
         }\r
 \r
-        NSResult NSConsumer::selectTopic(const std::string &topicName)\r
+        NSResult NSConsumer::setTopic(const std::string &topicName)\r
         {\r
-            NS_LOG(DEBUG, "selectTopic - IN");\r
-            NSResult result = (NSResult) NSProviderSelectTopic(OICStrdup(getConsumerId().c_str()),\r
-                              OICStrdup(topicName.c_str()));\r
-            NS_LOG(DEBUG, "selectTopic - OUT");\r
+            NS_LOG(DEBUG, "setTopic - IN");\r
+            NSResult result = (NSResult) NSProviderSetConsumerTopic(getConsumerId().c_str(),\r
+                              topicName.c_str());\r
+            NS_LOG(DEBUG, "setTopic - OUT");\r
             return result;\r
         }\r
 \r
-        NSResult NSConsumer::unselectTopic(const std::string &topicName)\r
+        NSResult NSConsumer::unsetTopic(const std::string &topicName)\r
         {\r
-            NS_LOG(DEBUG, "unselectTopic - IN");\r
-            NSResult result = (NSResult) NSProviderUnselectTopic(OICStrdup(getConsumerId().c_str()),\r
-                              OICStrdup(topicName.c_str()));\r
-            NS_LOG(DEBUG, "unselectTopic - OUT");\r
+            NS_LOG(DEBUG, "unsetTopic - IN");\r
+            NSResult result = (NSResult) NSProviderUnsetConsumerTopic(getConsumerId().c_str(),\r
+                              topicName.c_str());\r
+            NS_LOG(DEBUG, "unsetTopic - OUT");\r
             return result;\r
         }\r
 \r
-        NSTopicsList *NSConsumer::getConsumerTopics()\r
+        NSTopicsList *NSConsumer::getConsumerTopicList()\r
         {\r
-            NS_LOG(DEBUG, "getConsumerTopics - IN");\r
-            ::NSTopicLL *topics = NSProviderGetConsumerTopics(OICStrdup(getConsumerId().c_str()));\r
+            NS_LOG(DEBUG, "getConsumerTopicList - IN");\r
+            ::NSTopicLL *topics = NSProviderGetConsumerTopics(getConsumerId().c_str());\r
 \r
             NSTopicsList *nsTopics = new NSTopicsList(topics);\r
-            NS_LOG(DEBUG, "getConsumerTopics - OUT");\r
+            NS_LOG(DEBUG, "getConsumerTopicList - OUT");\r
             return nsTopics;\r
         }\r
     }\r
index c2e2855..8b1364b 100755 (executable)
@@ -40,7 +40,7 @@ namespace OIC
             NSProviderService::getInstance()->getAcceptedConsumers().push_back(nsConsumer);\r
             if (NSProviderService::getInstance()->getProviderConfig().m_subscribeRequestCb != NULL)\r
             {\r
-                NS_LOG(DEBUG, "initiating the callback");\r
+                NS_LOG(DEBUG, "initiating the callback for consumer subscribed");\r
                 NSProviderService::getInstance()->getProviderConfig().m_subscribeRequestCb(nsConsumer);\r
             }\r
             NS_LOG(DEBUG, "onConsumerSubscribedCallback - OUT");\r
@@ -52,7 +52,7 @@ namespace OIC
             NSSyncInfo *nsSyncInfo = new NSSyncInfo(syncInfo);\r
             if (NSProviderService::getInstance()->getProviderConfig().m_syncInfoCb != NULL)\r
             {\r
-                NS_LOG(DEBUG, "initiating the callback");\r
+                NS_LOG(DEBUG, "initiating the callback for synchronized");\r
                 NSProviderService::getInstance()->getProviderConfig().m_syncInfoCb(nsSyncInfo);\r
             }\r
             delete nsSyncInfo;\r
@@ -63,7 +63,7 @@ namespace OIC
         {\r
             ::NSMessage *nsMsg = new ::NSMessage;\r
             nsMsg->messageId = msg->getMessageId();\r
-            OICStrcpy(nsMsg->providerId, msg->getProviderId().length(), msg->getProviderId().c_str());\r
+            OICStrcpy(nsMsg->providerId, NS_UTILS_UUID_STRING_SIZE, msg->getProviderId().c_str());\r
             nsMsg->sourceName = OICStrdup(msg->getSourceName().c_str());\r
             nsMsg->type = (::NSMessageType) msg->getType();\r
             nsMsg->dateTime = OICStrdup(msg->getTime().c_str());\r
@@ -95,133 +95,127 @@ namespace OIC
             return &s_instance;\r
         }\r
 \r
-        NSResult NSProviderService::Start(NSProviderService::ProviderConfig config)\r
+        NSResult NSProviderService::start(NSProviderService::ProviderConfig config)\r
         {\r
-            NS_LOG(DEBUG, "Start - IN");\r
+            NS_LOG(DEBUG, "start - IN");\r
 \r
             m_config = config;\r
             NSProviderConfig nsConfig;\r
             nsConfig.subRequestCallback = onConsumerSubscribedCallback;\r
             nsConfig.syncInfoCallback = onMessageSynchronizedCallback;\r
-            nsConfig.policy = config.policy;\r
+            nsConfig.subControllability = config.subControllability;\r
             nsConfig.userInfo = OICStrdup(config.userInfo.c_str());\r
 \r
             NSResult result = (NSResult) NSStartProvider(nsConfig);\r
-            NS_LOG(DEBUG, "Start - OUT");\r
+            NS_LOG(DEBUG, "start - OUT");\r
             return result;\r
         }\r
 \r
-        NSResult NSProviderService::Stop()\r
+        NSResult NSProviderService::stop()\r
         {\r
-            NS_LOG(DEBUG, "Stop - IN");\r
+            NS_LOG(DEBUG, "stop - IN");\r
             NSResult result = (NSResult) NSStopProvider();\r
-            NS_LOG(DEBUG, "Stop - OUT");\r
+            NS_LOG(DEBUG, "stop - OUT");\r
             return result;\r
         }\r
 \r
-        NSResult NSProviderService::EnableRemoteService(const std::string &serverAddress)\r
+        NSResult NSProviderService::enableRemoteService(const std::string &serverAddress)\r
         {\r
-            NS_LOG(DEBUG, "EnableRemoteService - IN");\r
+            NS_LOG(DEBUG, "enableRemoteService - IN");\r
+            NS_LOG_V(DEBUG, "Server Address : %s", serverAddress.c_str());\r
             NSResult result = NSResult::ERROR;\r
 #ifdef WITH_CLOUD\r
             result = (NSResult) NSProviderEnableRemoteService(OICStrdup(serverAddress.c_str()));\r
 #else\r
+            (void) serverAddress;\r
             NS_LOG(ERROR, "Remote Services feature is not enabled in the Build");\r
 #endif\r
-            NS_LOG(DEBUG, "EnableRemoteService - OUT");\r
+            NS_LOG(DEBUG, "enableRemoteService - OUT");\r
             return result;\r
         }\r
 \r
-        NSResult NSProviderService::DisableRemoteService(const std::string &serverAddress)\r
+        NSResult NSProviderService::disableRemoteService(const std::string &serverAddress)\r
         {\r
-            NS_LOG(DEBUG, "DisableRemoteService - IN");\r
+            NS_LOG(DEBUG, "disableRemoteService - IN");\r
+            NS_LOG_V(DEBUG, "Server Address : %s", serverAddress.c_str());\r
             NSResult result = NSResult::ERROR;\r
 #ifdef WITH_CLOUD\r
             result = (NSResult) NSProviderDisableRemoteService(OICStrdup(serverAddress.c_str()));\r
 #else\r
+            (void) serverAddress;\r
             NS_LOG(ERROR, "Remote Services feature is not enabled in the Build");\r
 #endif\r
-            NS_LOG(DEBUG, "DisableRemoteService - OUT");\r
+            NS_LOG(DEBUG, "disableRemoteService - OUT");\r
             return result;\r
         }\r
 \r
-        NSResult NSProviderService::SendMessage(NSMessage *msg)\r
+        NSResult NSProviderService::sendMessage(NSMessage *msg)\r
         {\r
-            NS_LOG(DEBUG, "SendMessage - IN");\r
+            NS_LOG(DEBUG, "sendMessage - IN");\r
             NSResult result = NSResult::ERROR;\r
             if (msg != nullptr)\r
             {\r
                 ::NSMessage *nsMsg = getNSMessage(msg);\r
+\r
+                NS_LOG_V(DEBUG, "nsMsg->providerId : %s", nsMsg->providerId);\r
                 result = (NSResult) NSSendMessage(nsMsg);\r
                 delete nsMsg->mediaContents;\r
                 delete nsMsg;\r
             }\r
             else\r
+            {\r
                 NS_LOG(DEBUG, "Empty Message");\r
-            NS_LOG(DEBUG, "SendMessage - OUT");\r
+            }\r
+            NS_LOG(DEBUG, "sendMessage - OUT");\r
             return result;\r
         }\r
 \r
-        void NSProviderService::SendSyncInfo(uint64_t messageId,\r
+        void NSProviderService::sendSyncInfo(uint64_t messageId,\r
                                              NSSyncInfo::NSSyncType type)\r
         {\r
-            NS_LOG(DEBUG, "SendSyncInfo - IN");\r
+            NS_LOG(DEBUG, "sendSyncInfo - IN");\r
             NSProviderSendSyncInfo(messageId, (NSSyncType)type);\r
-            NS_LOG(DEBUG, "SendSyncInfo - OUT");\r
+            NS_LOG(DEBUG, "sendSyncInfo - OUT");\r
             return;\r
         }\r
 \r
-        NSMessage *NSProviderService::CreateMessage()\r
+        NSMessage *NSProviderService::createMessage()\r
         {\r
-            NS_LOG(DEBUG, "CreateMessage - IN");\r
+            NS_LOG(DEBUG, "createMessage - IN");\r
 \r
             ::NSMessage *message = NSCreateMessage();\r
             NSMessage *nsMessage = new NSMessage(message);\r
 \r
-            NS_LOG_V(DEBUG, "Message ID : %lld", nsMessage->getMessageId());\r
+            NS_LOG_V(DEBUG, "Message ID : %lld", (long long int) nsMessage->getMessageId());\r
             NS_LOG_V(DEBUG, "Provider ID : %s", nsMessage->getProviderId().c_str());\r
-            NS_LOG(DEBUG, "CreateMessage - OUT");\r
+            NS_LOG(DEBUG, "createMessage - OUT");\r
 \r
             return nsMessage;\r
         }\r
 \r
-        NSConsumer *NSProviderService::getConsumer(const std::string &id)\r
+        NSResult NSProviderService::registerTopic(const std::string &topicName)\r
         {\r
-            for (auto it : getAcceptedConsumers())\r
-            {\r
-                if (it->getConsumerId() == id)\r
-                {\r
-                    NS_LOG(DEBUG, "getConsumer : Found Consumer with given ID");\r
-                    return it;\r
-                }\r
-            }\r
-            NS_LOG(DEBUG, "getConsumer : Not Found Consumer with given ID");\r
-            return NULL;\r
-        }\r
-\r
-        NSResult NSProviderService::AddTopic(const std::string &topicName)\r
-        {\r
-            NS_LOG(DEBUG, "AddTopic - IN");\r
-            NSResult result = (NSResult) NSProviderAddTopic(OICStrdup(topicName.c_str()));\r
-            NS_LOG(DEBUG, "AddTopic - OUT");\r
+            NS_LOG(DEBUG, "registerTopic - IN");\r
+            NSResult result = (NSResult) NSProviderRegisterTopic(topicName.c_str());\r
+            NS_LOG(DEBUG, "registerTopic - OUT");\r
             return result;\r
         }\r
 \r
-        NSResult NSProviderService::DeleteTopic(const std::string &topicName)\r
+        NSResult NSProviderService::unregisterTopic(const std::string &topicName)\r
         {\r
-            NS_LOG(DEBUG, "DeleteTopic - IN");\r
-            NSResult result = (NSResult) NSProviderDeleteTopic(OICStrdup(topicName.c_str()));\r
-            NS_LOG(DEBUG, "DeleteTopic - OUT");\r
+            NS_LOG(DEBUG, "unregisterTopic - IN");\r
+            NSResult result = (NSResult) NSProviderUnregisterTopic(topicName.c_str());\r
+            NS_LOG(DEBUG, "unregisterTopic - OUT");\r
             return result;\r
         }\r
 \r
-        NSTopicsList *NSProviderService::GetTopics()\r
+        NSTopicsList *NSProviderService::getRegisteredTopicList()\r
         {\r
-            NS_LOG(DEBUG, "GetTopics - IN");\r
+            NS_LOG(DEBUG, "getRegisteredTopicList - IN");\r
             ::NSTopicLL *topics = NSProviderGetTopics();\r
 \r
             NSTopicsList *nsTopics = new NSTopicsList(topics);\r
-            NS_LOG(DEBUG, "GetTopics - OUT");\r
+            NS_LOG(DEBUG, "getRegisteredTopicList - OUT");\r
             return nsTopics;\r
         }\r
 \r
@@ -230,7 +224,21 @@ namespace OIC
             return m_config;\r
         }\r
 \r
-        std::list<NSConsumer *>& NSProviderService::getAcceptedConsumers()\r
+        NSConsumer *NSProviderService::getConsumer(const std::string &id)\r
+        {\r
+            for (auto it : getAcceptedConsumers())\r
+            {\r
+                if (it->getConsumerId() == id)\r
+                {\r
+                    NS_LOG(DEBUG, "getConsumer : Found Consumer with given ID");\r
+                    return it;\r
+                }\r
+            }\r
+            NS_LOG(DEBUG, "getConsumer : Not Found Consumer with given ID");\r
+            return NULL;\r
+        }\r
+\r
+        std::list<NSConsumer *> &NSProviderService::getAcceptedConsumers()\r
         {\r
             return m_acceptedConsumers;\r
         }\r
index 686e7df..87cb5b2 100644 (file)
 namespace
 {
     NSProviderSimulator g_providerSimul;
-     OIC::Service::NSProvider * g_provider;
+    OIC::Service::NSProvider *g_provider;
 
     std::atomic_bool g_isStartedStack(false);
 
-    std::chrono::milliseconds g_waitForResponse(2000);
+    std::chrono::milliseconds g_waitForResponse(1000);
 
     std::condition_variable responseCon;
     std::mutex mutexForCondition;
@@ -58,137 +58,128 @@ namespace
 
 class TestWithMock: public testing::Test
 {
-public:
-    MockRepository mocks;
+    public:
+        MockRepository mocks;
 
-protected:
-    virtual ~TestWithMock() noexcept(noexcept(std::declval<Test>().~Test()))
-    {
-
-    }
-
-    virtual void TearDown()
-    {
-        try
+    protected:
+        virtual ~TestWithMock() noexcept(noexcept(std::declval<Test>().~Test()))
         {
-            mocks.VerifyAll();
+
         }
-        catch (...)
+
+        virtual void TearDown()
         {
-            mocks.reset();
-            throw;
+            try
+            {
+                mocks.VerifyAll();
+            }
+            catch (...)
+            {
+                mocks.reset();
+                throw;
+            }
         }
-    }
 };
 
 class NotificationServiceConsumerTest : public TestWithMock
 {
-public:
-    NotificationServiceConsumerTest() = default;
-    ~NotificationServiceConsumerTest() = default;
-
-    static void ProviderDiscoveredCallbackEmpty( OIC::Service::NSProvider *)
-    {
-        std::cout << __func__ << std::endl;
-    }
+    public:
+        NotificationServiceConsumerTest() = default;
+        ~NotificationServiceConsumerTest() = default;
 
-    static void NotificationReceivedCallbackEmpty( OIC::Service::NSMessage *)
-    {
-        std::cout << __func__ << std::endl;
-    }
+        static void ProviderDiscoveredCallbackEmpty( OIC::Service::NSProvider *)
+        {
+            std::cout << __func__ << std::endl;
+        }
 
-    static void SyncCallbackEmpty(OIC::Service::NSSyncInfo *)
-    {
-        std::cout << __func__ << std::endl;
-    }
+        static void NotificationReceivedCallbackEmpty( OIC::Service::NSMessage *)
+        {
+            std::cout << __func__ << std::endl;
+        }
 
-    static void FoundResourceEmpty(std::shared_ptr< OC::OCResource >)
-    {
-        std::cout << __func__ << std::endl;
-    }
+        static void SyncCallbackEmpty(OIC::Service::NSSyncInfo *)
+        {
+            std::cout << __func__ << std::endl;
+        }
 
-    static void ProviderChangedCallbackEmpty( OIC::Service::NSProvider * , OIC::Service::NSResponse )
-    {
-        std::cout << __func__ << std::endl;
-    }
+        static void FoundResourceEmpty(std::shared_ptr< OC::OCResource >)
+        {
+            std::cout << __func__ << std::endl;
+        }
 
-protected:
+        static void ProviderChangedCallbackEmpty( OIC::Service::NSProviderState )
+        {
+            std::cout << __func__ << std::endl;
+        }
 
-    void SetUp()
-    {
-        TestWithMock::SetUp();
+    protected:
 
-        if (g_isStartedStack == false)
+        void SetUp()
         {
-            OC::PlatformConfig cfg
-            {
-                OC::ServiceType::InProc,
-                OC::ModeType::Both,
-                "0.0.0.0",
-                0,
-                OC::QualityOfService::LowQos
-            };
-            OC::OCPlatform::Configure(cfg);
+            TestWithMock::SetUp();
 
-            try
+            if (g_isStartedStack == false)
             {
-                OC::OCPlatform::stopPresence();
-            }
-            catch (...)
-            {
-
+                OC::PlatformConfig cfg
+                {
+                    OC::ServiceType::InProc,
+                    OC::ModeType::Both,
+                    "0.0.0.0",
+                    0,
+                    OC::QualityOfService::LowQos
+                };
+                OC::OCPlatform::Configure(cfg);
+
+                try
+                {
+                    OC::OCPlatform::stopPresence();
+                }
+                catch (...)
+                {
+
+                }
+
+                g_isStartedStack = true;
             }
 
-            g_isStartedStack = true;
         }
 
-    }
-
-    void TearDown()
-    {
-        TestWithMock::TearDown();
-    }
+        void TearDown()
+        {
+            TestWithMock::TearDown();
+        }
 
 };
 
 TEST_F(NotificationServiceConsumerTest, StartConsumerPositive)
 {
-    OIC::Service::NSConsumerService::ConsumerConfig cfg;
-    cfg.m_discoverCb = ProviderDiscoveredCallbackEmpty;
-    cfg.m_changedCb = ProviderChangedCallbackEmpty;
-    OIC::Service::NSConsumerService::getInstance()->Start(cfg);
+    OIC::Service::NSConsumerService::getInstance()->start(ProviderDiscoveredCallbackEmpty);
 }
 
 TEST_F(NotificationServiceConsumerTest, StopConsumerPositive)
 {
-    OIC::Service::NSConsumerService::getInstance()->Stop();
+    OIC::Service::NSConsumerService::getInstance()->stop();
 }
 
 TEST_F(NotificationServiceConsumerTest, DiscoverProviderWithNonAccepterWhenStartedConsumerFirst)
 {
     mocks.ExpectCallFunc(ProviderDiscoveredCallbackEmpty).Do(
-            [this]( OIC::Service::NSProvider * provider)
-            {
-                std::cout << "Call Discovered" << std::endl;
-                g_provider = provider;
-                g_provider->subscribe();
-                g_provider->setListener((OIC::Service::NSProvider::MessageReceivedCallback)NotificationReceivedCallbackEmpty,
-                                                   (OIC::Service::NSProvider::SyncInfoReceivedCallback)SyncCallbackEmpty);
-                responseCon.notify_all();
-            });
-
-    OIC::Service::NSConsumerService::ConsumerConfig cfg;
-    cfg.m_discoverCb = ProviderDiscoveredCallbackEmpty;
-    cfg.m_changedCb = ProviderChangedCallbackEmpty;
-    OIC::Service::NSConsumerService::getInstance()->Start(cfg);
+        [this]( OIC::Service::NSProvider * provider)
+    {
+        std::cout << "Call Discovered" << std::endl;
+        std::cout << provider->getProviderId() << std::endl;
+        responseCon.notify_all();
+    });
+
+    OIC::Service::NSConsumerService::getInstance()->start(ProviderDiscoveredCallbackEmpty);
 
     g_providerSimul.setAccepter((int)NSSelector::NS_SELECTION_CONSUMER);
     g_providerSimul.createNotificationResource();
 
-    std::unique_lock< std::mutex > lock{ mutexForCondition };
+    std::unique_lock< std::mutex > lock { mutexForCondition };
     responseCon.wait_for(lock, g_waitForResponse);
 
-     OIC::Service::NSConsumerService::getInstance()->Stop();
+    OIC::Service::NSConsumerService::getInstance()->stop();
     g_providerSimul.deleteNotificationResource();
 }
 
@@ -197,26 +188,22 @@ TEST_F(NotificationServiceConsumerTest, DiscoverProviderWithNonAccepterWhenStart
     g_providerSimul.setAccepter((int)NSSelector::NS_SELECTION_CONSUMER);
     g_providerSimul.createNotificationResource();
     {
-        std::unique_lock< std::mutex > lock{ mutexForCondition };
+        std::unique_lock< std::mutex > lock { mutexForCondition };
         responseCon.wait_for(lock, g_waitForResponse);
     }
 
     mocks.ExpectCallFunc(ProviderDiscoveredCallbackEmpty).Do(
-            [this]( OIC::Service::NSProvider * provider)
-            {
-                std::cout << "Call Discovered" << std::endl;
-                 g_provider->subscribe();
-                g_provider->setListener((OIC::Service::NSProvider::MessageReceivedCallback)NotificationReceivedCallbackEmpty,
-                                                   (OIC::Service::NSProvider::SyncInfoReceivedCallback)SyncCallbackEmpty);
-                responseCon.notify_all();
-            });
-
-    OIC::Service::NSConsumerService::ConsumerConfig cfg;
-    cfg.m_discoverCb = ProviderDiscoveredCallbackEmpty;
-    cfg.m_changedCb = ProviderChangedCallbackEmpty;
-    OIC::Service::NSConsumerService::getInstance()->Start(cfg);
-
-    std::unique_lock< std::mutex > lock{ mutexForCondition };
+        [this]( OIC::Service::NSProvider * provider)
+    {
+        std::cout << "Call Discovered" << std::endl;
+        g_provider = provider;
+        std::cout << g_provider->getProviderId() << std::endl;
+        responseCon.notify_all();
+    });
+
+    OIC::Service::NSConsumerService::getInstance()->start(ProviderDiscoveredCallbackEmpty);
+
+    std::unique_lock< std::mutex > lock { mutexForCondition };
     responseCon.wait_for(lock, g_waitForResponse);
 
 }
@@ -224,37 +211,41 @@ TEST_F(NotificationServiceConsumerTest, DiscoverProviderWithNonAccepterWhenStart
 TEST_F(NotificationServiceConsumerTest, DiscoverProviderWithNonAccepterWhenRescan)
 {
     g_providerSimul.setAccepter((int)NSSelector::NS_SELECTION_CONSUMER);
-    mocks.ExpectCallFunc(ProviderDiscoveredCallbackEmpty).Do(
-            [this]( OIC::Service::NSProvider * provider)
-            {
-                std::cout << "Call Discovered" << std::endl;
-                g_provider = provider;
-                 g_provider->subscribe();
-                g_provider->setListener((OIC::Service::NSProvider::MessageReceivedCallback)NotificationReceivedCallbackEmpty,
-                                                   (OIC::Service::NSProvider::SyncInfoReceivedCallback)SyncCallbackEmpty);
-                std::cout << g_provider->getProviderId() << std::endl;
-                responseCon.notify_all();
-            });
-
-     OIC::Service::NSConsumerService::getInstance()->RescanProvider();
-
-    std::unique_lock< std::mutex > lock{ mutexForCondition };
-    responseCon.wait_for(lock, g_waitForResponse);
+    mocks.OnCallFunc(ProviderDiscoveredCallbackEmpty).Do(
+        [this]( OIC::Service::NSProvider * provider)
+    {
+        std::cout << "Call Discovered" << std::endl;
+        g_provider = provider;
+        std::cout << g_provider->getProviderId() << std::endl;
+        responseCon.notify_all();
+    });
+
+    OIC::Service::NSConsumerService::getInstance()->rescanProvider();
 
-//     OIC::Service::NSConsumerService::getInstance()->Stop();
+    std::unique_lock< std::mutex > lock { mutexForCondition };
+    responseCon.wait_for(lock, g_waitForResponse);
 }
 
 TEST_F(NotificationServiceConsumerTest, ExpectSubscribeSuccess)
 {
-//    mocks.ExpectCallFunc(ProviderChangedCallbackEmpty).Do(
-//            []( OIC::Service::NSProvider * , OIC::Service::NSResponse)
-//            {
-//                std::cout << "Income Accepted subscription : " << std::endl;
-//            });
-
-    g_provider->subscribe();
-    std::unique_lock< std::mutex > lock{ mutexForCondition };
+    OIC::Service::NSProviderState revState = OIC::Service::NSProviderState::DENY;
+    mocks.OnCallFunc(ProviderChangedCallbackEmpty).Do(
+        [this, & revState](OIC::Service::NSProviderState state)
+    {
+        std::cout << "Income Accepted subscription : " << std::endl;
+        revState = state;
+        responseCon.notify_all();
+    });
+
+    g_provider->setListener( (OIC::Service::NSProvider::ProviderStateCallback)
+                             ProviderChangedCallbackEmpty,
+                             (OIC::Service::NSProvider::MessageReceivedCallback)NotificationReceivedCallbackEmpty,
+                             (OIC::Service::NSProvider::SyncInfoReceivedCallback)SyncCallbackEmpty);
+    if (!g_provider->isSubscribed())
+        g_provider->subscribe();
+    std::unique_lock< std::mutex > lock { mutexForCondition };
     responseCon.wait_for(lock, g_waitForResponse);
+    EXPECT_EQ(OIC::Service::NSProviderState::ALLOW, revState);
 }
 
 TEST_F(NotificationServiceConsumerTest, ExpectReceiveNotification)
@@ -264,17 +255,43 @@ TEST_F(NotificationServiceConsumerTest, ExpectReceiveNotification)
     std::string msg = "msg";
 
     mocks.ExpectCallFunc(NotificationReceivedCallbackEmpty).Do(
-            []( OIC::Service::NSMessage * message)
-            {
-                std::cout << "Income Notification : " << message->getMessageId() << std::endl;
-            });
+        [this]( OIC::Service::NSMessage * message)
+    {
+        std::cout << "Income Notification : " << message->getMessageId() << std::endl;
+        responseCon.notify_all();
+    });
 
     g_providerSimul.notifyMessage(id, title, msg);
 
-    std::unique_lock< std::mutex > lock{ mutexForCondition };
+    std::unique_lock< std::mutex > lock { mutexForCondition };
     responseCon.wait_for(lock, g_waitForResponse);
 
-     OIC::Service::NSConsumerService::getInstance()->Stop();
+    OIC::Service::NSConsumerService::getInstance()->stop();
+}
+
+TEST_F(NotificationServiceConsumerTest, DiscoverProviderWithAccepterisProvider)
+{
+    g_providerSimul.setAccepter((int)NSSelector::NS_SELECTION_PROVIDER);
+
+    mocks.ExpectCallFunc(ProviderDiscoveredCallbackEmpty).Do(
+        [this]( OIC::Service::NSProvider * provider)
+    {
+        std::cout << "Call Discovered" << std::endl;
+        g_provider = provider;
+        g_provider->setListener( (OIC::Service::NSProvider::ProviderStateCallback)
+                                 ProviderChangedCallbackEmpty,
+                                 (OIC::Service::NSProvider::MessageReceivedCallback)NotificationReceivedCallbackEmpty,
+                                 (OIC::Service::NSProvider::SyncInfoReceivedCallback)SyncCallbackEmpty);
+        if (!g_provider->isSubscribed())
+            g_provider->subscribe();
+        std::cout << g_provider->getProviderId() << std::endl;
+        responseCon.notify_all();
+    });
+
+
+    OIC::Service::NSConsumerService::getInstance()->start(ProviderDiscoveredCallbackEmpty);
+    std::unique_lock< std::mutex > lock { mutexForCondition };
+    responseCon.wait_for(lock, g_waitForResponse);
 }
 
 TEST_F(NotificationServiceConsumerTest, ExpectReceiveNotificationWithAccepterisProvider)
@@ -282,31 +299,22 @@ TEST_F(NotificationServiceConsumerTest, ExpectReceiveNotificationWithAccepterisP
     uint64_t id = 11;
     std::string title = "title";
     std::string msg = "msg";
+    uint64_t revId = 1;
 
-    g_providerSimul.setAccepter((int)NSSelector::NS_SELECTION_PROVIDER);
-
-    OIC::Service::NSConsumerService::ConsumerConfig cfg;
-    cfg.m_discoverCb = ProviderDiscoveredCallbackEmpty;
-    cfg.m_changedCb = ProviderChangedCallbackEmpty;
-    OIC::Service::NSConsumerService::getInstance()->Start(cfg);
+    mocks.OnCallFunc(NotificationReceivedCallbackEmpty).Do(
+        [this, & id, & revId](OIC::Service::NSMessage * message)
     {
-        std::unique_lock< std::mutex > lock{ mutexForCondition };
-        responseCon.wait_for(lock, g_waitForResponse);
-    }
-
-    mocks.ExpectCallFunc(NotificationReceivedCallbackEmpty).Do(
-            []( OIC::Service::NSMessage * message)
-            {
-                std::cout << "Income Notification : " << message->getMessageId() << std::endl;
-            });
+        std::cout << "Income Notification : " << message->getMessageId() << std::endl;
+        revId =  message->getMessageId();
+        responseCon.notify_all();
+    });
 
     g_providerSimul.notifyMessage(id, title, msg);
 
-    std::unique_lock< std::mutex > lock{ mutexForCondition };
+    std::unique_lock< std::mutex > lock { mutexForCondition };
     responseCon.wait_for(lock, g_waitForResponse);
 
-//    g_providerSimul.deleteNotificationResource();
-//     OIC::Service::NSConsumerService::getInstance()->Stop();
+    EXPECT_EQ(id, revId);
 }
 
 TEST_F(NotificationServiceConsumerTest, ExpectCallbackReadCheckWhenProviderNotifySync)
@@ -314,39 +322,35 @@ TEST_F(NotificationServiceConsumerTest, ExpectCallbackReadCheckWhenProviderNotif
     uint64_t id = 12;
     std::string title = "title";
     std::string msg = "msg";
-
     OIC::Service::NSSyncInfo::NSSyncType type = OIC::Service::NSSyncInfo::NSSyncType::NS_SYNC_DELETED;
 
     mocks.OnCallFunc(NotificationReceivedCallbackEmpty).Do(
-            []( OIC::Service::NSMessage * message)
-            {
-                std::cout << "Income Notification : " << message->getMessageId() << std::endl;
-            });
-
-    mocks.ExpectCallFunc(SyncCallbackEmpty).Do(
-            [& type](OIC::Service::NSSyncInfo * sync)
-            {
-                std::cout << "Income SyncInfo : " << sync->getMessageId()
-                        << ", State : " << (int) sync->getState() << std::endl;
-                type = sync->getState();
+        [this]( OIC::Service::NSMessage * message)
+    {
+        std::cout << "Income Notification : " << message->getMessageId() << std::endl;
+    });
 
-            });
+    mocks.OnCallFunc(SyncCallbackEmpty).Do(
+        [& type, this](OIC::Service::NSSyncInfo * sync)
+    {
+        std::cout << "Income SyncInfo : " << sync->getMessageId()
+                  << ", State : " << (int) sync->getState() << std::endl;
+        type = sync->getState();
+        responseCon.notify_all();
+    });
 
     g_providerSimul.notifyMessage(id, title, msg);
     {
-        std::unique_lock< std::mutex > lock{ mutexForCondition };
+        std::unique_lock< std::mutex > lock { mutexForCondition };
         responseCon.wait_for(lock, g_waitForResponse);
     }
 
     g_providerSimul.sendRead(id);
     {
-        std::unique_lock< std::mutex > lock{ mutexForCondition };
+        std::unique_lock< std::mutex > lock { mutexForCondition };
         responseCon.wait_for(lock, g_waitForResponse);
     }
 
-//    g_providerSimul.deleteNotificationResource();
-//     OIC::Service::NSConsumerService::getInstance()->Stop();
-
     EXPECT_EQ(OIC::Service::NSSyncInfo::NSSyncType::NS_SYNC_READ, type);
 }
 
@@ -355,39 +359,35 @@ TEST_F(NotificationServiceConsumerTest, ExpectCallbackDismissCheckWhenProviderNo
     uint64_t id = 13;
     std::string title = "title";
     std::string msg = "msg";
-
     OIC::Service::NSSyncInfo::NSSyncType type = OIC::Service::NSSyncInfo::NSSyncType::NS_SYNC_READ;
 
     mocks.OnCallFunc(NotificationReceivedCallbackEmpty).Do(
-            []( OIC::Service::NSMessage * message)
-            {
-                std::cout << "Income Notification : " << message->getMessageId() << std::endl;
-            });
-
-    mocks.ExpectCallFunc(SyncCallbackEmpty).Do(
-            [& type](OIC::Service::NSSyncInfo * sync)
-            {
-                std::cout << "Income Notification : " << sync->getMessageId()
-                        << ", State : " << (int) sync->getState() << std::endl;
-                type = sync->getState();
+        [this]( OIC::Service::NSMessage * message)
+    {
+        std::cout << "Income Notification : " << message->getMessageId() << std::endl;
+    });
 
-            });
+    mocks.OnCallFunc(SyncCallbackEmpty).Do(
+        [& type, this](OIC::Service::NSSyncInfo * sync)
+    {
+        std::cout << "Income Notification : " << sync->getMessageId()
+                  << ", State : " << (int) sync->getState() << std::endl;
+        type = sync->getState();
+        responseCon.notify_all();
+    });
 
     g_providerSimul.notifyMessage(id, title, msg);
     {
-        std::unique_lock< std::mutex > lock{ mutexForCondition };
+        std::unique_lock< std::mutex > lock { mutexForCondition };
         responseCon.wait_for(lock, g_waitForResponse);
     }
 
     g_providerSimul.sendDismiss(id);
     {
-        std::unique_lock< std::mutex > lock{ mutexForCondition };
+        std::unique_lock< std::mutex > lock { mutexForCondition };
         responseCon.wait_for(lock, g_waitForResponse);
     }
 
-//    g_providerSimul.deleteNotificationResource();
-//     OIC::Service::NSConsumerService::getInstance()->Stop();
-
     EXPECT_EQ(OIC::Service::NSSyncInfo::NSSyncType::NS_SYNC_DELETED, type);
 }
 
@@ -396,36 +396,33 @@ TEST_F(NotificationServiceConsumerTest, ExpectCallbackReadCheckWhenConsumerPostS
     uint64_t id = 14;
     std::string title = "title";
     std::string msg = "msg";
-
     OIC::Service::NSSyncInfo::NSSyncType type = OIC::Service::NSSyncInfo::NSSyncType::NS_SYNC_DELETED;
 
     mocks.OnCallFunc(NotificationReceivedCallbackEmpty).Do(
-            []( OIC::Service::NSMessage * message)
-            {
-                std::cout << "Income Notification : " << message->getMessageId() << std::endl;
-                g_provider->SendSyncInfo(message->getMessageId(), OIC::Service::NSSyncInfo::NSSyncType::NS_SYNC_READ);
-                std::unique_lock< std::mutex > lock{ mutexForCondition };
-                responseCon.wait_for(lock, g_waitForResponse);
-            });
-
-    mocks.ExpectCallFunc(SyncCallbackEmpty).Do(
-            [& type](OIC::Service::NSSyncInfo * sync)
-            {
-                std::cout << "Income Notification : " << sync->getMessageId()
-                        << ", State : " << (int) sync->getState() << std::endl;
-                type = sync->getState();
+        [this]( OIC::Service::NSMessage * message)
+    {
+        std::cout << "Income Notification : " << message->getMessageId() << std::endl;
+        g_provider->sendSyncInfo(message->getMessageId(),
+                                 OIC::Service::NSSyncInfo::NSSyncType::NS_SYNC_READ);
+        std::unique_lock< std::mutex > lock { mutexForCondition };
+        responseCon.wait_for(lock, g_waitForResponse);
+    });
 
-            });
+    mocks.OnCallFunc(SyncCallbackEmpty).Do(
+        [& type, this](OIC::Service::NSSyncInfo * sync)
+    {
+        std::cout << "Income Notification : " << sync->getMessageId()
+                  << ", State : " << (int) sync->getState() << std::endl;
+        type = sync->getState();
+        responseCon.notify_all();
+    });
 
     g_providerSimul.notifyMessage(id, title, msg);
     {
-        std::unique_lock< std::mutex > lock{ mutexForCondition };
+        std::unique_lock< std::mutex > lock { mutexForCondition };
         responseCon.wait_for(lock, g_waitForResponse);
     }
 
-//    g_providerSimul.deleteNotificationResource();
-//     OIC::Service::NSConsumerService::getInstance()->Stop();
-
     EXPECT_EQ(OIC::Service::NSSyncInfo::NSSyncType::NS_SYNC_READ, type);
 }
 
@@ -434,43 +431,64 @@ TEST_F(NotificationServiceConsumerTest, ExpectCallbackDismissCheckWhenConsumerPo
     uint64_t id = 15;
     std::string title = "title";
     std::string msg = "msg";
-
     OIC::Service::NSSyncInfo::NSSyncType type = OIC::Service::NSSyncInfo::NSSyncType::NS_SYNC_READ;
 
     mocks.OnCallFunc(NotificationReceivedCallbackEmpty).Do(
-            []( OIC::Service::NSMessage * message)
-            {
-                std::cout << "Income Notification : " << message->getMessageId() << std::endl;
-                g_provider->SendSyncInfo(message->getMessageId(), OIC::Service::NSSyncInfo::NSSyncType::NS_SYNC_DELETED);
-                std::unique_lock< std::mutex > lock{ mutexForCondition };
-                responseCon.wait_for(lock, g_waitForResponse);
-            });
-
-    mocks.ExpectCallFunc(SyncCallbackEmpty).Do(
-            [& type](OIC::Service::NSSyncInfo * sync)
-            {
-                std::cout << "Income Notification : " << sync->getMessageId()
-                        << ", State : " << (int) sync->getState() << std::endl;
-                type = sync->getState();
+        [this]( OIC::Service::NSMessage * message)
+    {
+        std::cout << "Income Notification : " << message->getMessageId() << std::endl;
+        g_provider->sendSyncInfo(message->getMessageId(),
+                                 OIC::Service::NSSyncInfo::NSSyncType::NS_SYNC_DELETED);
+        std::unique_lock< std::mutex > lock { mutexForCondition };
+        responseCon.wait_for(lock, g_waitForResponse);
+    });
 
-            });
+    mocks.OnCallFunc(SyncCallbackEmpty).Do(
+        [& type, this](OIC::Service::NSSyncInfo * sync)
+    {
+        std::cout << "Income Notification : " << sync->getMessageId()
+                  << ", State : " << (int) sync->getState() << std::endl;
+        type = sync->getState();
+        responseCon.notify_all();
+    });
 
     g_providerSimul.notifyMessage(id, title, msg);
     {
-        std::unique_lock< std::mutex > lock{ mutexForCondition };
+        std::unique_lock< std::mutex > lock { mutexForCondition };
         responseCon.wait_for(lock, g_waitForResponse);
     }
 
     EXPECT_EQ(OIC::Service::NSSyncInfo::NSSyncType::NS_SYNC_DELETED, type);
 }
 
-TEST_F(NotificationServiceConsumerTest, ExpectUnsubscribeSuccess)
+TEST_F(NotificationServiceConsumerTest, ExpectCallbackDeletedProvider)
 {
-    g_provider->unSubscribe();
-    std::unique_lock< std::mutex > lock{ mutexForCondition };
-    responseCon.wait_for(lock, g_waitForResponse);
+    OIC::Service::NSProviderState type = OIC::Service::NSProviderState::ALLOW;
+    mocks.OnCallFunc(ProviderChangedCallbackEmpty).Do(
+        [& type, this](OIC::Service::NSProviderState state)
+    {
+        std::cout << "Income Changed Callback : " << std::endl;
+        type = state;
+        responseCon.notify_all();
+    });
 
     g_providerSimul.deleteNotificationResource();
-     OIC::Service::NSConsumerService::getInstance()->Stop();
 
+    std::unique_lock< std::mutex > lock { mutexForCondition };
+    responseCon.wait_for(lock, g_waitForResponse);
+
+    EXPECT_EQ(type, OIC::Service::NSProviderState::STOPPED);
+    OIC::Service::NSConsumerService::getInstance()->stop();
 }
+
+//TO add when unsubscibe API is added back
+//TEST_F(NotificationServiceConsumerTest, ExpectUnsubscribeSuccess)
+//{
+//    g_provider->unsubscribe();
+//   std::unique_lock< std::mutex > lock{ mutexForCondition };
+//    responseCon.wait_for(lock, g_waitForResponse);
+//
+//    g_providerSimul.deleteNotificationResource();
+//     OIC::Service::NSConsumerService::getInstance()->stop();
+//
+//}
index 1371e89..ebed3fa 100644 (file)
@@ -98,7 +98,7 @@ private:
                     std::string msgUri = m_notificationUri + m_messageUri;
                     std::string syncUri = m_notificationUri + m_syncUri;
                     std::string providerId = "123456789012345678901234567890123456";
-                    rep.setValue("ACCEPTER", m_accepter);
+                    rep.setValue("ACCEPTER", (bool) m_accepter);
                     rep.setValue("MESSAGE_URI", msgUri);
                     rep.setValue("SYNC_URI", syncUri);
                     rep.setValue("PROVIDER_ID", providerId);
index 5e9fd0e..b5e76af 100644 (file)
@@ -37,99 +37,100 @@ namespace
 {
     std::atomic_bool g_isStartedStack(false);
 
-    std::chrono::milliseconds g_waitForResponse(3000);
+    std::chrono::milliseconds g_waitForResponse(500);
 
     std::condition_variable responseCon;
     std::mutex mutexForCondition;
 
     NSConsumerSimulator g_consumerSimul;
-     OIC::Service::NSConsumer * g_consumer;
+    OIC::Service::NSConsumer *g_consumer;
 }
 
 class TestWithMock: public testing::Test
 {
-public:
-    MockRepository mocks;
+    public:
+        MockRepository mocks;
 
-protected:
-    virtual ~TestWithMock() noexcept(noexcept(std::declval<Test>().~Test())) {}
+    protected:
+        virtual ~TestWithMock() noexcept(noexcept(std::declval<Test>().~Test())) {}
 
-    virtual void TearDown() {
-        try
+        virtual void TearDown()
         {
-            mocks.VerifyAll();
-        }
-        catch (...)
-        {
-            mocks.reset();
-            throw;
+            try
+            {
+                mocks.VerifyAll();
+            }
+            catch (...)
+            {
+                mocks.reset();
+                throw;
+            }
         }
-    }
 };
 
 class NotificationProviderServiceTest : public TestWithMock
 {
-public:
-    NotificationProviderServiceTest() = default;
-    ~NotificationProviderServiceTest() = default;
+    public:
+        NotificationProviderServiceTest() = default;
+        ~NotificationProviderServiceTest() = default;
 
-    static void ConsumerSubscribedCallbackEmpty(OIC::Service::NSConsumer *)
-    {
-        std::cout << __func__ << std::endl;
-    }
+        static void ConsumerSubscribedCallbackEmpty(OIC::Service::NSConsumer *)
+        {
+            std::cout << __func__ << std::endl;
+        }
 
-    static void MessageSynchronizedCallbackEmpty(OIC::Service::NSSyncInfo *)
-    {
-        std::cout << __func__ << std::endl;
-    }
+        static void MessageSynchronizedCallbackEmpty(OIC::Service::NSSyncInfo *)
+        {
+            std::cout << __func__ << std::endl;
+        }
 
-    static void MessageCallbackFromConsumerEmpty(
+        static void MessageCallbackFromConsumerEmpty(
             const int &, const std::string &, const std::string &, const std::string &)
-    {
-        std::cout << __func__ << std::endl;
-    }
-
-    static void SyncCallbackFromConsumerEmpty(int, int)
-    {
-        std::cout << __func__ << std::endl;
-    }
+        {
+            std::cout << __func__ << std::endl;
+        }
 
-protected:
+        static void SyncCallbackFromConsumerEmpty(int, int)
+        {
+            std::cout << __func__ << std::endl;
+        }
 
-    void SetUp()
-    {
-        TestWithMock::SetUp();
+    protected:
 
-        if (g_isStartedStack == false)
+        void SetUp()
         {
-            OC::PlatformConfig cfg
-            {
-                OC::ServiceType::InProc,
-                OC::ModeType::Both,
-                "0.0.0.0",
-                0,
-                OC::QualityOfService::HighQos
-            };
-            OC::OCPlatform::Configure(cfg);
+            TestWithMock::SetUp();
 
-            try
-            {
-                OC::OCPlatform::stopPresence();
-            }
-            catch (...)
+            if (g_isStartedStack == false)
             {
+                OC::PlatformConfig cfg
+                {
+                    OC::ServiceType::InProc,
+                    OC::ModeType::Both,
+                    "0.0.0.0",
+                    0,
+                    OC::QualityOfService::HighQos
+                };
+                OC::OCPlatform::Configure(cfg);
+
+                try
+                {
+                    OC::OCPlatform::stopPresence();
+                }
+                catch (...)
+                {
+
+                }
 
+                g_isStartedStack = true;
             }
 
-            g_isStartedStack = true;
         }
 
-    }
-
-    void TearDown()
-    {
-        TestWithMock::TearDown();
-    }
+        void TearDown()
+        {
+            TestWithMock::TearDown();
+        }
 
 };
 
@@ -138,22 +139,16 @@ TEST_F(NotificationProviderServiceTest, StartProviderPositiveWithPolicyTrue)
     OIC::Service::NSProviderService::ProviderConfig config;
     config.m_subscribeRequestCb = ConsumerSubscribedCallbackEmpty;
     config.m_syncInfoCb = MessageSynchronizedCallbackEmpty;
-    config.policy = true;
-
-    OIC::Service::NSResult ret =  OIC::Service::NSProviderService::getInstance()->Start(config);
+    config.subControllability = true;
 
-    std::unique_lock< std::mutex > lock{ mutexForCondition };
-    responseCon.wait_for(lock, g_waitForResponse);
+    OIC::Service::NSResult ret =  OIC::Service::NSProviderService::getInstance()->start(config);
 
     EXPECT_EQ(ret,  OIC::Service::NSResult::OK);
 }
 
 TEST_F(NotificationProviderServiceTest, StopProviderPositive)
 {
-     OIC::Service::NSResult ret =  OIC::Service::NSProviderService::getInstance()->Stop();
-
-    std::unique_lock< std::mutex > lock{ mutexForCondition };
-    responseCon.wait_for(lock, g_waitForResponse);
+    OIC::Service::NSResult ret =  OIC::Service::NSProviderService::getInstance()->stop();
 
     EXPECT_EQ(ret,  OIC::Service::NSResult::OK);
 }
@@ -163,47 +158,46 @@ TEST_F(NotificationProviderServiceTest, StartProviderPositiveWithPolicyFalse)
     OIC::Service::NSProviderService::ProviderConfig  config;
     config.m_subscribeRequestCb = ConsumerSubscribedCallbackEmpty;
     config.m_syncInfoCb = MessageSynchronizedCallbackEmpty;
-    config.policy = false;
+    config.subControllability = false;
 
-     OIC::Service::NSResult ret =  OIC::Service::NSProviderService::getInstance()->Start(config);
+    OIC::Service::NSResult ret =  OIC::Service::NSProviderService::getInstance()->start(config);
 
-    std::unique_lock< std::mutex > lock{ mutexForCondition };
-    responseCon.wait_for(lock, std::chrono::milliseconds(3000));
-    g_consumerSimul.findProvider();
-
-    responseCon.wait_for(lock, std::chrono::milliseconds(3000));
-     OIC::Service::NSProviderService::getInstance()->Stop();
     EXPECT_EQ(ret,  OIC::Service::NSResult::OK);
+    OIC::Service::NSProviderService::getInstance()->stop();
 }
 
-TEST_F(NotificationProviderServiceTest, ExpectCallbackWhenReceiveSubscribeRequestWithAccepterProvider)
+TEST_F(NotificationProviderServiceTest,
+       ExpectCallbackWhenReceiveSubscribeRequestWithAccepterProvider)
 {
+    g_consumer = NULL;
     mocks.ExpectCallFunc(ConsumerSubscribedCallbackEmpty).Do(
-            []( OIC::Service::NSConsumer * consumer)
-            {
-                std::cout << "ConsumerSubscribedCallbackEmpty" << std::endl;
-                g_consumer = new  OIC::Service::NSConsumer(consumer->getConsumerId());
-                responseCon.notify_all();
-            });
+        []( OIC::Service::NSConsumer * consumer)
+    {
+        std::cout << "ConsumerSubscribedCallbackEmpty" << std::endl;
+        g_consumer = consumer;
+        responseCon.notify_all();
+    });
 
     OIC::Service::NSProviderService::ProviderConfig  config;
     config.m_subscribeRequestCb = ConsumerSubscribedCallbackEmpty;
     config.m_syncInfoCb = MessageSynchronizedCallbackEmpty;
-    config.policy = true;
+    config.subControllability = true;
 
-     OIC::Service::NSProviderService::getInstance()->Start(config);
+    OIC::Service::NSProviderService::getInstance()->start(config);
 
     {
-        std::unique_lock< std::mutex > lock{ mutexForCondition };
+        std::unique_lock< std::mutex > lock { mutexForCondition };
         responseCon.wait_for(lock, g_waitForResponse);
     }
 
     g_consumerSimul.setCallback(MessageCallbackFromConsumerEmpty,
-            SyncCallbackFromConsumerEmpty);
+                                SyncCallbackFromConsumerEmpty);
     g_consumerSimul.findProvider();
 
-    std::unique_lock< std::mutex > lock{ mutexForCondition };
-    responseCon.wait_for(lock, std::chrono::milliseconds(1000));
+    std::unique_lock< std::mutex > lock { mutexForCondition };
+    responseCon.wait_for(lock, g_waitForResponse);
+
+    EXPECT_NE((void*)g_consumer, (void*)NULL);
 }
 
 TEST_F(NotificationProviderServiceTest, NeverCallNotifyOnConsumerByAcceptIsFalse)
@@ -212,31 +206,33 @@ TEST_F(NotificationProviderServiceTest, NeverCallNotifyOnConsumerByAcceptIsFalse
     int msgID;
 
     mocks.OnCallFunc(MessageCallbackFromConsumerEmpty).Do(
-            [& expectTrue, &msgID](const int &id, const std::string&, const std::string&, const std::string&)
-            {
-                if (id == msgID)
-                {
-                    std::cout << "This function never call" << std::endl;
-                    expectTrue = false;
-                }
-            });
+        [& expectTrue, &msgID](const int & id, const std::string &, const std::string &,
+                               const std::string &)
+    {
+        if (id == msgID)
+        {
+            std::cout << "This function never call" << std::endl;
+            expectTrue = false;
+        }
+        responseCon.notify_all();
+    });
 
-    g_consumer->acceptSubscription(g_consumer, false);
+    g_consumer->acceptSubscription(false);
 
-     OIC::Service::NSMessage * msg =  OIC::Service::NSProviderService::getInstance()->CreateMessage();
+    OIC::Service::NSMessage *msg =  OIC::Service::NSProviderService::getInstance()->createMessage();
     msgID = (int)msg->getMessageId();
     msg->setTitle(std::string("Title"));
     msg->setContentText(std::string("ContentText"));
     msg->setSourceName(std::string("OCF"));
 
-     OIC::Service::NSProviderService::getInstance()->SendMessage(msg);
+    OIC::Service::NSProviderService::getInstance()->sendMessage(msg);
     {
-        std::unique_lock< std::mutex > lock{ mutexForCondition };
+        std::unique_lock< std::mutex > lock { mutexForCondition };
         responseCon.wait_for(lock, g_waitForResponse);
     }
 
-    std::unique_lock< std::mutex > lock{ mutexForCondition };
-    responseCon.wait_for(lock, std::chrono::milliseconds(1000));
+    std::unique_lock< std::mutex > lock { mutexForCondition };
+    responseCon.wait_for(lock, g_waitForResponse);
 
     EXPECT_EQ(expectTrue, true);
 }
@@ -246,30 +242,27 @@ TEST_F(NotificationProviderServiceTest, ExpectCallNotifyOnConsumerByAcceptIsTrue
     int msgID;
 
     mocks.ExpectCallFunc(MessageCallbackFromConsumerEmpty).Do(
-            [&msgID](const int &id, const std::string&, const std::string&, const std::string&)
-            {
-                if (id == msgID)
-                {
-                    std::cout << "ExpectCallNotifyOnConsumerByAcceptIsTrue" << std::endl;
-                    responseCon.notify_all();
-                }
-            });
+        [&msgID](const int & id, const std::string &, const std::string &, const std::string &)
+    {
+        if (id == msgID)
+        {
+            std::cout << "ExpectCallNotifyOnConsumerByAcceptIsTrue" << std::endl;
+            responseCon.notify_all();
+        }
+    });
 
-    g_consumer->acceptSubscription(g_consumer, true);
+    g_consumer->acceptSubscription(true);
 
-     OIC::Service::NSMessage * msg =  OIC::Service::NSProviderService::getInstance()->CreateMessage();
+    OIC::Service::NSMessage *msg =  OIC::Service::NSProviderService::getInstance()->createMessage();
     msgID = (int)msg->getMessageId();
     msg->setTitle(std::string("Title"));
     msg->setContentText(std::string("ContentText"));
     msg->setSourceName(std::string("OCF"));
-
-      OIC::Service::NSProviderService::getInstance()->SendMessage(msg);
-    {
-        std::unique_lock< std::mutex > lock{ mutexForCondition };
-        responseCon.wait_for(lock, g_waitForResponse);
-    }
-
-    std::unique_lock< std::mutex > lock{ mutexForCondition };
+    OIC::Service::NSProviderService::getInstance()->registerTopic("OCF_TOPIC1");
+    g_consumer->setTopic("OCF_TOPIC1");
+    OIC::Service::NSProviderService::getInstance()->sendMessage(msg);
+    OIC::Service::NSProviderService::getInstance()->unregisterTopic("OCF_TOPIC1");
+    std::unique_lock< std::mutex > lock { mutexForCondition };
     responseCon.wait_for(lock, g_waitForResponse);
 }
 
@@ -278,26 +271,27 @@ TEST_F(NotificationProviderServiceTest, ExpectCallbackSyncOnReadToConsumer)
     int id;
 
     mocks.ExpectCallFunc(SyncCallbackFromConsumerEmpty).Do(
-            [& id](int & type, int &syncId)
-            {
+        [& id](int & type, int & syncId)
+    {
         std::cout << "MessageSynchronizedCallbackEmpty" << std::endl;
-                if (syncId == id &&
-                        type == (int)OIC::Service::NSSyncInfo::NSSyncType::NS_SYNC_READ)
-                {
-                    std::cout << "ExpectCallbackSyncOnReadFromConsumer" << std::endl;
-                    responseCon.notify_all();
-                }
-            });
+        if (syncId == id &&
+            type == (int)OIC::Service::NSSyncInfo::NSSyncType::NS_SYNC_READ)
+        {
+            std::cout << "ExpectCallbackSyncOnReadFromConsumer" << std::endl;
+            responseCon.notify_all();
+        }
+    });
 
-    OIC::Service::NSMessage * msg =  OIC::Service::NSProviderService::getInstance()->CreateMessage();
+    OIC::Service::NSMessage *msg =  OIC::Service::NSProviderService::getInstance()->createMessage();
     id = (int)msg->getMessageId();
     msg->setTitle(std::string("Title"));
     msg->setContentText(std::string("ContentText"));
     msg->setSourceName(std::string("OCF"));
 
-     OIC::Service::NSProviderService::getInstance()->SendSyncInfo(msg->getMessageId(), OIC::Service::NSSyncInfo::NSSyncType::NS_SYNC_READ);
-    std::unique_lock< std::mutex > lock{ mutexForCondition };
-    responseCon.wait_for(lock, std::chrono::milliseconds(5000));
+    OIC::Service::NSProviderService::getInstance()->sendSyncInfo(msg->getMessageId(),
+            OIC::Service::NSSyncInfo::NSSyncType::NS_SYNC_READ);
+    std::unique_lock< std::mutex > lock { mutexForCondition };
+    responseCon.wait_for(lock, g_waitForResponse);
 }
 
 TEST_F(NotificationProviderServiceTest, ExpectCallbackSyncOnReadFromConsumer)
@@ -305,33 +299,194 @@ TEST_F(NotificationProviderServiceTest, ExpectCallbackSyncOnReadFromConsumer)
     int type = (int)OIC::Service::NSSyncInfo::NSSyncType::NS_SYNC_READ;
     int id;
     mocks.ExpectCallFunc(MessageSynchronizedCallbackEmpty).Do(
-            [& id](OIC::Service::NSSyncInfo * sync)
-            {
-                std::cout << "MessageSynchronizedCallbackEmpty" << std::endl;
-                if ((int)sync->getMessageId() == id && sync->getState() == OIC::Service::NSSyncInfo::NSSyncType::NS_SYNC_READ)
-                {
-                    std::cout << "ExpectCallbackSyncOnReadFromConsumer" << std::endl;
-                    responseCon.notify_all();
-                }
-            });
+        [& id](OIC::Service::NSSyncInfo * sync)
+    {
+        std::cout << "MessageSynchronizedCallbackEmpty" << std::endl;
+        if ((int)sync->getMessageId() == id
+            && sync->getState() == OIC::Service::NSSyncInfo::NSSyncType::NS_SYNC_READ)
+        {
+            std::cout << "ExpectCallbackSyncOnReadFromConsumer" << std::endl;
+            responseCon.notify_all();
+        }
+    });
 
-     OIC::Service::NSMessage * msg =  OIC::Service::NSProviderService::getInstance()->CreateMessage();
+    OIC::Service::NSMessage *msg =  OIC::Service::NSProviderService::getInstance()->createMessage();
     id = (int)msg->getMessageId();
     msg->setTitle(std::string("Title"));
     msg->setContentText(std::string("ContentText"));
     msg->setSourceName(std::string("OCF"));
-
     g_consumerSimul.syncToProvider(type, id, msg->getProviderId());
-    std::unique_lock< std::mutex > lock{ mutexForCondition };
-    responseCon.wait_for(lock, std::chrono::milliseconds(5000));
+    std::unique_lock< std::mutex > lock { mutexForCondition };
+    responseCon.wait(lock);
+}
+
+TEST_F(NotificationProviderServiceTest, ExpectEqualAddedTopicsAndRegisteredTopics)
+{
+    std::string str1("TEST1");
+    std::string str2("TEST2");
+    OIC::Service::NSProviderService::getInstance()->registerTopic(str1);
+    OIC::Service::NSProviderService::getInstance()->registerTopic(str2);
+    std::unique_lock< std::mutex > lock { mutexForCondition };
+    responseCon.wait_for(lock, g_waitForResponse);
+    bool isSame = false;
+    OIC::Service::NSTopicsList *topicList =
+        OIC::Service::NSProviderService::getInstance()->getRegisteredTopicList();
+    if (!topicList)
+    {
+        printf("topic is NULL\n");
+        isSame = false;
+    }
+    else
+    {
+        std::string compString[10];
+        int i = 0;
+        for (auto itr : topicList->getTopicsList())
+        {
+            compString[i] = itr->getTopicName(); i++;
+        }
+        std::cout << compString[0] << std::endl;
+        std::cout << compString[1] << std::endl;
+        if (str1.compare(compString[0]) == 0 && str2.compare(compString[1]) == 0)
+        {
+            isSame = true;
+        }
+    }
+    EXPECT_EQ(isSame, true);
+
+    OIC::Service::NSProviderService::getInstance()->unregisterTopic(str1);
+    OIC::Service::NSProviderService::getInstance()->unregisterTopic(str2);
+    responseCon.wait_for(lock, g_waitForResponse);
+}
+
+TEST_F(NotificationProviderServiceTest, ExpectEqualUnregisteredTopicsAndRegisteredTopics)
+{
+    std::string str1("TEST1");
+    std::string str2("TEST2");
+    OIC::Service::NSProviderService::getInstance()->registerTopic(str1);
+    OIC::Service::NSProviderService::getInstance()->registerTopic(str2);
+    OIC::Service::NSProviderService::getInstance()->unregisterTopic(str2);
+    std::unique_lock< std::mutex > lock { mutexForCondition };
+    responseCon.wait_for(lock, g_waitForResponse);
+    bool isSame = false;
+    OIC::Service::NSTopicsList *topicList =
+        OIC::Service::NSProviderService::getInstance()->getRegisteredTopicList();
+    if (!topicList)
+    {
+        printf("topic is NULL\n");
+        isSame = false;
+    }
+    else
+    {
+        std::list<OIC::Service::NSTopic *>::iterator it = topicList->getTopicsList().begin();
+        std::string compStr = (*it)->getTopicName() ;
+        std::cout << compStr << std::endl;
+        if (str1.compare(compStr) == 0 )
+        {
+            isSame = true;
+        }
+    }
+    EXPECT_EQ(isSame, true);
+
+    OIC::Service::NSProviderService::getInstance()->unregisterTopic(str1);
+    responseCon.wait_for(lock, g_waitForResponse);
+}
+
+TEST_F(NotificationProviderServiceTest, ExpectEqualSetConsumerTopicsAndGetConsumerTopics)
+{
+    std::string str1("TEST1");
+    std::string str2("TEST2");
+    OIC::Service::NSProviderService::getInstance()->registerTopic(str1);
+    OIC::Service::NSProviderService::getInstance()->registerTopic(str2);
+    g_consumer->setTopic(str1);
+
+    std::unique_lock< std::mutex > lock { mutexForCondition };
+    responseCon.wait_for(lock, g_waitForResponse);
+
+    bool isSame = false;
+    OIC::Service::NSTopicsList *topicList =  g_consumer->getConsumerTopicList();
+
+    if (!topicList)
+    {
+        printf("topic is NULL\n");
+        isSame = false;
+    }
+    else
+    {
+        std::string compString[10];
+        int i = 0, state[10];
+        for (auto itr : topicList->getTopicsList())
+        {
+            compString[i] = itr->getTopicName();
+            state[i++] = (int) itr->getState();
+        }
+        std::cout << compString[0] << std::endl;
+        std::cout << compString[1] << std::endl;
+        if (str1.compare(compString[0]) == 0 && str2.compare(compString[1]) == 0
+            && state[0] == 1 &&  state[1] == 0)
+        {
+            isSame = true;
+        }
+    }
+
+    EXPECT_EQ(isSame, true);
+
+    OIC::Service::NSProviderService::getInstance()->unregisterTopic(str1);
+    OIC::Service::NSProviderService::getInstance()->unregisterTopic(str2);
+    responseCon.wait_for(lock, g_waitForResponse);
+}
+
+TEST_F(NotificationProviderServiceTest, ExpectEqualUnSetConsumerTopicsAndGetConsumerTopics)
+{
+    std::string str1("TEST1");
+    std::string str2("TEST2");
+    OIC::Service::NSProviderService::getInstance()->registerTopic(str1);
+    OIC::Service::NSProviderService::getInstance()->registerTopic(str2);
+    g_consumer->setTopic(str1);
+    g_consumer->setTopic(str2);
+    g_consumer->unsetTopic(str1);
+
+    std::unique_lock< std::mutex > lock { mutexForCondition };
+    responseCon.wait_for(lock, g_waitForResponse);
+
+    bool isSame = false;
+    OIC::Service::NSTopicsList *topicList =  g_consumer->getConsumerTopicList();
+
+    if (!topicList)
+    {
+        printf("topic is NULL\n");
+        isSame = false;
+    }
+    else
+    {
+        std::string compString[10];
+        int i = 0, state[10];
+        for (auto itr : topicList->getTopicsList())
+        {
+            compString[i] = itr->getTopicName();
+            state[i++] = (int) itr->getState();
+        }
+        std::cout << compString[0] << std::endl;
+        std::cout << compString[1] << std::endl;
+        if (str1.compare(compString[0]) == 0 && str2.compare(compString[1]) == 0
+            && state[0] == 0 &&  state[1] == 1)
+        {
+            isSame = true;
+        }
+    }
+
+    EXPECT_EQ(isSame, true);
+
+    OIC::Service::NSProviderService::getInstance()->unregisterTopic(str1);
+    OIC::Service::NSProviderService::getInstance()->unregisterTopic(str2);
+    responseCon.wait_for(lock, g_waitForResponse);
 }
 
 TEST_F(NotificationProviderServiceTest, CancelObserves)
 {
     bool ret = g_consumerSimul.cancelObserves();
 
-    std::unique_lock< std::mutex > lock{ mutexForCondition };
-    responseCon.wait_for(lock, std::chrono::milliseconds(5000));
+    std::unique_lock< std::mutex > lock { mutexForCondition };
+    responseCon.wait_for(lock, g_waitForResponse);
 
     EXPECT_EQ(ret, true);
 }
index b9230db..90ef7f5 100644 (file)
@@ -53,7 +53,7 @@ GTest_Main = File(gtest_dir + '/lib/.libs/libgtest_main.a')
 
 notification_wrapper_test_env.AppendUnique(LIBPATH = [lib_env.get('BUILD_DIR')])
 notification_wrapper_test_env.AppendUnique(LIBS = [
-    'connectivity_abstraction', 'oc', 'octbstack', 'oc_logger', 'coap', 'notification_provider', 'notification_consumer' ,
+    'connectivity_abstraction', 'oc', 'octbstack', 'oc_logger', 'coap', 
     GTest_Main, GTest])
 
 if env.get('WITH_TCP') == True:
@@ -82,10 +82,10 @@ notification_wrapper_test_env.AppendUnique(CPPPATH = ['../../src/consumer'])
 ######################################################################
 
 notification_consumer_wrapper_test_env = notification_wrapper_test_env.Clone()
-notification_consumer_wrapper_test_env.AppendUnique(LIBS = ['notification_consumer_wrapper'])
+notification_consumer_wrapper_test_env.AppendUnique(LIBS = ['notification_consumer_wrapper','notification_consumer'])
 
 notification_provider_wrapper_test_env = notification_wrapper_test_env.Clone()
-notification_provider_wrapper_test_env.AppendUnique(LIBS = ['notification_provider_wrapper'])
+notification_provider_wrapper_test_env.AppendUnique(LIBS = ['notification_provider_wrapper','notification_provider'])
 
 notification_consumer_wrapper_test_src = env.Glob('./NSConsumerServiceTest.cpp')
 notification_consumer_wrapper_test = notification_consumer_wrapper_test_env.Program('notification_consumer_wrapper_test', notification_consumer_wrapper_test_src)
index 373dbf2..9023618 100755 (executable)
@@ -16,6 +16,6 @@ android {
 dependencies {\r
     compile fileTree(include: ['*.jar'], dir: 'libs')\r
     compile 'com.android.support:appcompat-v7:23.0.1'\r
-    compile project(':iotivity-base-armeabi-debug')\r
-    compile project(':iotivity-armeabi-notification-service-debug')\r
+    compile project(':iotivity-base-armeabi-release')\r
+    compile project(':iotivity-armeabi-notification-service-release')\r
 }\r
index f953507..175356d 100755 (executable)
@@ -31,29 +31,33 @@ import org.iotivity.base.OcResourceHandle;
 import org.iotivity.base.PlatformConfig;\r
 import org.iotivity.base.QualityOfService;\r
 import org.iotivity.base.ServiceType;\r
+import org.iotivity.service.ns.common.NSException;\r
 import org.iotivity.service.ns.common.SyncInfo;\r
+import org.iotivity.service.ns.common.TopicsList;\r
 import org.iotivity.service.ns.consumer.ConsumerService;\r
 import org.iotivity.service.ns.consumer.Provider;\r
 \r
 import java.util.HashMap;\r
 \r
 public class ConsumerProxy\r
-    implements ConsumerService.OnProviderDiscoveredListner,\r
-    ConsumerService.OnSubscriptionAcceptedListener,\r
+    implements ConsumerService.OnProviderDiscoveredListener,\r
+    Provider.OnProviderStateListener,\r
     Provider.OnMessageReceivedListner, Provider.OnSyncInfoReceivedListner\r
 {\r
-\r
     private static final String TAG = "NS_CONSUMER_PROXY";\r
 \r
     private Context mContext = null;\r
     private ConsumerService consumerService = null;\r
+    private boolean mAcceptor = false;\r
+    private Provider mProvider = null;\r
 \r
     private Handler mHandler = null;\r
 \r
     private static final int PROVIDER_DISCOVERED = 1;\r
-    private static final int SUBSCRIPTION_ACCEPTED = 2;\r
+    private static final int STATE_CHANGED = 2;\r
     private static final int MESSAGE_RECEIVED = 3;\r
     private static final int SYNCINFO_RECEIVED = 4;\r
+    private static final int TOPICS_RECEIVED = 5;\r
 \r
     public ConsumerProxy(Context context)\r
     {\r
@@ -68,6 +72,11 @@ public class ConsumerProxy
         this.mHandler = handler;\r
     }\r
 \r
+    public boolean getAcceptor()\r
+    {\r
+        return mAcceptor;\r
+    }\r
+\r
     private void configurePlatform()\r
     {\r
 \r
@@ -98,7 +107,7 @@ public class ConsumerProxy
         configurePlatform();\r
         try\r
         {\r
-            consumerService.Start(this, this);\r
+            consumerService.start(this);\r
         }\r
         catch (Exception e)\r
         {\r
@@ -110,7 +119,8 @@ public class ConsumerProxy
     {\r
         try\r
         {\r
-            consumerService.Stop();\r
+            consumerService.stop();\r
+            mProvider = null;\r
         }\r
         catch (Exception e)\r
         {\r
@@ -122,7 +132,7 @@ public class ConsumerProxy
     {\r
         try\r
         {\r
-            consumerService.EnableRemoteService(serverAddress);\r
+            consumerService.enableRemoteService(serverAddress);\r
         }\r
         catch (Exception e)\r
         {\r
@@ -134,112 +144,94 @@ public class ConsumerProxy
     {\r
         try\r
         {\r
-            consumerService.RescanProvider();\r
+            consumerService.rescanProvider();\r
         }\r
         catch (Exception e)\r
         {\r
             Log.e(TAG, "Exception: rescanProvider : " + e);\r
         }\r
     }\r
-\r
-    public Provider getProvider(String providerId)\r
-    {\r
-        Provider provider = null;\r
-        try\r
-        {\r
-            provider = consumerService.GetProvider(providerId);\r
-        }\r
-        catch (Exception e)\r
-        {\r
-            Log.e(TAG, "Exception: getProvider : " + e);\r
-        }\r
-        return provider;\r
-    }\r
-\r
-    public void subscribe(String providerId)\r
+    public void getTopicsList()\r
     {\r
-        try\r
+        if (mProvider != null)\r
         {\r
-            Provider provider = getProvider(providerId);\r
-            if (provider != null)\r
-                provider.Subscribe();\r
-            else\r
-                Log.e(TAG, "providerID is Null : ");\r
+            try\r
+            {\r
+                TopicsList topicsList = mProvider.getTopicList();\r
+            }\r
+            catch (Exception e)\r
+            {\r
+                Log.e(TAG, "Exception: getTopicsList : " + e);\r
+            }\r
         }\r
-        catch (Exception e)\r
+        else\r
         {\r
-            Log.e(TAG, "Exception: Subscribe : " + e);\r
+            Log.e(TAG, "getTopicsList Provider NULL");\r
         }\r
     }\r
-\r
-    public void unsubscribe(String providerId)\r
+    public void updateTopicList(TopicsList topicsList)\r
     {\r
-        try\r
+        if (mProvider != null)\r
         {\r
-            Provider provider = getProvider(providerId);\r
-            if (provider != null)\r
-                provider.Unsubscribe();\r
-            else\r
-                Log.e(TAG, "providerID is Null : ");\r
+            try\r
+            {\r
+                mProvider.updateTopicList(topicsList);\r
+            }\r
+            catch (Exception e)\r
+            {\r
+                Log.e(TAG, "Exception: updateTopicList : " + e);\r
+            }\r
         }\r
-        catch (Exception e)\r
+        else\r
         {\r
-            Log.e(TAG, "Exception: Unsubscribe : " + e);\r
+            Log.e(TAG, "updateTopicList Provider NULL");\r
         }\r
     }\r
-\r
-    public void sendSyncInfo(String providerId, long messageId, SyncInfo.SyncType syncType)\r
+    @Override\r
+    public void onProviderDiscovered(Provider provider)\r
     {\r
-        try\r
-        {\r
-            Provider provider = getProvider(providerId);\r
-            if (provider != null)\r
-                provider.SendSyncInfo(messageId, syncType);\r
-            else\r
-                Log.e(TAG, "providerID is Null : ");\r
-        }\r
-        catch (Exception e)\r
+        Log.i(TAG, "onProviderDiscovered");\r
+        if (provider == null)\r
         {\r
-            Log.e(TAG, "Exception: SendSyncInfo : " + e);\r
+            Log.e(TAG, "providerID is Null  ");\r
+            return;\r
         }\r
-    }\r
-\r
-    public void setListener(String providerId)\r
-    {\r
+        mProvider = provider;\r
+        Log.i(TAG, "Provider ID: " + provider.getProviderId() );\r
+        Message msg = mHandler.obtainMessage(PROVIDER_DISCOVERED,\r
+                                             "Provider Discovered Id: " + provider.getProviderId());\r
+        mHandler.sendMessage(msg);\r
         try\r
         {\r
-            Provider provider = getProvider(providerId);\r
-            if (provider != null)\r
-                provider.SetListener(this, this);\r
+            Log.i(TAG, "setListeners to Discovered Provider");\r
+            provider.setListener(this, this, this);\r
+            Log.i(TAG, "setListeners done");\r
+            if (! provider.isSubscribed())\r
+            {\r
+                Log.i(TAG, "Provider not subscribed. Acceptor is Consumer");\r
+                mAcceptor = false;\r
+                provider.subscribe();\r
+            }\r
             else\r
-                Log.e(TAG, "providerID is Null : ");\r
+            {\r
+                Log.i(TAG, "Provider is already subscribed. Acceptor is Provider");\r
+                mAcceptor = true;\r
+            }\r
         }\r
         catch (Exception e)\r
         {\r
-            Log.e(TAG, "Exception: SetListener : " + e);\r
+            Log.e(TAG, "Exception : " + e);\r
         }\r
     }\r
 \r
     @Override\r
-    public void onProviderDiscovered(Provider provider)\r
+    public void onProviderStateReceived(Provider.ProviderState state)\r
     {\r
-        Log.i(TAG, "onProviderDiscovered");\r
+        Log.i(TAG, "onProviderStateReceived");\r
 \r
-        Log.i(TAG, "Provider ID: " + provider.getProviderId() );\r
-        Message msg = mHandler.obtainMessage(PROVIDER_DISCOVERED, provider.getProviderId());\r
+        Log.i(TAG, "Provider state: " + state );\r
+        Message msg = mHandler.obtainMessage(STATE_CHANGED, "Provider state: " + state);\r
         mHandler.sendMessage(msg);\r
-        subscribe(provider.getProviderId());\r
-    }\r
-\r
-    @Override\r
-    public void onSubscriptionAccepted(Provider provider)\r
-    {\r
-        Log.i(TAG, "onSubscriptionAccepted");\r
-\r
-        Log.i(TAG, "Provider ID: " + provider.getProviderId() );\r
-        Message msg = mHandler.obtainMessage(SUBSCRIPTION_ACCEPTED, provider.getProviderId());\r
-        mHandler.sendMessage(msg);\r
-        setListener(provider.getProviderId());\r
     }\r
 \r
     @Override\r
@@ -250,14 +242,25 @@ public class ConsumerProxy
         Log.i(TAG, "Message Id: " + message.getMessageId());\r
         Log.i(TAG, "Message title: " + message.getTitle());\r
         Log.i(TAG, "Message Content: " + message.getContentText());\r
+        Log.i(TAG, "Message Topic: " + message.getTopic());\r
         Log.i(TAG, "Message Source: " + message.getSourceName());\r
 \r
         Message msg = mHandler.obtainMessage(MESSAGE_RECEIVED,\r
-                                             "Message Id: " + message.getMessageId() +\r
-                                             " / Message title: " + message.getTitle() +\r
-                                             " / Message Content: " + message.getContentText() +\r
-                                             " / Message Source: " + message.getSourceName() );\r
+                                             "Message Id: " + message.getMessageId() + "\n" +\r
+                                             "Message title: " + message.getTitle() + "\n" +\r
+                                             "Message Content: " + message.getContentText() + "\n" +\r
+                                             "Message Topic: " + message.getTopic() + "\n" +\r
+                                             "Message Source: " + message.getSourceName() );\r
         mHandler.sendMessage(msg);\r
+        try\r
+        {\r
+            Log.i(TAG, "send READ syncInfo");\r
+            mProvider.sendSyncInfo(message.getMessageId(), SyncInfo.SyncType.READ);\r
+        }\r
+        catch (Exception e)\r
+        {\r
+            Log.e(TAG, "Exception : " + e);\r
+        }\r
     }\r
 \r
     @Override\r
@@ -268,8 +271,8 @@ public class ConsumerProxy
         Log.i(TAG, "Sync Id: " + sync.getMessageId());\r
         Log.i(TAG, "Sync STATE: " + sync.getState());\r
         Message msg = mHandler.obtainMessage(SYNCINFO_RECEIVED,\r
-                                             "Sync Id: " + sync.getMessageId() +\r
-                                             " / Sync STATE: " + sync.getState());\r
+                                             "Sync Id: " + sync.getMessageId() + "\n" +\r
+                                             "Sync STATE: " + sync.getState());\r
         mHandler.sendMessage(msg);\r
     }\r
 }\r
index 01e2a99..7d9e463 100755 (executable)
@@ -32,14 +32,18 @@ import android.widget.EditText;
 import android.widget.TextView;\r
 import android.widget.Toast;\r
 \r
+import org.iotivity.service.ns.common.TopicsList;\r
+\r
 public class MainActivity extends AppCompatActivity\r
 {\r
-\r
     private final String TAG = "NS_MAIN_ACTIVITY";\r
 \r
     private Button btnStart;\r
     private Button btnStop;\r
     private Button btnRescan;\r
+    private Button btnEnableRemoteService;\r
+    private Button btnGetTopicList;\r
+    private Button btnUpdateTopicList;\r
     private static TextView TvLog;\r
 \r
     private boolean isStarted = false;\r
@@ -48,9 +52,10 @@ public class MainActivity extends AppCompatActivity
     private ConsumerProxy mConsumerProxy = null;\r
 \r
     private static final int PROVIDER_DISCOVERED = 1;\r
-    private static final int SUBSCRIPTION_ACCEPTED = 2;\r
+    private static final int STATE_CHANGED = 2;\r
     private static final int MESSAGE_RECEIVED = 3;\r
     private static final int SYNCINFO_RECEIVED = 4;\r
+    private static final int TOPICS_RECEIVED = 5;\r
 \r
     public static Handler mHandler = new Handler()\r
     {\r
@@ -64,16 +69,16 @@ public class MainActivity extends AppCompatActivity
                         String providerId = (String) msg.obj;\r
                         if (providerId != null)\r
                         {\r
-                            TvLog.append("Discovered : ProviderID: " + providerId + "\n");\r
+                            TvLog.append( providerId + "\n");\r
                         }\r
                         break;\r
                     }\r
-                case SUBSCRIPTION_ACCEPTED:\r
+                case STATE_CHANGED:\r
                     {\r
-                        String providerId = (String) msg.obj;\r
-                        if (providerId != null)\r
+                        String state = (String) msg.obj;\r
+                        if (state != null)\r
                         {\r
-                            TvLog.append("Subscription Accepted : ProviderID: " + providerId + "\n");\r
+                            TvLog.append( state + "\n");\r
                         }\r
                         break;\r
                     }\r
@@ -82,7 +87,7 @@ public class MainActivity extends AppCompatActivity
                         String message = (String) msg.obj;\r
                         if (message != null)\r
                         {\r
-                            TvLog.append("Message Received : " + message + "\n");\r
+                            TvLog.append( message + "\n");\r
                         }\r
                         break;\r
                     }\r
@@ -91,7 +96,7 @@ public class MainActivity extends AppCompatActivity
                         String sync = (String) msg.obj;\r
                         if (sync != null)\r
                         {\r
-                            TvLog.append("SyncInfo Received : " + sync + "\n");\r
+                            TvLog.append( sync + "\n");\r
                         }\r
                         break;\r
                     }\r
@@ -122,12 +127,18 @@ public class MainActivity extends AppCompatActivity
         btnStart = (Button) findViewById(R.id.BtnStart);\r
         btnStop = (Button) findViewById(R.id.BtnStop);\r
         btnRescan = (Button) findViewById(R.id.BtnRescan);\r
+        btnEnableRemoteService = (Button) findViewById(R.id.BtnEnableRemoteService);\r
+        btnGetTopicList = (Button) findViewById(R.id.BtnGetTopicList);\r
+        btnUpdateTopicList = (Button) findViewById(R.id.BtnUpdateTopicList);\r
 \r
         TvLog = (TextView) findViewById(R.id.TvLog);\r
 \r
         btnStart.setOnClickListener(mClickListener);\r
         btnStop.setOnClickListener(mClickListener);\r
         btnRescan.setOnClickListener(mClickListener);\r
+        btnEnableRemoteService.setOnClickListener(mClickListener);\r
+        btnGetTopicList.setOnClickListener(mClickListener);\r
+        btnUpdateTopicList.setOnClickListener(mClickListener);\r
 \r
         mConsumerProxy = new ConsumerProxy(getApplicationContext());\r
         mConsumerProxy.setHandler(mHandler);\r
@@ -136,7 +147,7 @@ public class MainActivity extends AppCompatActivity
     @Override\r
     protected void onDestroy()\r
     {\r
-        if(isStarted)\r
+        if (isStarted)\r
             mConsumerProxy.stopNotificationConsumer();\r
         super.onDestroy();\r
     }\r
@@ -152,7 +163,6 @@ public class MainActivity extends AppCompatActivity
         {\r
             switch (v.getId())\r
             {\r
-\r
                 case R.id.BtnStart:\r
                     {\r
                         if (isStarted == false)\r
@@ -174,29 +184,65 @@ public class MainActivity extends AppCompatActivity
                     {\r
                         if (isStarted == false)\r
                         {\r
-                            Log.e(TAG, "Fail to stop service");\r
+                            Log.e(TAG, "Fail to stop service. Service has not been started");\r
                             break;\r
                         }\r
-\r
+                        TvLog.append("Stop NS-Consumer\n");\r
                         mConsumerProxy.stopNotificationConsumer();\r
                         isStarted = false;\r
-\r
-                        TvLog.append("Stop NS-Consumer\n");\r
                     }\r
                     break;\r
                 case R.id.BtnRescan:\r
                     {\r
                         if (isStarted == false)\r
                         {\r
-                            Log.e(TAG, "Fail to rescan");\r
+                            Log.e(TAG, "Fail to rescan. Service has not been started");\r
                             break;\r
                         }\r
 \r
-                        mConsumerProxy.rescanProvider();\r
                         TvLog.append("Rescan NS-Consumer\n");\r
+                        mConsumerProxy.rescanProvider();\r
                     }\r
                     break;\r
+                case R.id.BtnEnableRemoteService:\r
+                    {\r
+                        if (isStarted == false)\r
+                        {\r
+                            Log.e(TAG, "Fail to Enable RemoteService. Service has not been started");\r
+                            break;\r
+                        }\r
+                        TvLog.append("EnableRemoteService NS-Consumer\n");\r
 \r
+                        //TODO: Update to read the serverAddress from UI\r
+                        String serverAddress = new String();\r
+                        mConsumerProxy.enableRemoteService(serverAddress);\r
+                    }\r
+                    break;\r
+                case R.id.BtnGetTopicList:\r
+                    {\r
+                        if (isStarted == false)\r
+                        {\r
+                            Log.e(TAG, "Fail to GetTopicList. Service has not been started");\r
+                            break;\r
+                        }\r
+                        TvLog.append("GetTopicList NS-Consumer\n");\r
+                        mConsumerProxy.getTopicsList();\r
+                    }\r
+                    break;\r
+                case R.id.BtnUpdateTopicList:\r
+                    {\r
+                        if (isStarted == false)\r
+                        {\r
+                            Log.e(TAG, "Fail to UpdateTopicList. Service has not been started");\r
+                            break;\r
+                        }\r
+                        TvLog.append("UpdateTopicList NS-Consumer\n");\r
+\r
+                        //TODO: Update to read the TopicsList from UI\r
+                        TopicsList topicsList = new TopicsList();\r
+                        mConsumerProxy.updateTopicList(topicsList);\r
+                    }\r
+                    break;\r
             }\r
         }\r
     };\r
index 5cc23da..2a93adc 100755 (executable)
                 android:layout_width="match_parent"\r
                 android:id="@+id/BtnRescan"\r
                 android:text="RESCAN"/>\r
+            <Button\r
+                android:layout_gravity="center_vertical|center_horizontal"\r
+                android:layout_height="0dp"\r
+                android:layout_width="match_parent"\r
+                android:id="@+id/BtnEnableRemoteService"\r
+                android:text="Enable Remote Service"/>\r
+            <Button\r
+                android:layout_gravity="center_vertical|center_horizontal"\r
+                android:layout_height="0dp"\r
+                android:layout_width="match_parent"\r
+                android:id="@+id/BtnGetTopicList"\r
+                android:text="Get TopicList"/>\r
+            <Button\r
+                android:layout_gravity="center_vertical|center_horizontal"\r
+                android:layout_height="0dp"\r
+                android:layout_width="match_parent"\r
+                android:id="@+id/BtnUpdateTopicList"\r
+                android:text="Update TopicList"/>\r
         </LinearLayout>\r
 \r
         <LinearLayout\r
diff --git a/service/notification/examples/android/NotiConsumerExample/iotivity-armeabi-notification-service-debug/iotivity-armeabi-notification-service-debug.aar b/service/notification/examples/android/NotiConsumerExample/iotivity-armeabi-notification-service-debug/iotivity-armeabi-notification-service-debug.aar
deleted file mode 100755 (executable)
index 20b37e6..0000000
Binary files a/service/notification/examples/android/NotiConsumerExample/iotivity-armeabi-notification-service-debug/iotivity-armeabi-notification-service-debug.aar and /dev/null differ
diff --git a/service/notification/examples/android/NotiConsumerExample/iotivity-base-armeabi-debug/build.gradle b/service/notification/examples/android/NotiConsumerExample/iotivity-base-armeabi-debug/build.gradle
deleted file mode 100755 (executable)
index e09bcd6..0000000
+++ /dev/null
@@ -1,2 +0,0 @@
-configurations.maybeCreate("default")
-artifacts.add("default", file('iotivity-base-armeabi-debug.aar'))
\ No newline at end of file
diff --git a/service/notification/examples/android/NotiConsumerExample/iotivity-base-armeabi-debug/iotivity-base-armeabi-debug.aar b/service/notification/examples/android/NotiConsumerExample/iotivity-base-armeabi-debug/iotivity-base-armeabi-debug.aar
deleted file mode 100755 (executable)
index 18802ee..0000000
Binary files a/service/notification/examples/android/NotiConsumerExample/iotivity-base-armeabi-debug/iotivity-base-armeabi-debug.aar and /dev/null differ
diff --git a/service/notification/examples/android/NotiConsumerExample/iotivity-base-armeabi-release/build.gradle b/service/notification/examples/android/NotiConsumerExample/iotivity-base-armeabi-release/build.gradle
new file mode 100755 (executable)
index 0000000..a4078ab
--- /dev/null
@@ -0,0 +1,2 @@
+configurations.maybeCreate("default")
+artifacts.add("default", file('iotivity-base-armeabi-release.aar'))
\ No newline at end of file
index 68c1980..836b36e 100755 (executable)
@@ -1 +1 @@
-include ':app', ':iotivity-base-armeabi-debug', ':iotivity-armeabi-notification-service-debug'
\ No newline at end of file
+include ':app', ':iotivity-base-armeabi-release', ':iotivity-armeabi-notification-service-release'
\ No newline at end of file
index b2772bb..a5072f6 100755 (executable)
@@ -41,7 +41,7 @@ import org.iotivity.service.ns.common.MediaContents;
 public class MainActivity extends AppCompatActivity {\r
 \r
     private final String TAG = "NS_MAIN_ACTIVITY";\r
-    private static final int MESSAGE_SUBSCRIPTION = 1;\r
+    private static final int CONSUMER_SUBSCRIBED = 1;\r
     private static final int MESSAGE_SYNC = 2;\r
     private static final int MESSAGE_NOTIFICATION = 3;\r
 \r
@@ -68,16 +68,16 @@ public class MainActivity extends AppCompatActivity {
         @Override\r
         public void handleMessage(Message msg) {\r
             switch (msg.what) {\r
-                case MESSAGE_SUBSCRIPTION:\r
-                    String subscriber = (String) msg.obj;\r
-                    if(subscriber != null)\r
-                        TvLog.append("Subscriber IP(" + ++subCnt + "): " + subscriber + "\n");\r
+                case CONSUMER_SUBSCRIBED:\r
+                    String ConsumerId = (String) msg.obj;\r
+                    if(ConsumerId != null)\r
+                        TvLog.append("Consumer Subscibed: " + ConsumerId + "\n");\r
                     break;\r
 \r
                 case MESSAGE_SYNC:\r
                     String sync = (String) msg.obj;\r
                     if(sync != null)\r
-                        TvLog.append("Sync-Read(Msg ID: " + sync + ")\n");\r
+                        TvLog.append("SyncInfo Received :" + sync + "\n");\r
                     break;\r
 \r
                 default:\r
index 789afe1..0c5aada 100755 (executable)
@@ -23,7 +23,7 @@
 package com.sec.notiproviderexample;\r
 \r
 import android.content.Context;\r
-import android.os.Handler;\r
+import android.os.*;\r
 import android.util.Log;\r
 import android.widget.Toast;\r
 \r
@@ -33,6 +33,7 @@ import org.iotivity.base.OcResourceHandle;
 import org.iotivity.base.PlatformConfig;\r
 import org.iotivity.base.QualityOfService;\r
 import org.iotivity.base.ServiceType;\r
+import org.iotivity.service.ns.common.Message;\r
 import org.iotivity.service.ns.provider.*;\r
 import org.iotivity.service.ns.common.*;\r
 \r
@@ -40,7 +41,7 @@ import org.iotivity.service.ns.common.*;
 import java.util.HashMap;\r
 \r
 public class ProviderProxy\r
-        implements ProviderService.OnSubscriptionListener, ProviderService.OnSyncInfoListener{\r
+        implements ProviderService.OnConsumerSubscribedListener, ProviderService.OnMessageSynchronizedListener{\r
 \r
     private static final String TAG = "NS_PROVIDER_PROXY";\r
 \r
@@ -51,7 +52,7 @@ public class ProviderProxy
 \r
     private Handler mHandler = null;\r
 \r
-    private static final int MESSAGE_SUBSCRIPTION = 1;\r
+    private static final int CONSUMER_SUBSCRIBED = 1;\r
     private static final int MESSAGE_SYNC = 2;\r
 \r
     private static final int SYNC_READ = 0;\r
@@ -97,7 +98,7 @@ public class ProviderProxy
         Log.i(TAG, "Start ProviderService -IN");\r
         configurePlatform();\r
         try{\r
-            int result =  ioTNotification.Start(policy, this, this);\r
+            int result =  ioTNotification.start(this, this, policy, "Info");\r
             Log.i(TAG, "Notification Start: " + result);\r
         }\r
         catch(Exception e){\r
@@ -115,7 +116,7 @@ public class ProviderProxy
             Log.e(TAG, "Exception: stopping presence when terminating NS server: " + e);\r
         }\r
         try{\r
-            int result =  ioTNotification.Stop();\r
+            int result =  ioTNotification.stop();\r
             Log.i(TAG, "Notification Stop: " + result);\r
         }\r
         catch(Exception e){\r
@@ -129,7 +130,7 @@ public class ProviderProxy
         Log.i(TAG, "SendMessage ProviderService - IN");\r
 \r
         try{\r
-            int result =  ioTNotification.SendMessage(notiMessage);\r
+            int result =  ioTNotification.sendMessage(notiMessage);\r
             Log.i(TAG, "Notification Send Message: " + result);\r
         }\r
         catch(Exception e){\r
@@ -151,7 +152,7 @@ public class ProviderProxy
             if(msgMap.get(messageId) == SYNC_UNREAD)\r
             {\r
                 try{\r
-                    ioTNotification.SendSyncInfo(messageId,syncType );\r
+                    ioTNotification.sendSyncInfo(messageId, syncType);\r
                     Log.i(TAG, "Notification Sync " );\r
                 }\r
                 catch(Exception e) {\r
@@ -166,7 +167,7 @@ public class ProviderProxy
     public void EnableRemoteService(String servAdd) {\r
         Log.i(TAG, "EnableRemoteService ProviderService - IN");\r
         try{\r
-            int result = ioTNotification.EnableRemoteService(servAdd);\r
+            int result = ioTNotification.enableRemoteService(servAdd);\r
             Log.i(TAG, "Notification EnableRemoteService: "+ result );\r
         }\r
         catch(Exception e) {\r
@@ -178,7 +179,7 @@ public class ProviderProxy
     public void DisableRemoteService(String servAdd) {\r
         Log.i(TAG, "DisableRemoteService ProviderService - IN");\r
         try{\r
-            int result = ioTNotification.DisableRemoteService(servAdd);\r
+            int result = ioTNotification.disableRemoteService(servAdd);\r
             Log.i(TAG, "Notification DisableRemoteService: "+ result );\r
         }\r
         catch(Exception e) {\r
@@ -191,7 +192,7 @@ public class ProviderProxy
     {\r
         Log.i(TAG,"AcceptSubscription ProviderService - IN");\r
         try{\r
-            int result = consumer.AcceptSubscription(consumer, accepted);\r
+            int result = consumer.acceptSubscription(accepted);\r
             Log.i(TAG, "Notification AcceptSubscription: "+result );\r
         }\r
         catch(Exception e) {\r
@@ -204,12 +205,18 @@ public class ProviderProxy
     public void onConsumerSubscribed(Consumer consumer) {\r
         Log.i(TAG, "onConsumerSubscribed - IN");\r
         AcceptSubscription(consumer, true);\r
+        android.os.Message msg = mHandler.obtainMessage(CONSUMER_SUBSCRIBED,\r
+                "Consumer Id: " + consumer.getConsumerId()  );\r
+        mHandler.sendMessage(msg);\r
         Log.i(TAG, "onConsumerSubscribed - OUT");\r
     }\r
 \r
     @Override\r
     public void onMessageSynchronized(SyncInfo syncInfo) {\r
         Log.i(TAG, "Received SyncInfo with messageID: "+syncInfo.getMessageId());\r
+        android.os.Message msg = mHandler.obtainMessage(MESSAGE_SYNC,\r
+                "Message Id: " + syncInfo.getMessageId()  );\r
+        mHandler.sendMessage(msg);\r
     }\r
 \r
     public HashMap<String, Integer> getMsgMap() {\r
index 15b2f37..790caca 100644 (file)
@@ -49,10 +49,15 @@ if env.get('WITH_CLOUD') == True:
         notification_sample_env.AppendUnique(CPPPATH = ['../../src/provider'])
        notification_sample_env.AppendUnique(CPPDEFINES = ['WITH_CLOUD'])
 
-       CONSUMER_CLOUD = File('cloud_connector.c')
-       notification_sample_consumer_src = ['notificationconsumer.c', CONSUMER_CLOUD]
-        PROVIDER_CLOUD = File('cloud_connector.c')
-        notification_sample_provider_src = ['notificationprovider.c', PROVIDER_CLOUD]
+        providerCloudConnectorObj = notification_sample_env.Object('cloud_connector.c')
+        consumerCloudConnectorObj = notification_sample_env.Object('cloud_connector.c')
+
+        #PROVIDER_CLOUD = File('cloud_connector.c')
+        #notification_sample_provider_src = ['notificationprovider.c', PROVIDER_CLOUD]
+        notification_sample_provider_src = ['notificationprovider.c', providerCloudConnectorObj]
+       #CONSUMER_CLOUD = File('cloud_connector.c')
+       #notification_sample_consumer_src = ['notificationconsumer.c', CONSUMER_CLOUD]
+        notification_sample_consumer_src = ['notificationconsumer.c', consumerCloudConnectorObj]
 
 if env.get('WITH_TCP') == True:
        notification_sample_env.AppendUnique(CPPDEFINES = ['WITH_TCP'])
@@ -71,3 +76,7 @@ notification_sample_consumer_env = notification_sample_env.Clone()
 notification_sample_consumer_env.AppendUnique(LIBS = 'libnotification_consumer')
 notificationconsumer = notification_sample_consumer_env.Program('notificationconsumer', notification_sample_consumer_src)
 i_notificationprovider = notification_sample_consumer_env.Install(env.get('BUILD_DIR'), notificationconsumer)
+
+if env.get('WITH_CLOUD') == True:
+        Export('providerCloudConnectorObj')
+        Export('consumerCloudConnectorObj')
index 9d44402..26a49ed 100644 (file)
@@ -20,6 +20,7 @@
 
 #include <stdio.h>
 #include <unistd.h>
+#include <string.h>
 #include "pthread.h"
 
 #include "ocstack.h"
@@ -42,6 +43,7 @@ char CLOUD_ACCESS_TOKEN[50];
 
 
 NSProvider * g_provider = NULL;
+NSTopicLL * g_topicLL = NULL;
 
 FILE* server_fopen(const char *path, const char *mode)
 {
@@ -49,19 +51,12 @@ FILE* server_fopen(const char *path, const char *mode)
     return fopen("oic_ns_provider_db.dat", mode);
 }
 
-void onDiscoverNotification(NSProvider * provider)
-{
-    printf("notification resource discovered\n");
-    printf("subscribe result %d\n", NSSubscribe(provider));
-    printf("startSubscribing\n");
-}
-
-void printProviderTopicList(NSProvider *provider)
+void printProviderTopicList(NSTopicLL * topics)
 {
     printf("printProviderTopicList\n");
-    if (provider->topicLL)
+    if (topics)
     {
-        NSTopicLL * iter = provider->topicLL;
+        NSTopicLL * iter = topics;
         while (iter)
         {
             printf("Topic Name: %s\t Topic State: %d\n", iter->topicName, iter->state);
@@ -70,16 +65,23 @@ void printProviderTopicList(NSProvider *provider)
     }
 }
 
-void onProviderChanged(NSProvider * provider, NSResponse response)
+void onProviderChanged(NSProvider * provider, NSProviderState response)
 {
     printf("Provider changed: %d\n", response);
     printf("subscribed provider Id : %s\n", provider->providerId);
 
-    if (response == NS_TOPIC)
+    if (response == NS_DISCOVERED)
     {
-        printf ("Provider Topic Updated\n");
+        printf("notification resource discovered\n");
+        printf("subscribe result %d\n", NSSubscribe(provider->providerId));
+        printf("startSubscribing\n");
+    }
 
-        printProviderTopicList(provider);
+    else if (response == NS_TOPIC)
+    {
+        printf ("Provider Topic Updated\n");
+        g_topicLL = NSConsumerGetTopicList(provider->providerId);
+        printProviderTopicList(g_topicLL);
         g_provider = provider;
     }
 }
@@ -138,7 +140,6 @@ int main(void)
     }
 
     NSConsumerConfig cfg;
-    cfg.discoverCb = onDiscoverNotification;
     cfg.changedCb = onProviderChanged;
     cfg.messageCb = onNotificationPosted;
     cfg.syncInfoCb = onNotificationSync;
@@ -184,23 +185,31 @@ int main(void)
                 printf("3. Get Topics\n");
                 if(g_provider)
                 {
-                    NSConsumerGetInterestTopics(g_provider);
+                    g_topicLL = NSConsumerGetTopicList(g_provider->providerId);
+                    printProviderTopicList(g_topicLL);
                 }
                 break;
             case 4:
                 printf("4. Select Topics\n");
 
-                if (g_provider && g_provider->topicLL)
+                if (g_provider && g_topicLL)
                 {
-                    NSTopicLL * iter = g_provider->topicLL;
+                    NSTopicLL * iter = g_topicLL;
                     int i = 0;
                     while (iter)
                     {
                         iter->state = (i++)%2;
-                        printf("Topic Name: %s\t Topic State: %d\n", iter->topicName, iter->state);
                         iter = iter->next;
                     }
-                    NSConsumerSelectInterestTopics(g_provider);
+                    NSResult ret = NSConsumerUpdateTopicList(g_provider->providerId, g_topicLL);
+                    if (ret == NS_OK)
+                    {
+                        printProviderTopicList(g_topicLL);
+                    }
+                    else
+                    {
+                        printf("Update fail\n");
+                    }
                 }
                 break;
             case 5:
index c638d23..32c4f09 100644 (file)
@@ -30,6 +30,7 @@
 #include "pthread.h"
 #include "oic_string.h"
 #include "oic_malloc.h"
+#include "ocstack.h"
 
 #define TAG "NSProviderExample"
 
 #include "cloud_connector.h"
 
 // Input the following values to publish resource to cloud
-char REMOTE_SERVER_ADDRESS[50];
-char AUTH_PROVIDER[50];
-char AUTH_CODE[50];
-char UID[50];
-char ACCESS_TOKEN[50];
+char REMOTE_SERVER_ADDRESS[50] = {'\0',};
+char AUTH_PROVIDER[50] = {'\0',};
+char AUTH_CODE[50] = {'\0',};
+char UID[50] = {'\0',};
+char ACCESS_TOKEN[50] = {'\0',};
 #endif
 
 char mainConsumer[37] = {'\0',};
@@ -78,7 +79,7 @@ void subscribeRequestCallback(NSConsumer *consumer)
         OICStrcpy(mainConsumer, 37, consumer->consumerId);
     }
 
-    NSAcceptSubscription(consumer, true);
+    NSAcceptSubscription(consumer->consumerId, true);
 }
 
 void syncCallback(NSSyncInfo *sync)
@@ -134,6 +135,17 @@ void removeTopics(NSTopicLL * topics)
     }
 }
 
+void input(char * buffer)
+{
+    char ch;
+    int i = 0;
+
+    while( (ch = getchar()) != '\n' && i < 100)
+        buffer[i++] = ch;
+
+    buffer[i] = '\0';
+}
+
 int main()
 {
     int num;
@@ -181,10 +193,15 @@ int main()
 
         printf("input : ");
 
-        scanf("%d", &num);
-        fflush(stdin);
-        scanf("%c", &dummy);
-        fflush(stdin);
+        if(scanf("%d", &num) > 0)
+        {
+            fflush(stdin);
+            if(scanf("%c", &dummy) > 0)
+            {
+                fflush(stdin);
+                printf("\n");
+            }
+        }
 
         switch (num)
         {
@@ -192,7 +209,7 @@ int main()
             {
                 printf("NSStartProvider(Accepter: Provider)");
                 NSProviderConfig config;
-                config.policy = true;
+                config.subControllability = true;
                 config.subRequestCallback = subscribeRequestCallback;
                 config.syncInfoCallback = syncCallback;
                 config.userInfo = OICStrdup("OCF_NOTIFICATION");
@@ -204,7 +221,7 @@ int main()
             {
                 printf("NSStartProvider(Accepter: Consumer)");
                 NSProviderConfig config;
-                config.policy = false;
+                config.subControllability = false;
                 config.subRequestCallback = subscribeRequestCallback;
                 config.syncInfoCallback = syncCallback;
                 config.userInfo = OICStrdup("OCF_NOTIFICATION");
@@ -215,20 +232,19 @@ int main()
             case 3:
             {
                 printf("NSSendNotification()");
-                char title[100];
-                char body[100];
-                char topic[100];
+                char title[100] = {'\0',};
+                char body[100] = {'\0',};
+                char topic[100] = {'\0',};
 
                 printf("id : %d\n", ++id);
                 printf("title : ");
-
-                gets(title);
+                input(title);
 
                 printf("body : ");
-                gets(body);
+                input(body);
 
                 printf("topic : ");
-                gets(topic);
+                input(topic);
 
                 printf("app - mTitle : %s \n", title);
                 printf("app - mContentText : %s \n", body);
@@ -255,28 +271,28 @@ int main()
 
             case 5:
                 printf("NSProviderAddTopic\n");
-                NSProviderAddTopic("OCF_TOPIC1");
-                NSProviderAddTopic("OCF_TOPIC2");
-                NSProviderAddTopic("OCF_TOPIC3");
-                NSProviderAddTopic("OCF_TOPIC4");
+                NSProviderRegisterTopic("OCF_TOPIC1");
+                NSProviderRegisterTopic("OCF_TOPIC2");
+                NSProviderRegisterTopic("OCF_TOPIC3");
+                NSProviderRegisterTopic("OCF_TOPIC4");
                 break;
 
             case 6:
                 printf("NSProviderDeleteTopic\n");
-                NSProviderDeleteTopic("OCF_TOPIC2");
+                NSProviderUnregisterTopic("OCF_TOPIC2");
                 break;
 
             case 7:
                 printf("NSProviderSelectTopic\n");
-                NSProviderSelectTopic(mainConsumer, "OCF_TOPIC1");
-                NSProviderSelectTopic(mainConsumer, "OCF_TOPIC2");
-                NSProviderSelectTopic(mainConsumer, "OCF_TOPIC3");
-                NSProviderSelectTopic(mainConsumer, "OCF_TOPIC4");
+                NSProviderSetConsumerTopic(mainConsumer, "OCF_TOPIC1");
+                NSProviderSetConsumerTopic(mainConsumer, "OCF_TOPIC2");
+                NSProviderSetConsumerTopic(mainConsumer, "OCF_TOPIC3");
+                NSProviderSetConsumerTopic(mainConsumer, "OCF_TOPIC4");
                 break;
 
             case 8:
                 printf("NSProviderUnSelectTopic\n");
-                NSProviderUnselectTopic(mainConsumer, "OCF_TOPIC1");
+                NSProviderUnsetConsumerTopic(mainConsumer, "OCF_TOPIC1");
                 break;
 
             case 9:
@@ -302,20 +318,20 @@ int main()
                 break;
 #ifdef WITH_CLOUD
             case 21:
-                printf("Enable Remote Service");
+                printf("Enable Remote Service\n");
                 if(!IsCloudLoggedin())
                 {
-                    printf("Login required");
+                    printf("Login required\n");
                     break;
                 }
-                NSProviderEnableRemoteService(REMOTE_SERVER_ADDRESS);                
+                NSProviderEnableRemoteService(REMOTE_SERVER_ADDRESS);
                 break;
 
             case 22:
-                printf("Disable Remote Service");
+                printf("Disable Remote Service\n");
                 if(!IsCloudLoggedin())
                 {
-                    printf("Login required");
+                    printf("Login required\n");
                     break;
                 }
                 NSProviderDisableRemoteService(REMOTE_SERVER_ADDRESS);
@@ -323,13 +339,13 @@ int main()
 
             case 31:
                 printf("Remote Server Address: ");
-                gets(REMOTE_SERVER_ADDRESS);
+                input(REMOTE_SERVER_ADDRESS);
 
                 printf("Auth Provider(eg. github): ");
-                gets(AUTH_PROVIDER);
+                input(AUTH_PROVIDER);
 
                 printf("Auth Code: ");
-                gets(AUTH_CODE);
+                input(AUTH_CODE);
 
                 OCCloudSignup(REMOTE_SERVER_ADDRESS, OCGetServerInstanceIDString(),
                     AUTH_PROVIDER, AUTH_CODE, CloudSignupCallback);
@@ -337,21 +353,21 @@ int main()
                 break;
             case 32:
                 printf("Remote Server Address: ");
-                gets(REMOTE_SERVER_ADDRESS);
+                input(REMOTE_SERVER_ADDRESS);
 
                 printf("UID: ");
-                gets(UID);
+                input(UID);
 
                 printf("ACCESS_TOKEN: ");
-                gets(ACCESS_TOKEN);
+                input(ACCESS_TOKEN);
 
                 OCCloudLogin(REMOTE_SERVER_ADDRESS, UID, OCGetServerInstanceIDString(),
                     ACCESS_TOKEN, CloudLoginoutCallback);
-                printf("OCCloudLogin requested");
+                printf("OCCloudLogin requested\n");
                 break;
             case 33:
                 OCCloudLogout(REMOTE_SERVER_ADDRESS, CloudLoginoutCallback);
-                printf("OCCloudLogin requested");
+                printf("OCCloudLogin requested\n");
                 break;
 #endif
             case 0:
index 42a4a4a..c0ec948 100644 (file)
 
 #define NS_UUID_STRING_SIZE 37
 
-#define NS_ATTRIBUTE_POLICY "ACCEPTER"
-#define NS_ATTRIBUTE_MESSAGE "MESSAGE_URI"
-#define NS_ATTRIBUTE_SYNC "SYNC_URI"
-#define NS_ATTRIBUTE_TOPIC "TOPIC_URI"
-#define NS_ATTRIBUTE_MESSAGE_ID "MESSAGE_ID"
-#define NS_ATTRIBUTE_PROVIDER_ID "PROVIDER_ID"
-#define NS_ATTRIBUTE_CONSUMER_ID "CONSUMER_ID"
-#define NS_ATTRIBUTE_TOPIC_LIST "TOPIC_LIST"
-#define NS_ATTRIBUTE_TOPIC_NAME "TOPIC_NAME"
-#define NS_ATTRIBUTE_TOPIC_SELECTION "TOPIC_STATE"
-#define NS_ATTRIBUTE_TITLE "TITLE"
-#define NS_ATTRIBUTE_TEXT "CONTENTTEXT"
-#define NS_ATTRIBUTE_SOURCE "SOURCE"
-#define NS_ATTRIBUTE_STATE "STATE"
-#define NS_ATTRIBUTE_DEVICE "DEVICE"
-#define NS_ATTRIBUTE_TYPE "TYPE"
-#define NS_ATTRIBUTE_DATETIME "DATE_TIME"
-#define NS_ATTRIBUTE_TTL "TTL"
-
 /**
  * Result code of notification service
  */
@@ -63,15 +44,16 @@ typedef enum eResult
 } NSResult;
 
 /**
- * Response code of notification service
+ * Provider state of notification consumer service
  */
-typedef enum eResponse
+typedef enum
 {
     NS_ALLOW = 1,
     NS_DENY = 2,
     NS_TOPIC = 3,
-
-} NSResponse;
+    NS_DISCOVERED = 11,
+    NS_STOPPED = 12
+} NSProviderState;
 
 /**
  * Notification message status to synchronize
@@ -81,6 +63,7 @@ typedef enum
     NS_SYNC_UNREAD = 0,
     NS_SYNC_READ = 1,
     NS_SYNC_DELETED = 2,
+
 } NSSyncType;
 
 /**
@@ -100,7 +83,7 @@ typedef enum
 } NSMessageType;
 
 /**
- *  Notification topic
+ *  Notification topic state
  */
 typedef enum
 {
@@ -109,6 +92,9 @@ typedef enum
 
 } NSTopicState;
 
+/**
+ * Topic linked list
+ */
 typedef struct _nsTopic
 {
     char * topicName;
@@ -117,16 +103,6 @@ typedef struct _nsTopic
 
 } NSTopicLL;
 
-typedef struct
-{
-    NSTopicLL * head;
-    NSTopicLL * tail;
-    //TODO: decide struct fields
-    char consumerId[NS_UUID_STRING_SIZE];
-    NSTopicLL ** topics;
-
-} NSTopicList;
-
 /**
  *  Consumer information
  */
@@ -142,7 +118,6 @@ typedef struct
 typedef struct
 {
     char providerId[NS_UUID_STRING_SIZE];
-    NSTopicLL * topicLL;
 
 } NSProvider;
 
index 798b733..42c1dcb 100644 (file)
@@ -35,17 +35,11 @@ extern "C"
 #include "NSCommon.h"
 
 /**
- * Invoked when the discovered provider is received
- * @param[in] provider  Provider who has the notification resource
- */
-typedef void (* NSProviderDiscoveredCallback)(NSProvider *);
-
-/**
  * Invoked when the provider state is changed
  * @param[in] provider  Provider which has the notification resource
- * @param[in] response  Response which has the provider state
+ * @param[in] state  Response which has the provider state
  */
-typedef void (* NSProviderChangedCallback)(NSProvider *, NSResponse);
+typedef void (* NSProviderStateCallback)(NSProvider *, NSProviderState);
 
 /**
  * Invoked when the notification message from provider is received
@@ -64,8 +58,7 @@ typedef void (* NSSyncInfoReceivedCallback)(NSSyncInfo *);
 
 typedef struct
 {
-    NSProviderDiscoveredCallback discoverCb;
-    NSProviderChangedCallback changedCb;
+    NSProviderStateCallback changedCb;
     NSMessageReceivedCallback messageCb;
     NSSyncInfoReceivedCallback syncInfoCb;
 
@@ -73,7 +66,7 @@ typedef struct
 
 /**
  * Initialize notification service for consumer
- * @param[in]  config  NSConsumerconfig structure of callback functions
+ * @param[in] config  NSConsumerconfig structure of callback functions
  * @return ::NS_OK or result code of NSResult
  */
 NSResult NSStartConsumer(NSConsumerConfig config);
@@ -86,10 +79,10 @@ NSResult NSStopConsumer();
 
 /**
  * Request to discover to remote address as parameter.
- * @param[in]  server address combined with IP address and port number using delimiter :
+ * @param[in] server address combined with IP address and port number using delimiter :
  * @return ::NS_OK or result code of NSResult
  */
-NSResult NSConsumerEnableRemoteService(char *serverAddress);
+NSResult NSConsumerEnableRemoteService(const char *serverAddress);
 
 /**
  * Request discovery manually
@@ -99,24 +92,17 @@ NSResult NSRescanProvider();
 
 /**
  * Request to subscribe notification message resource of provider
- * @param[in]  provider  Provider who send the notification message
- * @return ::NS_OK or result code of NSResult
- */
-NSResult NSSubscribe(NSProvider *provider);
-
-/**
- * Request to unsubscribe in order not to receive notification message from provider
- * @param[in]  provider  Provider who send the notification message
+ * @param[in] providerId the Id of Provider who send the notification message
  * @return ::NS_OK or result code of NSResult
  */
-NSResult NSUnsubscribe(NSProvider *provider);
+NSResult NSSubscribe(const char * providerId);
 
 /**
  * Send sync type to provider in order to synchronize notification status with other consumers
  * when consumer consumes the notification such as READ, DELETE
- * @param[in]  providerId  Provider id of the Notification message
- * @param[in]  messageId  Notification message id to synchronize the status
- * @param[in]  type  changed notification status from NSSyncType
+ * @param[in] providerId Provider id of the Notification message
+ * @param[in] messageId Notification message id to synchronize the status
+ * @param[in] type changed notification status from NSSyncType
  * @return ::NS_OK or result code of NSResult
  */
 NSResult NSConsumerSendSyncInfo(
@@ -124,31 +110,25 @@ NSResult NSConsumerSendSyncInfo(
 
 /**
  * Request NSProvider that is matched by provider id
- * @param[in]  providerId  the id of provider that user wants to get
+ * @param[in] providerId the id of provider that user wants to get
  * @return NSProvider
  */
 NSProvider * NSConsumerGetProvider(const char * providerId);
 
 /**
- * Request NSMessage that is matched by message id
- * @param[in]  messageId  the id of message that user wants to get
- * @return NSMessage
- */
-NSMessage * NSConsumerGetMessage(uint64_t messageId);
-
-/**
  * Request NSTopic list that is subscribed from provider
- * @param[in]  provider  the provider that user wants to get
+ * @param[in] providerId the Id of provider that user wants to get
  * @return NSResult
  */
-NSResult NSConsumerGetInterestTopics(NSProvider * provider);
+NSTopicLL * NSConsumerGetTopicList(const char * providerId);
 
 /**
  * Select Topic list that is wanted to subscribe from provider
- * @param[in]  provider  the provider that user wants to set
+ * @param[in] providerId the Id of provider that user wants to set
+ * @param[in] topics the topic list that user wants to set
  * @return NSResult
  */
-NSResult NSConsumerSelectInterestTopics(NSProvider * provider);
+NSResult NSConsumerUpdateTopicList(const char * providerId, NSTopicLL * topics);
 
 #ifdef __cplusplus
 }
index 5304c73..534d102 100644 (file)
@@ -62,7 +62,7 @@ typedef struct
      * if policy is true, provider decides to allow or deny for all the subscribing consumers.\r
      * Otherwise(policy is false) consumer decides to request subscription to discovered providers.\r
      */\r
-    bool policy;\r
+    bool subControllability;\r
     /* User Information */\r
     char * userInfo;\r
 \r
@@ -86,21 +86,21 @@ NSResult NSStopProvider();
  * @param[in]  server address combined with IP address and port number using delimiter :\r
  * @return ::NS_OK or result code of NSResult\r
  */\r
-NSResult NSProviderEnableRemoteService(char *serverAddress);\r
+NSResult NSProviderEnableRemoteService(char * serverAddress);\r
 \r
 /**\r
  * Request to cancel remote service using cloud server\r
  * @param[in]  server address combined with IP address and port number using delimiter :\r
  * @return ::NS_OK or result code of NSResult\r
  */\r
-NSResult NSProviderDisableRemoteService(char *serverAddress);\r
+NSResult NSProviderDisableRemoteService(char * serverAddress);\r
 \r
 /**\r
  * Send notification message to all subscribers\r
  * @param[in]  message  Notification message including id, title, contentText\r
  * @return ::NS_OK or result code of NSResult\r
  */\r
-NSResult NSSendMessage(NSMessage *msg);\r
+NSResult NSSendMessage(NSMessage * msg);\r
 \r
 /**\r
  * Send acceptance to consumer who subscribes the resource of notification message\r
@@ -108,7 +108,7 @@ NSResult NSSendMessage(NSMessage *msg);
  * @param[in]  accepted  the result of acceptance; Allow or Deny\r
  * @return ::NS_OK or result code of NSResult\r
  */\r
-NSResult NSAcceptSubscription(NSConsumer *consumer, bool accepted);\r
+NSResult NSAcceptSubscription(const char * consumerId, bool accepted);\r
 \r
 /**\r
  * Get consumer list that is stored in the cache of notification service\r
@@ -137,14 +137,14 @@ NSMessage * NSCreateMessage();
  * @param[in]  topicName Topic name to add\r
  * @return ::NS_OK or result code of NSResult\r
  */\r
-NSResult NSProviderAddTopic(char* topicName);\r
+NSResult NSProviderRegisterTopic(const char * topicName);\r
 \r
 /**\r
  * Delete topic from topic list\r
  * @param[in]  topicName Topic name to delete\r
  * @return ::NS_OK or result code of NSResult\r
  */\r
-NSResult NSProviderDeleteTopic(char* topicName);\r
+NSResult NSProviderUnregisterTopic(const char * topicName);\r
 \r
 /**\r
  * Select a topic name for a consumer\r
@@ -152,7 +152,7 @@ NSResult NSProviderDeleteTopic(char* topicName);
  * @param[in]  topicName Topic name to select\r
  * @return ::NS_OK or result code of NSResult\r
  */\r
-NSResult NSProviderSelectTopic(char* consumerId, char* topicName);\r
+NSResult NSProviderSetConsumerTopic(const char * consumerId, const char * topicName);\r
 \r
 /**\r
  * Unselect a topic from the topic list for consumer\r
@@ -160,14 +160,14 @@ NSResult NSProviderSelectTopic(char* consumerId, char* topicName);
  * @param[in]  topicName Topic name to unselect\r
  * @return ::NS_OK or result code of NSResult\r
  */\r
-NSResult NSProviderUnselectTopic(char* consumerId, char* topicName);\r
+NSResult NSProviderUnsetConsumerTopic(const char * consumerId, const char * topicName);\r
 \r
 /**\r
  * Request topic list with selection state for the consumer\r
  * @param[in] consumerid  the id of consumer which topic list is subscribed for\r
  * @return :: Topic list\r
  */\r
-NSTopicLL * NSProviderGetConsumerTopics(char *consumerId);\r
+NSTopicLL * NSProviderGetConsumerTopics(const char * consumerId);\r
 \r
 /**\r
  * Request topics list already registered by provider user\r
index a365e51..38cca0a 100644 (file)
@@ -21,6 +21,7 @@
 #ifndef _NS_CONSTANTS_H_
 #define _NS_CONSTANTS_H_
 
+#define __PRINTLOG 0
 #define __NS_FILE__ ( strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : __FILE__ )
 
 #ifdef TB_LOG
@@ -28,6 +29,7 @@
 #define NS_LOG_V(level, format, ...) (OIC_LOG_V((level), __NS_FILE__, (format), __VA_ARGS__))
 #define NS_LOG(level, msg) (OIC_LOG((level), __NS_FILE__, (msg)))
 #else
+#if (__PRINTLOG == 1)
 #include "logger.h"
 #define NS_CONVERT_LEVEL(level) ( \
         ((level) == 0) ? "DEBUG" : \
         printf((msg)); \
         printf("\n"); \
     }
+#else
+#define NS_CONVERT_LEVEL(level)
+#define NS_LOG(level, msg)
+#define NS_LOG_V(level, format, ...) NS_LOG((level), ((format), __VA_ARGS__))
+#endif
 #endif
 
 #define NS_TAG                     "IOT_NOTI"
         } \
     }
 
+#define VERSION        "1.2.0"
+
+#define NS_ATTRIBUTE_VERSION "VERSION"
+#define NS_ATTRIBUTE_POLICY "ACCEPTER"
+#define NS_ATTRIBUTE_MESSAGE "MESSAGE_URI"
+#define NS_ATTRIBUTE_SYNC "SYNC_URI"
+#define NS_ATTRIBUTE_TOPIC "TOPIC_URI"
+#define NS_ATTRIBUTE_MESSAGE_ID "MESSAGE_ID"
+#define NS_ATTRIBUTE_PROVIDER_ID "PROVIDER_ID"
+#define NS_ATTRIBUTE_CONSUMER_ID "CONSUMER_ID"
+#define NS_ATTRIBUTE_TOPIC_LIST "TOPIC_LIST"
+#define NS_ATTRIBUTE_TOPIC_NAME "TOPIC_NAME"
+#define NS_ATTRIBUTE_TOPIC_SELECTION "TOPIC_STATE"
+#define NS_ATTRIBUTE_TITLE "TITLE"
+#define NS_ATTRIBUTE_TEXT "CONTENTTEXT"
+#define NS_ATTRIBUTE_SOURCE "SOURCE"
+#define NS_ATTRIBUTE_STATE "STATE"
+#define NS_ATTRIBUTE_DEVICE "DEVICE"
+#define NS_ATTRIBUTE_TYPE "TYPE"
+#define NS_ATTRIBUTE_DATETIME "DATE_TIME"
+#define NS_ATTRIBUTE_TTL "TTL"
+#define NS_ATTRIBUTE_ICON_IMAGE "ICON_IMAGE"
 
 typedef enum eConnectionState
 {
@@ -230,7 +259,6 @@ typedef enum eTaskType
     TASK_CONSUMER_REQ_TOPIC_URI = 8299,
     TASK_CONSUMER_REQ_TOPIC_LIST = 8300,
     TASK_CONSUMER_RECV_TOPIC_LIST = 8031,
-    TASK_CONSUMER_GET_TOPIC_LIST = 8302,
     TASK_CONSUMER_SELECT_TOPIC_LIST = 8303,
 
     TASK_EVENT_CONNECTED = 9000,
@@ -245,7 +273,9 @@ typedef enum eTaskType
     TASK_DELETE_TOPIC = 11002,
     TASK_SUBSCRIBE_TOPIC = 11003,
     TASK_UNSUBSCRIBE_TOPIC = 11004,
-    TASK_POST_TOPIC = 11005
+    TASK_POST_TOPIC = 11005,
+    TASK_GET_TOPICS = 11006,
+    TAST_GET_CONSUMER_TOPICS = 11007
 
 } NSTaskType;
 
index bb5c68f..bb9a15f 100644 (file)
@@ -37,6 +37,15 @@ typedef struct _nsTask
     struct _nsTask * nextTask;\r
 } NSTask;\r
 \r
+typedef struct\r
+{\r
+    NSTopicLL * head;\r
+    NSTopicLL * tail;\r
+    char consumerId[NS_UUID_STRING_SIZE];\r
+    NSTopicLL ** topics;\r
+\r
+} NSTopicList;\r
+\r
 typedef void * NSCacheData;\r
 \r
 typedef struct _NSCacheElement\r
@@ -86,7 +95,9 @@ typedef struct
 typedef struct\r
 {\r
     OCResourceHandle handle;\r
-    int accepter;\r
+    char providerId[NS_UUID_STRING_SIZE];\r
+    char * version;\r
+    bool policy;\r
     char * message_uri;\r
     char * sync_uri;\r
 \r
@@ -108,6 +119,7 @@ typedef struct
     char * title;\r
     char * contentText;\r
     char * sourceName;\r
+    char * topicName;\r
     NSMediaContents * mediaContents;\r
 } NSMessageResource;\r
 \r
@@ -115,12 +127,14 @@ typedef struct
 {\r
     OCResourceHandle handle;\r
     char * id;\r
+    char providerId[NS_UUID_STRING_SIZE];\r
     char * state;\r
 } NSSyncResource;\r
 \r
 typedef struct\r
 {\r
     OCResourceHandle handle;\r
+    char providerId[NS_UUID_STRING_SIZE];\r
     char consumerId[NS_UUID_STRING_SIZE];\r
     NSTopicList ** TopicList;\r
 } NSTopicResource;\r
index f5af451..d00895a 100644 (file)
@@ -98,6 +98,15 @@ bool * NSGetBoneIsStartedConsumer()
 void NSSetIsStartedConsumer(bool setValue)
 {
     * NSGetBoneIsStartedConsumer() = setValue;
+
+    if (setValue == false)
+    {
+        pthread_mutex_destroy(*NSGetStackMutex());
+        *NSGetStackMutex() = NULL;
+
+        NSOICFree(*NSGetConsumerId());
+        *NSGetConsumerId() = NULL;
+    }
 }
 
 bool NSIsStartedConsumer()
@@ -105,53 +114,50 @@ bool NSIsStartedConsumer()
     return * NSGetBoneIsStartedConsumer();
 }
 
-NSProviderDiscoveredCallback * NSGetBoneDiscoverCb()
+NSProviderStateCallback * NSGetProviderChangedCb()
 {
-    static NSProviderDiscoveredCallback g_discoverCb = NULL;
+    static NSProviderStateCallback g_changedCb = NULL;
 
-    return & g_discoverCb;
+    return & g_changedCb;
 }
 
-void NSSetDiscoverProviderCb(NSProviderDiscoveredCallback cb)
+void NSSetProviderChangedCb(NSProviderStateCallback cb)
 {
-    * NSGetBoneDiscoverCb() = cb;
+    *(NSGetProviderChangedCb()) = cb;
 }
 
-NSProviderDiscoveredCallback NSGetDiscoverCb()
+typedef struct
 {
-    return * NSGetBoneDiscoverCb();
-}
+    NSProvider * provider;
+    NSProviderState state;
+} NSProviderChangedData;
 
-void * NSDiscoveredProviderFunc(void * provider)
+void * NSProviderChangedFunc(void * obj)
 {
-    NSGetDiscoverCb()((NSProvider *) provider);
-
+    NSProviderChangedData * data = (NSProviderChangedData *) obj;
+    (*(NSGetProviderChangedCb()))(data->provider, data->state);
+    NSOICFree(data);
     return NULL;
 }
 
-void NSDiscoveredProvider(NSProvider * provider)
+void NSProviderChanged(NSProvider * provider, NSProviderState response)
 {
     NS_VERIFY_NOT_NULL_V(provider);
 
-    NSConsumerThread * thread = NSThreadInit(NSDiscoveredProviderFunc, (void *) provider);
-    NS_VERIFY_NOT_NULL_V(thread);
-}
+    NSProvider * retProvider = NSCopyProvider((NSProvider_internal *) provider);
+    NS_VERIFY_NOT_NULL_V(retProvider);
 
-NSProviderChangedCallback * NSGetProviderChangedCb()
-{
-    static NSProviderChangedCallback g_changedCb = NULL;
+    NSProviderChangedData * data =
+            (NSProviderChangedData *)OICMalloc(sizeof(NSProviderChangedData));
+    NS_VERIFY_NOT_NULL_WITH_POST_CLEANING_V(data, NSRemoveProvider(retProvider));
 
-    return & g_changedCb;
-}
+    data->provider = retProvider;
+    data->state = response;
 
-void NSSetProviderChangedCb(NSProviderChangedCallback cb)
-{
-    *(NSGetProviderChangedCb()) = cb;
-}
+    NSConsumerThread * thread = NSThreadInit(NSProviderChangedFunc, (void *) data);
+    NS_VERIFY_NOT_NULL_V(thread);
 
-void NSProviderChanged(NSProvider * provider, NSResponse response)
-{
-    (*(NSGetProviderChangedCb()))(provider, response);
+    NSDestroyThreadHandle(thread);
 }
 
 NSSyncInfoReceivedCallback * NSGetBoneNotificationSyncCb()
@@ -182,6 +188,8 @@ void NSNotificationSync(NSSyncInfo * sync)
 
     NSConsumerThread * thread = NSThreadInit(NSNotificationSyncFunc, (void *) retSync);
     NS_VERIFY_NOT_NULL_V(thread);
+
+    NSDestroyThreadHandle(thread);
 }
 
 NSMessageReceivedCallback  * NSGetBoneMessagePostedCb()
@@ -216,6 +224,8 @@ void NSMessagePost(NSMessage * msg)
 
     NSConsumerThread * thread = NSThreadInit(NSMessagePostFunc, (void *) retMsg);
     NS_VERIFY_NOT_NULL_V(thread);
+
+    NSDestroyThreadHandle(thread);
 }
 
 NSTask * NSMakeTask(NSTaskType type, void * data)
@@ -250,9 +260,18 @@ NSMessage * NSCopyMessage(NSMessage * msg)
     {
         newMsg->topic = OICStrdup(msg->topic);
     }
-
-    // TODO change to copy function.
-    newMsg->mediaContents = msg->mediaContents;
+    if (msg->mediaContents)
+    {
+        newMsg->mediaContents = (NSMediaContents *)OICMalloc(sizeof(NSMediaContents));
+        NS_VERIFY_NOT_NULL_WITH_POST_CLEANING(
+                newMsg->mediaContents, NULL, NSRemoveMessage(newMsg));
+        newMsg->mediaContents->iconImage =
+                (char *)OICMalloc(sizeof(char)*strlen(msg->mediaContents->iconImage));
+        NS_VERIFY_NOT_NULL_WITH_POST_CLEANING(
+                newMsg->mediaContents->iconImage, NULL, NSRemoveMessage(newMsg));
+        memcpy(newMsg->mediaContents->iconImage, msg->mediaContents->iconImage,
+               strlen(msg->mediaContents->iconImage));
+    }
 
     return newMsg;
 }
@@ -267,7 +286,10 @@ void NSRemoveMessage(NSMessage * msg)
     NSOICFree(msg->dateTime);
     NSOICFree(msg->topic);
 
-    // TODO change to remove function.
+    if (msg->mediaContents)
+    {
+        NSOICFree(msg->mediaContents->iconImage);
+    }
     NSOICFree(msg->mediaContents);
 
     NSOICFree(msg);
@@ -398,7 +420,7 @@ void NSRemoveTopicLL(NSTopicLL * topicHead)
 
     while (iter)
     {
-        following = (NSTopicLL *) iter->next;
+        following = iter->next;
 
         NSRemoveTopicNode(iter);
 
@@ -425,7 +447,8 @@ NSTopicLL * NSCopyTopicLL(NSTopicLL * topicHead)
         NS_VERIFY_NOT_NULL_WITH_POST_CLEANING(newTopicNode, NULL, NSRemoveTopicLL(newTopicHead));
 
         NSResult ret = NSInsertTopicNode(newTopicHead, newTopicNode);
-        NS_VERIFY_STACK_SUCCESS_WITH_POST_CLEANING(ret, NULL, NSRemoveTopicLL(newTopicHead));
+        NS_VERIFY_NOT_NULL_WITH_POST_CLEANING(ret == NS_OK ? (void *)1 : NULL,
+                                                    NULL, NSRemoveTopicLL(newTopicHead));
 
         iter = (NSTopicLL *) iter->next;
     }
@@ -467,6 +490,7 @@ NSProvider_internal * NSCopyProvider_internal(NSProvider_internal * prov)
     newProv->syncUri = OICStrdup(prov->syncUri);
     newProv->topicUri = OICStrdup(prov->topicUri);
     newProv->accessPolicy = prov->accessPolicy;
+    newProv->state = prov->state;
 
     return newProv;
 }
@@ -478,16 +502,6 @@ NSProvider * NSCopyProvider(NSProvider_internal * prov)
     NSProvider * newProv = (NSProvider *) OICMalloc(sizeof(NSProvider));
     NS_VERIFY_NOT_NULL(newProv, NULL);
 
-    newProv->topicLL = NULL;
-
-    if (prov->topicLL)
-    {
-        NSTopicLL * topicList = NSCopyTopicLL(prov->topicLL);
-        NS_VERIFY_NOT_NULL_WITH_POST_CLEANING(topicList, NULL, NSRemoveProvider(newProv));
-
-        newProv->topicLL = topicList;
-    }
-
     OICStrcpy(newProv->providerId, NS_DEVICE_ID_LENGTH, prov->providerId);
 
     return newProv;
@@ -512,42 +526,9 @@ void NSRemoveProvider_internal(NSProvider_internal * prov)
 void NSRemoveProvider(NSProvider * prov)
 {
     NS_VERIFY_NOT_NULL_V(prov);
-
-    if (prov->topicLL)
-    {
-        NSRemoveTopicLL(prov->topicLL);
-    }
-
     NSOICFree(prov);
 }
 
-NSSyncInfo_internal * NSCopySyncInfo(NSSyncInfo_internal * syncInfo)
-{
-    NS_VERIFY_NOT_NULL(syncInfo, NULL);
-
-    NSProviderConnectionInfo * connections = NSCopyProviderConnections(syncInfo->connection);
-    NS_VERIFY_NOT_NULL(connections, NULL);
-
-    NSSyncInfo_internal * newSyncInfo = (NSSyncInfo_internal *)OICMalloc(sizeof(NSSyncInfo_internal));
-    NS_VERIFY_NOT_NULL_WITH_POST_CLEANING(newSyncInfo, NULL, NSRemoveConnections(connections));
-
-    OICStrcpy(newSyncInfo->providerId, sizeof(char) * NS_DEVICE_ID_LENGTH, syncInfo->providerId);
-    newSyncInfo->messageId = syncInfo->messageId;
-    newSyncInfo->state = syncInfo->state;
-    newSyncInfo->connection = connections;
-
-    return newSyncInfo;
-}
-
-void NSRemoveSyncInfo(NSSyncInfo_internal * syncInfo)
-{
-    NS_VERIFY_NOT_NULL_V(syncInfo);
-
-    NSRemoveConnections(syncInfo->connection);
-
-    NSOICFree(syncInfo);
-}
-
 OCStackResult NSInvokeRequest(OCDoHandle * handle,
         OCMethod method, const OCDevAddr * addr,
         const char * queryUrl, OCPayload * payload,
index 9c02e8d..417e6a0 100644 (file)
@@ -81,6 +81,7 @@ typedef struct
     char * topicUri;
 
     NSSelector accessPolicy;
+    NSProviderState state;
 
     NSProviderConnectionInfo * connection;
 
@@ -96,21 +97,11 @@ typedef struct
 
 } NSSyncInfo_internal;
 
-typedef struct
-{
-    NSSyncType status;
-    NSMessage * msg;
-
-} NSStoreMessage;
-
 bool NSIsStartedConsumer();
 void NSSetIsStartedConsumer(bool setValue);
 
-void NSSetDiscoverProviderCb(NSProviderDiscoveredCallback cb);
-void NSDiscoveredProvider(NSProvider * provider);
-
-void NSSetProviderChangedCb(NSProviderChangedCallback cb);
-void NSProviderChanged(NSProvider * provider, NSResponse response);
+void NSSetProviderChangedCb(NSProviderStateCallback cb);
+void NSProviderChanged(NSProvider * provider, NSProviderState response);
 
 void NSSetMessagePostedCb(NSMessageReceivedCallback  cb);
 void NSMessagePost(NSMessage * obj);
@@ -139,9 +130,6 @@ NSProvider * NSCopyProvider(NSProvider_internal *);
 void NSRemoveProvider_internal(NSProvider_internal *);
 void NSRemoveProvider(NSProvider *);
 
-NSSyncInfo_internal * NSCopySyncInfo(NSSyncInfo_internal *);
-void NSRemoveSyncInfo(NSSyncInfo_internal *);
-
 NSTopicLL * NSCopyTopicNode(NSTopicLL *);
 void NSRemoveTopicNode(NSTopicLL *);
 NSResult NSInsertTopicNode(NSTopicLL *, NSTopicLL *);
index f9ca253..7d5fa6c 100644 (file)
@@ -29,8 +29,6 @@
 
 #define NS_SYNC_URI "/notification/sync"
 
-static unsigned long NS_MESSAGE_ACCEPTANCE = 1;
-
 NSMessage * NSCreateMessage_internal(uint64_t msgId, const char * providerId);
 NSSyncInfo * NSCreateSyncInfo_consumer(uint64_t msgId, const char * providerId, NSSyncType state);
 
@@ -191,7 +189,7 @@ OCStackApplicationResult NSConsumerMessageListener(
 
     NSTaskType type = TASK_CONSUMER_RECV_MESSAGE;
 
-    if (newNoti->messageId == NS_MESSAGE_ACCEPTANCE || newNoti->messageId == NS_DENY)
+    if (newNoti->messageId == NS_ALLOW || newNoti->messageId == NS_DENY)
     {
         NS_LOG(DEBUG, "Receive subscribe result");
         type = TASK_CONSUMER_RECV_PROVIDER_CHANGED;
@@ -252,6 +250,23 @@ NSMessage * NSGetMessage(OCClientResponse * clientResponse)
     OCRepPayloadGetPropString(payload, NS_ATTRIBUTE_DATETIME, &retMsg->dateTime);
     OCRepPayloadGetPropInt(payload, NS_ATTRIBUTE_TTL, (int64_t *)&retMsg->ttl);
 
+    char * icon = NULL;
+    OCRepPayloadGetPropString(payload, NS_ATTRIBUTE_ICON_IMAGE, &icon);
+
+    if (icon)
+    {
+        NSMediaContents * contents = (NSMediaContents *)OICMalloc(sizeof(NSMediaContents));
+        if (contents)
+        {
+            contents->iconImage = icon;
+            retMsg->mediaContents = contents;
+        }
+        else
+        {
+            NSOICFree(icon);
+        }
+    }
+
     NS_LOG_V(DEBUG, "Msg ID      : %lld", (long long int)retMsg->messageId);
     NS_LOG_V(DEBUG, "Msg Title   : %s", retMsg->title);
     NS_LOG_V(DEBUG, "Msg Content : %s", retMsg->contentText);
@@ -362,11 +377,11 @@ OCStackResult NSSendSyncInfo(NSSyncInfo * syncInfo, OCDevAddr * addr)
 
 char * NSGetCloudUri(const char * providerId, char * uri)
 {
-    size_t uriLen = NS_DEVICE_ID_LENGTH + 1 + strlen(uri) + 1;
+    size_t uriLen = NS_DEVICE_ID_LENGTH + 1 + strlen(uri) + 1 + 3;
     char * retUri = (char *)OICMalloc(uriLen);
     NS_VERIFY_NOT_NULL_WITH_POST_CLEANING(retUri, NULL, NSOICFree(uri));
 
-    snprintf(retUri, uriLen, "/%s%s", providerId, uri);
+    snprintf(retUri, uriLen, "/di/%s%s", providerId, uri);
     NSOICFree(uri);
     NS_LOG_V(DEBUG, "Cloud uri : %s", retUri);
 
@@ -429,8 +444,7 @@ void NSConsumerCommunicationTaskProcessing(NSTask * task)
             connections = connections->next;
         }
     }
-    else if (task->taskType == TASK_CONSUMER_REQ_TOPIC_LIST
-                || task->taskType == TASK_CONSUMER_GET_TOPIC_LIST)
+    else if (task->taskType == TASK_CONSUMER_REQ_TOPIC_LIST)
     {
         NSProvider_internal * provider = (NSProvider_internal *)task->taskData;
 
@@ -438,6 +452,7 @@ void NSConsumerCommunicationTaskProcessing(NSTask * task)
         NS_VERIFY_NOT_NULL_V(connections);
 
         char * topicUri = OICStrdup(provider->topicUri);
+        NS_VERIFY_NOT_NULL_V(topicUri);
 
         OCConnectivityType type = CT_DEFAULT;
         if (connections->addr->adapter == OC_ADAPTER_TCP)
@@ -450,15 +465,8 @@ void NSConsumerCommunicationTaskProcessing(NSTask * task)
         }
 
         NS_LOG(DEBUG, "get topic query");
-        char * query = NULL;
-        if (task->taskType == TASK_CONSUMER_REQ_TOPIC_LIST)
-        {
-            query = OICStrdup(topicUri);
-        }
-        else if (task->taskType == TASK_CONSUMER_GET_TOPIC_LIST)
-        {
-            query = NSMakeRequestUriWithConsumerId(topicUri);
-        }
+        char * query = NSMakeRequestUriWithConsumerId(topicUri);
+
         NS_VERIFY_NOT_NULL_V(query);
         NS_LOG_V(DEBUG, "topic query : %s", query);
 
@@ -526,6 +534,7 @@ void NSConsumerCommunicationTaskProcessing(NSTask * task)
         }
 
         char * topicUri = OICStrdup(provider->topicUri);
+        NS_VERIFY_NOT_NULL_V(topicUri);
 
         OCConnectivityType type = CT_DEFAULT;
         if (connections->addr->adapter == OC_ADAPTER_TCP)
@@ -630,7 +639,8 @@ NSTopicLL * NSGetTopicLL(OCClientResponse * clientResponse)
         }
 
         NSResult ret = NSInsertTopicNode(topicLL, topicNode);
-        NS_VERIFY_STACK_SUCCESS_WITH_POST_CLEANING(ret, NULL, NSRemoveTopicLL(topicLL));
+        NS_VERIFY_NOT_NULL_WITH_POST_CLEANING(ret == NS_OK ? (void *)1 : NULL,
+                                                    NULL, NSRemoveTopicLL(topicLL));
     }
 
     return topicLL;
index 52bf446..44c6a19 100644 (file)
@@ -43,6 +43,7 @@ OCStackApplicationResult NSConsumerPresenceListener(
     (void) handle;
 
     NS_VERIFY_NOT_NULL(clientResponse, OC_STACK_KEEP_TRANSACTION);
+    NS_VERIFY_NOT_NULL(clientResponse->payload, OC_STACK_KEEP_TRANSACTION);
     NS_VERIFY_STACK_SUCCESS(
             NSOCResultToSuccess(clientResponse->result), OC_STACK_KEEP_TRANSACTION);
 
@@ -111,6 +112,8 @@ OCStackApplicationResult NSProviderDiscoverListener(
     }
 
     OCResourcePayload * resource = ((OCDiscoveryPayload *)clientResponse->payload)->resources;
+    NS_LOG_V(DEBUG, "Discovered resource uri : %s",
+                        resource->uri);
     while (resource)
     {
         NS_VERIFY_NOT_NULL(resource->uri, OC_STACK_KEEP_TRANSACTION);
@@ -158,10 +161,9 @@ OCStackApplicationResult NSIntrospectProvider(
 
     NSProvider_internal * newProvider = NSGetProvider(clientResponse);
     NS_VERIFY_NOT_NULL(newProvider, OC_STACK_KEEP_TRANSACTION);
-    if (ctx && *((NSConsumerDiscoverType *)ctx) == NS_DISCOVER_CLOUD )
+    if (ctx && ctx == (void *)NS_DISCOVER_CLOUD )
     {
         newProvider->connection->isCloudConnection = true;
-        NSOICFree(ctx);
     }
 
     NS_LOG(DEBUG, "build NSTask");
@@ -188,10 +190,17 @@ NSProvider_internal * NSGetProvider(OCClientResponse * clientResponse)
     NS_LOG(DEBUG, "create NSProvider");
     NS_VERIFY_NOT_NULL(clientResponse->payload, NULL);
 
+    OCRepPayloadPropType accepterType = OCREP_PROP_BOOL;
+
     OCRepPayload * payload = (OCRepPayload *)clientResponse->payload;
     while (payload)
     {
         NS_LOG_V(DEBUG, "Payload Key : %s", payload->values->name);
+        NS_LOG_V(DEBUG, "Payload Type : %d", (int) payload->values->type);
+        if (!strcmp(payload->values->name, NS_ATTRIBUTE_POLICY))
+        {
+            accepterType = payload->values->type;
+        }
         payload = payload->next;
     }
 
@@ -201,11 +210,20 @@ NSProvider_internal * NSGetProvider(OCClientResponse * clientResponse)
     char * messageUri = NULL;
     char * syncUri = NULL;
     char * topicUri = NULL;
-    int64_t accepter = 0;
+    bool bAccepter = 0;
+    int64_t iAccepter = 0;
     NSProviderConnectionInfo * connection = NULL;
 
     NS_LOG(DEBUG, "get information of accepter");
-    bool getResult = OCRepPayloadGetPropInt(payload, NS_ATTRIBUTE_POLICY, & accepter);
+    bool getResult = false;
+    if (accepterType == OCREP_PROP_BOOL)
+    {
+        getResult = OCRepPayloadGetPropBool(payload, NS_ATTRIBUTE_POLICY, & bAccepter);
+    }
+    else if (accepterType == OCREP_PROP_INT)
+    {
+        getResult = OCRepPayloadGetPropInt(payload, NS_ATTRIBUTE_POLICY, & iAccepter);
+    }
     NS_VERIFY_NOT_NULL(getResult == true ? (void *) 1 : NULL, NULL);
 
     NS_LOG(DEBUG, "get provider ID");
@@ -244,9 +262,18 @@ NSProvider_internal * NSGetProvider(OCClientResponse * clientResponse)
     {
         newProvider->topicUri = topicUri;
     }
-    newProvider->accessPolicy = (NSSelector)accepter;
+    if (accepterType == OCREP_PROP_BOOL)
+    {
+        newProvider->accessPolicy = (NSSelector)bAccepter;
+    }
+    else if (accepterType == OCREP_PROP_INT)
+    {
+        newProvider->accessPolicy = (NSSelector)iAccepter;
+    }
+
     newProvider->connection = connection;
     newProvider->topicLL = NULL;
+    newProvider->state = NS_DISCOVERED;
 
     return newProvider;
 }
@@ -272,7 +299,7 @@ OCDevAddr * NSChangeAddress(const char * address)
     }
 
     int tmp = index + 1;
-    uint16_t port = address[tmp++];
+    uint16_t port = address[tmp++] - '0';
 
     while(address[tmp] != '\0')
     {
@@ -284,23 +311,28 @@ OCDevAddr * NSChangeAddress(const char * address)
     NS_VERIFY_NOT_NULL(retAddr, NULL);
 
     retAddr->adapter = OC_ADAPTER_TCP;
-    OICStrcpy(retAddr->addr, index - 1, address);
+    OICStrcpy(retAddr->addr, index + 1, address);
     retAddr->addr[index] = '\0';
     retAddr->port = port;
+    retAddr->flags = OC_IP_USE_V6;
+
+    NS_LOG(DEBUG, "Change Address for TCP request");
+    NS_LOG_V(DEBUG, "Origin : %s", address);
+    NS_LOG_V(DEBUG, "Changed Addr : %s", retAddr->addr);
+    NS_LOG_V(DEBUG, "Changed Port : %d", retAddr->port);
 
     return retAddr;
 }
 
 void NSConsumerHandleRequestDiscover(OCDevAddr * address, NSConsumerDiscoverType rType)
 {
-    OCConnectivityType type = CT_DEFAULT;
+    OCConnectivityType type = CT_ADAPTER_IP;
     NSConsumerDiscoverType * callbackData = NULL;
 
     if (address)
     {
         if (address->adapter == OC_ADAPTER_IP)
         {
-            type = CT_ADAPTER_IP;
             NS_LOG(DEBUG, "Request discover [UDP]");
         }
         else if (address->adapter == OC_ADAPTER_TCP)
@@ -313,8 +345,7 @@ void NSConsumerHandleRequestDiscover(OCDevAddr * address, NSConsumerDiscoverType
 
             if (rType == NS_DISCOVER_CLOUD)
             {
-                callbackData = (NSConsumerDiscoverType *)OICMalloc(sizeof(NSConsumerDiscoverType));
-                *callbackData = NS_DISCOVER_CLOUD;
+                callbackData = (void *) NS_DISCOVER_CLOUD;
             }
         }
         else
index ef1b94e..db95e81 100644 (file)
@@ -36,12 +36,10 @@ NSResult NSStartConsumer(NSConsumerConfig config)
     bool isStartedConsumer = NSIsStartedConsumer();
     NS_VERIFY_NOT_NULL(isStartedConsumer == false ? (void *) 1 : NULL, NS_OK);
 
-    NS_VERIFY_NOT_NULL(config.discoverCb, NS_ERROR);
     NS_VERIFY_NOT_NULL(config.messageCb, NS_ERROR);
     NS_VERIFY_NOT_NULL(config.syncInfoCb, NS_ERROR);
     NS_VERIFY_NOT_NULL(config.changedCb, NS_ERROR);
 
-    NSSetDiscoverProviderCb(config.discoverCb);
     NSSetMessagePostedCb(config.messageCb);
     NSSetNotificationSyncCb(config.syncInfoCb);
     NSSetProviderChangedCb(config.changedCb);
@@ -59,7 +57,6 @@ NSResult NSStopConsumer()
     bool isStartedConsumer = NSIsStartedConsumer();
     NS_VERIFY_NOT_NULL(isStartedConsumer == true ? (void *) 1 : NULL, NS_ERROR);
 
-    NSSetDiscoverProviderCb(NULL);
     NSSetMessagePostedCb(NULL);
     NSSetNotificationSyncCb(NULL);
     NSSetProviderChangedCb(NULL);
@@ -70,12 +67,25 @@ NSResult NSStopConsumer()
     return NS_OK;
 }
 
-NSResult NSConsumerEnableRemoteService(char *serverAddress)
+NSResult NSConsumerEnableRemoteService(const char *serverAddress)
 {
+    NS_VERIFY_NOT_NULL(serverAddress, NS_ERROR);
     bool isStartedConsumer = NSIsStartedConsumer();
     NS_VERIFY_NOT_NULL(isStartedConsumer == true ? (void *) 1 : NULL, NS_ERROR);
 
-    char * queryAddr = OICStrdup(serverAddress);
+    char * queryAddr = NULL;
+    if (strstr(serverAddress, "coap+tcp://"))
+    {
+        queryAddr = OICStrdup(serverAddress+11);
+    }
+    else if (strstr(serverAddress, "coap://"))
+    {
+        queryAddr = OICStrdup(serverAddress+7);
+    }
+    else
+    {
+        queryAddr = OICStrdup(serverAddress);
+    }
     NS_VERIFY_NOT_NULL(queryAddr, NS_ERROR);
 
     NSTask * discoverTask = NSMakeTask(TASK_CONSUMER_REQ_DISCOVER, (void *)queryAddr);
@@ -84,12 +94,17 @@ NSResult NSConsumerEnableRemoteService(char *serverAddress)
     return NSConsumerPushEvent(discoverTask);
 }
 
-NSResult NSSubscribe(NSProvider * provider)
+NSResult NSSubscribe(const char * providerId)
 {
+    NS_VERIFY_NOT_NULL(providerId, NS_ERROR);
     bool isStartedConsumer = NSIsStartedConsumer();
     NS_VERIFY_NOT_NULL(isStartedConsumer == true ? (void *) 1 : NULL, NS_ERROR);
 
-    NSProvider * prov = (NSProvider *)NSCopyProvider((NSProvider_internal *) provider);
+    NSProvider_internal * provInternal = NSConsumerFindNSProvider(providerId);
+    NS_VERIFY_NOT_NULL(provInternal, NS_ERROR);
+
+    NSProvider * prov = (NSProvider *)NSCopyProvider(provInternal);
+    NSRemoveProvider_internal(provInternal);
     NS_VERIFY_NOT_NULL(prov, NS_ERROR);
 
     NSTask * subscribeTask = NSMakeTask(TASK_CONSUMER_REQ_SUBSCRIBE, (void *) prov);
@@ -98,12 +113,17 @@ NSResult NSSubscribe(NSProvider * provider)
     return NSConsumerPushEvent(subscribeTask);
 }
 
-NSResult NSUnsubscribe(NSProvider * provider)
+NSResult NSUnsubscribe(const char * providerId)
 {
+    NS_VERIFY_NOT_NULL(providerId, NS_ERROR);
     bool isStartedConsumer = NSIsStartedConsumer();
     NS_VERIFY_NOT_NULL(isStartedConsumer == true ? (void *) 1 : NULL, NS_ERROR);
 
-    NSProvider * prov = (NSProvider *)NSCopyProvider((NSProvider_internal *) provider);
+    NSProvider_internal * provInternal = NSConsumerFindNSProvider(providerId);
+    NS_VERIFY_NOT_NULL(provInternal, NS_ERROR);
+
+    NSProvider * prov = (NSProvider *)NSCopyProvider((NSProvider_internal *) provInternal);
+    NSRemoveProvider_internal(provInternal);
     NS_VERIFY_NOT_NULL(prov, NS_ERROR);
 
     NSTask * unsubscribeTask = NSMakeTask(TASK_CONSUMER_REQ_SUBSCRIBE_CANCEL, (void *) prov);
@@ -114,6 +134,7 @@ NSResult NSUnsubscribe(NSProvider * provider)
 
 NSResult NSConsumerSendSyncInfo(const char * providerId, uint64_t messageId, NSSyncType type)
 {
+    NS_VERIFY_NOT_NULL(providerId, NS_ERROR);
     bool isStartedConsumer = NSIsStartedConsumer();
     NS_VERIFY_NOT_NULL(isStartedConsumer == true ? (void *) 1 : NULL, NS_ERROR);
 
@@ -143,6 +164,7 @@ NSResult NSRescanProvider()
 
 NSProvider * NSConsumerGetProvider(const char * providerId)
 {
+    NS_VERIFY_NOT_NULL(providerId, NULL);
     bool isStartedConsumer = NSIsStartedConsumer();
     NS_VERIFY_NOT_NULL(isStartedConsumer == true ? (void *) 1 : NULL, NULL);
 
@@ -158,73 +180,45 @@ NSProvider * NSConsumerGetProvider(const char * providerId)
     return retProv;
 }
 
-NSMessage * NSConsumerGetMessage(uint64_t messageId)
+NSTopicLL * NSConsumerGetTopicList(const char * providerId)
 {
+    NS_VERIFY_NOT_NULL(providerId, NULL);
     bool isStartedConsumer = NSIsStartedConsumer();
     NS_VERIFY_NOT_NULL(isStartedConsumer == true ? (void *) 1 : NULL, NULL);
 
-    char msgId[NS_DEVICE_ID_LENGTH] = { 0, };
-    snprintf(msgId, NS_DEVICE_ID_LENGTH, "%lld", (long long int)messageId);
-
-    return (NSMessage *) NSConsumerFindNSMessage(msgId);
-}
-
-NSResult NSConsumerGetInterestTopics(NSProvider * provider)
-{
-    bool isStartedConsumer = NSIsStartedConsumer();
-    NS_VERIFY_NOT_NULL(isStartedConsumer == true ? (void *) 1 : NULL, NS_ERROR);
-
-    NS_VERIFY_NOT_NULL(provider, NS_ERROR);
-
-    NS_LOG_V(DEBUG, "NSProvider ID: %s", provider->providerId);
-    NSProvider_internal * prov = NSConsumerFindNSProvider(provider->providerId);
-    NS_VERIFY_NOT_NULL(prov, NS_ERROR);
-    NSSelector selector = prov->accessPolicy;
-    NSRemoveProvider_internal(prov);
-    NS_VERIFY_NOT_NULL(selector == NS_SELECTION_CONSUMER ? (void *) 1 : NULL, NS_ERROR);
-
-    prov = (NSProvider *)NSCopyProvider((NSProvider_internal *) provider);
-    NS_VERIFY_NOT_NULL(prov, NS_ERROR);
+    NS_LOG_V(DEBUG, "NSProvider ID: %s", providerId);
+    NSProvider_internal * prov_internal = NSConsumerFindNSProvider(providerId);
+    NS_VERIFY_NOT_NULL(prov_internal, NULL);
 
-    NSTask * topicTask = NSMakeTask(TASK_CONSUMER_GET_TOPIC_LIST, (void *) prov);
-    NS_VERIFY_NOT_NULL(topicTask, NS_ERROR);
+    NSTopicLL * retTopics = prov_internal->topicLL;
+    prov_internal->topicLL = NULL;
+    NSRemoveProvider_internal(prov_internal);
 
-    return NSConsumerPushEvent(topicTask);
+    return retTopics;
 }
 
-NSResult NSConsumerSelectInterestTopics(NSProvider * provider)
+NSResult NSConsumerUpdateTopicList(const char * providerId, NSTopicLL * topics)
 {
+    NS_VERIFY_NOT_NULL(providerId, NS_ERROR);
+    NS_VERIFY_NOT_NULL(topics, NS_ERROR);
     bool isStartedConsumer = NSIsStartedConsumer();
     NS_VERIFY_NOT_NULL(isStartedConsumer == true ? (void *) 1 : NULL, NS_ERROR);
 
-    NS_VERIFY_NOT_NULL(provider, NS_ERROR);
-    NS_VERIFY_NOT_NULL(provider->topicLL, NS_ERROR);
+    NSProvider_internal * prov_internal = NSConsumerFindNSProvider(providerId);
+    NS_VERIFY_NOT_NULL(prov_internal, NS_ERROR);
+    NS_VERIFY_NOT_NULL_WITH_POST_CLEANING(prov_internal->topicLL, NS_ERROR,
+                         NSRemoveProvider_internal(prov_internal));
 
-    NSProvider_internal * prov = NSConsumerFindNSProvider(provider->providerId);
-    NS_VERIFY_NOT_NULL(prov, NS_ERROR);
-
-    NSSelector selector = prov->accessPolicy;
-    NSRemoveProvider_internal(prov);
-    NS_VERIFY_NOT_NULL(selector == NS_SELECTION_CONSUMER ? (void *) 1 : NULL, NS_ERROR);
+    NSSelector selector = prov_internal->accessPolicy;
+    NS_VERIFY_NOT_NULL_WITH_POST_CLEANING(
+            selector == NS_SELECTION_CONSUMER ? (void *) 1 : NULL, NS_ERROR,
+            NSRemoveProvider_internal(prov_internal));
 
-    prov = (NSProvider *)NSCopyProvider((NSProvider_internal *) provider);
-    NS_VERIFY_NOT_NULL(prov, NS_ERROR);
+    NSRemoveTopicLL(prov_internal->topicLL);
+    prov_internal->topicLL = NSCopyTopicLL(topics);
 
-    NSTask * topicTask = NSMakeTask(TASK_CONSUMER_SELECT_TOPIC_LIST, (void *) prov);
+    NSTask * topicTask = NSMakeTask(TASK_CONSUMER_SELECT_TOPIC_LIST, (void *) prov_internal);
     NS_VERIFY_NOT_NULL(topicTask, NS_ERROR);
 
     return NSConsumerPushEvent(topicTask);
 }
-
-NSResult NSDropNSMessage(NSMessage * obj)
-{
-    NS_VERIFY_NOT_NULL(obj, NS_ERROR);
-
-    obj->messageId = 0;
-    NSOICFree(obj->title);
-    NSOICFree(obj->contentText);
-    NSOICFree(obj->sourceName);
-    NSOICFree(obj);
-
-    return NS_OK;
-}
index f05016c..1bb3afb 100644 (file)
 #include "oic_malloc.h"
 #include "oic_string.h"
 
-NSCacheList ** NSGetMessageCacheList()
+#define NS_RESERVED_MESSAGEID 10
+
+// MessageState storage structure
+typedef struct _NSMessageStateLL
 {
-    static NSCacheList * messageCache = NULL;
-    return & messageCache;
-}
+    uint64_t messageId;
+    NSSyncType state;
+    struct _NSMessageStateLL * next;
+
+} NSMessageStateLL;
 
-void NSSetMessageCacheList(NSCacheList * cache)
+typedef struct
 {
-    *(NSGetMessageCacheList()) = cache;
-}
+    NSMessageStateLL * head;
+    NSMessageStateLL * tail;
+
+} NSMessageStateList;
+
+// Mutex of MessageState storage
+pthread_mutex_t ** NSGetMessageListMutex();
+void NSLockMessageListMutex();
+void NSUnlockMessageListMutex();
+
+// Function for MessageState
+NSMessageStateList * NSGetMessageStateList();
+NSMessageStateLL * NSFindMessageState(uint64_t msgId);
+bool NSUpdateMessageState(uint64_t msgId, NSSyncType state);
+bool NSDeleteMessageState(uint64_t msgId);
+bool NSInsertMessageState(uint64_t msgId, NSSyncType state);
+void NSDestroyMessageStateList();
 
 NSCacheList ** NSGetProviderCacheList()
 {
@@ -48,18 +68,7 @@ void NSSetProviderCacheList(NSCacheList * cache)
     *(NSGetProviderCacheList()) = cache;
 }
 
-void NSDestroyMessageCacheList()
-{
-    NSCacheList * cache = *(NSGetMessageCacheList());
-    if (cache)
-    {
-        NSStorageDestroy(cache);
-    }
-
-    NSSetMessageCacheList(NULL);
-}
-
-void NSDestroyProviderCacheList()
+void NSDestroyInternalCachedList()
 {
     NSCacheList * cache = *(NSGetProviderCacheList());
     if (cache)
@@ -68,27 +77,10 @@ void NSDestroyProviderCacheList()
     }
 
     NSSetProviderCacheList(NULL);
-}
-
-NSMessage * NSMessageCacheFind(const char * messageId)
-{
-    NS_VERIFY_NOT_NULL(messageId, NULL);
-
-    NSCacheList * MessageCache = *(NSGetMessageCacheList());
-    if (!MessageCache)
-    {
-        NS_LOG(DEBUG, "Message Cache Init");
-        MessageCache = NSStorageCreate();
-        NS_VERIFY_NOT_NULL(MessageCache, NULL);
-
-        MessageCache->cacheType = NS_CONSUMER_CACHE_MESSAGE;
-        NSSetMessageCacheList(MessageCache);
-    }
-
-    NSCacheElement * cacheElement = NSStorageRead(MessageCache, messageId);
-    NS_VERIFY_NOT_NULL(cacheElement, NULL);
 
-    return NSCopyMessage(((NSStoreMessage *) cacheElement->data)->msg);
+    NSDestroyMessageStateList();
+    pthread_mutex_destroy(*NSGetMessageListMutex());
+    *NSGetMessageListMutex() = NULL;
 }
 
 NSProvider_internal * NSProviderCacheFind(const char * providerId)
@@ -131,51 +123,6 @@ NSProvider_internal * NSFindProviderFromAddr(OCDevAddr * addr)
     return NSCopyProvider_internal((NSProvider_internal *) cacheElement->data);
 }
 
-void NSRemoveCacheElementMessage(NSCacheElement * obj)
-{
-    NSRemoveMessage(((NSStoreMessage *)obj->data)->msg);
-    NSOICFree(obj->data);
-    NSOICFree(obj);
-}
-
-NSResult NSMessageCacheUpdate(NSMessage * msg, NSSyncType type)
-{
-    NS_VERIFY_NOT_NULL(msg, NS_ERROR);
-
-    NSCacheList * MessageCache = *(NSGetMessageCacheList());
-    if (!MessageCache)
-    {
-        NS_LOG(DEBUG, "Message Cache Init");
-        MessageCache = NSStorageCreate();
-        NS_VERIFY_NOT_NULL(MessageCache, NS_ERROR);
-
-        MessageCache->cacheType = NS_CONSUMER_CACHE_MESSAGE;
-        NSSetMessageCacheList(MessageCache);
-    }
-
-    NSStoreMessage * sMsg = (NSStoreMessage *)OICMalloc(sizeof(NSStoreMessage));
-    NS_VERIFY_NOT_NULL(sMsg, NS_ERROR);
-
-    NSCacheElement * obj = (NSCacheElement *)OICMalloc(sizeof(NSCacheElement));
-    NS_VERIFY_NOT_NULL_WITH_POST_CLEANING(obj, NS_ERROR, NSOICFree(sMsg));
-
-    sMsg->status = type;
-    sMsg->msg = NSCopyMessage(msg);
-
-    obj->data = (NSCacheData *) sMsg;
-    obj->next = NULL;
-
-    NS_LOG(DEBUG, "try to write to storage");
-    NSResult ret = NSStorageWrite(MessageCache, obj);
-    NS_VERIFY_NOT_NULL_WITH_POST_CLEANING(ret == NS_OK ? (void *) 1 : NULL,
-            NS_ERROR, NSRemoveCacheElementMessage(obj));
-
-    NSRemoveCacheElementMessage(obj);
-
-    NS_LOG(DEBUG, "Update message done");
-    return NS_OK;
-}
-
 NSResult NSProviderCacheUpdate(NSProvider_internal * provider)
 {
     NSCacheList * ProviderCache = *(NSGetProviderCacheList());
@@ -222,7 +169,11 @@ void NSCancelAllSubscription()
     while ((obj = NSPopProviderCacheList(ProviderCache)))
     {
         NS_LOG(DEBUG, "build NSTask");
-        NSTask * task = NSMakeTask(TASK_CONSUMER_REQ_SUBSCRIBE_CANCEL, (void *) obj->data);
+        NSProvider * prov = NSCopyProvider((NSProvider_internal *) obj->data);
+        NS_VERIFY_NOT_NULL_WITH_POST_CLEANING_V(prov,
+                    NSRemoveProvider_internal((NSProvider_internal *) obj->data));
+
+        NSTask * task = NSMakeTask(TASK_CONSUMER_REQ_SUBSCRIBE_CANCEL, prov);
         NS_VERIFY_NOT_NULL_V(task);
 
         NSConsumerPushEvent(task);
@@ -238,9 +189,29 @@ void NSConsumerHandleProviderDiscovered(NSProvider_internal * provider)
 
     NSProvider_internal * providerCacheDataFromAddr
         = NSFindProviderFromAddr(provider->connection->addr);
-    NS_VERIFY_NOT_NULL_WITH_POST_CLEANING_V(
-        (providerCacheDataFromAddr == NULL) ? (void *)1 : NULL,
-        NSRemoveProvider_internal(providerCacheDataFromAddr));
+
+    if (providerCacheDataFromAddr)
+    {
+        if (!strcmp(providerCacheDataFromAddr->providerId, provider->providerId))
+        {
+            NSProviderConnectionInfo * infos = providerCacheDataFromAddr->connection;
+            while (infos)
+            {
+                isSubscribing |= infos->isSubscribing;
+                infos = infos->next;
+            }
+
+            if (isSubscribing == false)
+            {
+                NSProvider * providerForCb = NSCopyProvider(providerCacheDataFromAddr);
+                NSProviderChanged(providerForCb, NS_DISCOVERED);
+                NSRemoveProvider(providerForCb);
+            }
+            NSRemoveProvider_internal(providerCacheDataFromAddr);
+            return ;
+        }
+        NSRemoveProvider_internal(providerCacheDataFromAddr);
+    }
 
     NSProvider_internal * providerCacheData = NSProviderCacheFind(provider->providerId);
 
@@ -284,7 +255,8 @@ void NSConsumerHandleProviderDiscovered(NSProvider_internal * provider)
     {
         NS_LOG(DEBUG, "accepter is NS_ACCEPTER_CONSUMER, Callback to user");
         NSProvider * providerForCb = NSCopyProvider(provider);
-        NSDiscoveredProvider(providerForCb);
+        NSProviderChanged(providerForCb, NS_DISCOVERED);
+        NSRemoveProvider(providerForCb);
     }
     else
     {
@@ -308,6 +280,10 @@ void NSConsumerHandleProviderDeleted(NSProvider_internal * provider)
 
     NSResult ret = NSStorageDelete(providerCache, provider->providerId);
     NS_VERIFY_NOT_NULL_V(ret == NS_OK ? (void *)1 : NULL);
+
+    NS_LOG_V(DEBUG, "Stopped Provider : %s", provider->providerId);
+    NSProvider * providerForCb = NSCopyProvider(provider);
+    NSProviderChanged(providerForCb, NS_STOPPED);
 }
 
 void NSConsumerHandleSubscribeSucceed(NSProvider_internal * provider)
@@ -339,40 +315,57 @@ void NSConsumerHandleRecvProviderChanged(NSMessage * msg)
     NS_VERIFY_NOT_NULL_V(msg);
 
     NS_LOG_V(DEBUG, "confirmed by : %s", msg->providerId);
-    NSProvider_internal * provider = NSProviderCacheFind(msg->providerId);
-    NS_VERIFY_NOT_NULL_V(provider);
 
+    NSCacheList * ProviderCache = *(NSGetProviderCacheList());
+
+    NSCacheElement * cacheElement = NSStorageRead(ProviderCache, msg->providerId);
+    NS_VERIFY_NOT_NULL_V(cacheElement);
+
+    pthread_mutex_t * mutex = NSGetCacheMutex();
+    pthread_mutex_lock(mutex);
+    NS_VERIFY_NOT_NULL_WITH_POST_CLEANING_V(cacheElement, pthread_mutex_unlock(mutex));
+    NSProvider_internal * provider = (NSProvider_internal *) cacheElement->data;
+    if (provider->state == (NSProviderState) msg->messageId)
+    {
+        NS_LOG_V(DEBUG, "Already receive message(ALLOW/DENY) : %d", (int) msg->messageId);
+        pthread_mutex_unlock(mutex);
+        return;
+    }
+
+    NS_LOG_V(DEBUG, "Provider State Changed %d -> %d",
+             (int) provider->state, (int) msg->messageId);
     NS_LOG(DEBUG, "call back to user");
+    provider->state = (NSProviderState) msg->messageId;
+
     NSProvider * prov = NSCopyProvider(provider);
-    NSProviderChanged(prov, (NSResponse) msg->messageId);
-    NSRemoveProvider_internal(provider);
+
+    pthread_mutex_unlock(mutex);
+    NSProviderChanged(prov, (NSProviderState) msg->messageId);
 }
 
 void NSConsumerHandleRecvMessage(NSMessage * msg)
 {
     NS_VERIFY_NOT_NULL_V(msg);
 
-    NSResult ret = NSMessageCacheUpdate(msg, NS_SYNC_UNREAD);
-    NS_VERIFY_NOT_NULL_V(ret == NS_OK ? (void *) 1 : NULL);
-
-    NSMessagePost((NSMessage *) msg);
+    if (NSInsertMessageState(msg->messageId, NS_SYNC_UNREAD))
+    {
+        NSMessagePost(msg);
+    }
 }
 
 void NSConsumerHandleRecvSyncInfo(NSSyncInfo * sync)
 {
     NS_VERIFY_NOT_NULL_V(sync);
 
-    char msgId[NS_DEVICE_ID_LENGTH] = { 0, };
-    snprintf(msgId, NS_DEVICE_ID_LENGTH, "%lld", (long long int)sync->messageId);
-
-    NSMessage * msg = NSMessageCacheFind(msgId);
-    NS_VERIFY_NOT_NULL_V(msg);
-
-    NSResult ret = NSMessageCacheUpdate(msg, sync->state);
-    NS_VERIFY_NOT_NULL_V(ret == NS_OK ? (void *) 1 : NULL);
-    NSRemoveMessage(msg);
+    if (NSUpdateMessageState(sync->messageId, sync->state))
+    {
+        NSNotificationSync(sync);
+    }
 
-    NSNotificationSync(sync);
+    if (sync->state == NS_SYNC_DELETED)
+    {
+        NSDeleteMessageState(sync->messageId);
+    }
 }
 
 void NSConsumerHandleMakeSyncInfo(NSSyncInfo * sync)
@@ -383,6 +376,7 @@ void NSConsumerHandleMakeSyncInfo(NSSyncInfo * sync)
     NS_VERIFY_NOT_NULL_V (provider);
 
     NSProviderConnectionInfo * connections = NSCopyProviderConnections(provider->connection);
+    NSRemoveProvider_internal(provider);
     NS_VERIFY_NOT_NULL_V (connections);
 
     NSSyncInfo_internal * syncInfo = (NSSyncInfo_internal *)OICMalloc(sizeof(NSSyncInfo_internal));
@@ -424,7 +418,7 @@ void NSConsumerHandleRecvTopicLL(NSProvider_internal * provider)
 
     NS_LOG(DEBUG, "call back to user");
     NSProvider * prov = NSCopyProvider(provider);
-    NSProviderChanged((NSProvider *) prov, (NSResponse) NS_TOPIC);
+    NSProviderChanged((NSProvider *) prov, (NSProviderState) NS_TOPIC);
 }
 
 void NSConsumerInternalTaskProcessing(NSTask * task)
@@ -505,3 +499,178 @@ void NSConsumerInternalTaskProcessing(NSTask * task)
     }
     NSOICFree(task);
 }
+
+// implements of MessageState function
+pthread_mutex_t ** NSGetMessageListMutex()
+{
+    static pthread_mutex_t * g_mutex = NULL;
+    if (g_mutex == NULL)
+    {
+        g_mutex = (pthread_mutex_t *) OICMalloc(sizeof(pthread_mutex_t));
+        NS_VERIFY_NOT_NULL(g_mutex, NULL);
+
+        pthread_mutex_init(g_mutex, NULL);
+    }
+    return & g_mutex;
+}
+
+void NSLockMessageListMutex()
+{
+    NS_LOG_V(DEBUG, "%s", __func__);
+    pthread_mutex_lock(*NSGetMessageListMutex());
+}
+
+void NSUnlockMessageListMutex()
+{
+    NS_LOG_V(DEBUG, "%s", __func__);
+    pthread_mutex_unlock(*NSGetMessageListMutex());
+}
+
+NSMessageStateList * NSGetMessageStateList()
+{
+    static NSMessageStateList * g_messageStateList = NULL;
+    if (g_messageStateList == NULL)
+    {
+        g_messageStateList = (NSMessageStateList *)OICMalloc(sizeof(NSMessageStateList));
+        NS_VERIFY_NOT_NULL(g_messageStateList, NULL);
+
+        g_messageStateList->head = NULL;
+        g_messageStateList->tail = NULL;
+    }
+
+    return g_messageStateList;
+}
+
+NSMessageStateLL * NSFindMessageState(uint64_t msgId)
+{
+    NS_LOG_V(DEBUG, "%s", __func__);
+    if (msgId <= NS_RESERVED_MESSAGEID) return NULL;
+    NSMessageStateLL * iter = NULL;
+
+    NSLockMessageListMutex();
+    if (NSGetMessageStateList()->head == NULL)
+    {
+        NSUnlockMessageListMutex();
+        return false;
+    }
+
+    for (iter = NSGetMessageStateList()->head; iter; iter = iter->next)
+    {
+        if (iter->messageId == msgId)
+        {
+            NSUnlockMessageListMutex();
+            return iter;
+        }
+    }
+
+    NSUnlockMessageListMutex();
+    return NULL;
+}
+
+bool NSUpdateMessageState(uint64_t msgId, NSSyncType state)
+{
+    NS_LOG_V(DEBUG, "%s", __func__);
+    if (msgId <= NS_RESERVED_MESSAGEID) return NULL;
+    NSMessageStateLL * iter = NULL;
+
+    NSLockMessageListMutex();
+    for (iter = NSGetMessageStateList()->head; iter; iter = iter->next)
+    {
+        if (iter->messageId == msgId && state != iter->state)
+        {
+            iter->state = state;
+            NSUnlockMessageListMutex();
+            return true;
+        }
+    }
+
+    NSUnlockMessageListMutex();
+    return false;
+}
+
+bool NSDeleteMessageState(uint64_t msgId)
+{
+    NS_LOG_V(DEBUG, "%s", __func__);
+    if (msgId <= NS_RESERVED_MESSAGEID) return NULL;
+    NSMessageStateLL * iter = NULL;
+    NSMessageStateLL * prev = NULL;
+
+    NSLockMessageListMutex();
+    for (iter = NSGetMessageStateList()->head; iter; iter = iter->next)
+    {
+        if (iter->messageId == msgId)
+        {
+            if (iter == NSGetMessageStateList()->head)
+            {
+                NSGetMessageStateList()->head = NULL;
+                NSGetMessageStateList()->tail = NULL;
+            }
+            else if (iter == NSGetMessageStateList()->tail)
+            {
+                prev->next = NULL;
+                NSGetMessageStateList()->tail = prev;
+            }
+            else
+            {
+                prev->next = iter->next;
+            }
+            NSUnlockMessageListMutex();
+
+            NSOICFree(iter);
+            return true;
+        }
+        prev = iter;
+    }
+
+    NSUnlockMessageListMutex();
+    return false;
+}
+
+bool NSInsertMessageState(uint64_t msgId, NSSyncType state)
+{
+    NS_LOG_V(DEBUG, "%s", __func__);
+    if (NSFindMessageState(msgId))
+    {
+        return false;
+    }
+
+    NSMessageStateLL * insertMsg = (NSMessageStateLL * )OICMalloc(sizeof(NSMessageStateLL));
+    NS_VERIFY_NOT_NULL(insertMsg, false);
+
+    insertMsg->messageId = msgId;
+    insertMsg->state = state;
+    insertMsg->next = NULL;
+
+    NSLockMessageListMutex();
+    if (NSGetMessageStateList()->head == NULL)
+    {
+        NSGetMessageStateList()->head = insertMsg;
+    }
+    else
+    {
+        NSGetMessageStateList()->tail->next = insertMsg;
+    }
+    NSGetMessageStateList()->tail = insertMsg;
+    NSUnlockMessageListMutex();
+
+    return true;
+}
+
+void NSDestroyMessageStateList()
+{
+    NS_LOG_V(DEBUG, "%s", __func__);
+    NSLockMessageListMutex();
+
+    NSMessageStateLL * iter = NSGetMessageStateList()->head;
+    while (iter)
+    {
+        NSMessageStateLL * del = iter;
+        iter = iter->next;
+        NSOICFree(del);
+    }
+
+    NSGetMessageStateList()->head = NULL;
+    NSGetMessageStateList()->tail = NULL;
+
+    NSUnlockMessageListMutex();
+}
index cbe4cfa..b12265b 100644 (file)
@@ -42,7 +42,7 @@ void NSSetProviderCacheList(NSCacheList *);
 
 void NSDestroyMessageCacheList();
 
-void NSDestroyProviderCacheList();
+void NSDestroyInternalCachedList();
 
 NSMessage * NSMessageCacheFind(const char *);
 
index 7501958..f06f918 100644 (file)
@@ -123,11 +123,7 @@ NSResult NSStorageWrite(NSCacheList * list, NSCacheElement * newObj)
     NSCacheType type = list->cacheType;
     NS_LOG_V(DEBUG, "cache type : %d", type);
 
-    if (type == NS_CONSUMER_CACHE_MESSAGE)
-    {
-        return NSConsumerCacheWriteMessage(list, newObj);
-    }
-    else if (type == NS_CONSUMER_CACHE_PROVIDER)
+    if (type == NS_CONSUMER_CACHE_PROVIDER)
     {
         return NSConsumerCacheWriteProvider(list, newObj);
     }
@@ -162,11 +158,7 @@ NSResult NSStorageDelete(NSCacheList * list, const char * delId)
 
             list->head = del->next;
 
-            if (type == NS_CONSUMER_CACHE_MESSAGE)
-            {
-                NSRemoveMessage((NSMessage *) del->data);
-            }
-            else if (type == NS_CONSUMER_CACHE_PROVIDER)
+            if (type == NS_CONSUMER_CACHE_PROVIDER)
             {
                 NSRemoveProvider_internal((NSProvider_internal *) del->data);
             }
@@ -188,11 +180,8 @@ NSResult NSStorageDelete(NSCacheList * list, const char * delId)
             }
 
             prev->next = del->next;
-            if (type == NS_CONSUMER_CACHE_MESSAGE)
-            {
-                NSRemoveMessage((NSMessage *) del->data);
-            }
-            else if (type == NS_CONSUMER_CACHE_PROVIDER)
+
+            if (type == NS_CONSUMER_CACHE_PROVIDER)
             {
                 NSRemoveProvider_internal((NSProvider_internal *) del->data);
             }
@@ -209,73 +198,6 @@ NSResult NSStorageDelete(NSCacheList * list, const char * delId)
     return NS_OK;
 }
 
-void NSConsumerRemoveMessageStore(NSCacheElement * ele, NSStoreMessage * msg)
-{
-    NSOICFree(ele);
-    NSOICFree(msg);
-}
-
-NSResult NSConsumerCacheWriteMessage(NSCacheList * list, NSCacheElement * newObj)
-{
-    NS_VERIFY_NOT_NULL(list, NS_ERROR);
-    NS_VERIFY_NOT_NULL(newObj, NS_ERROR);
-
-    pthread_mutex_t * mutex = NSGetCacheMutex();
-
-    NSMessage * newMsgObj = ((NSStoreMessage *)newObj->data)->msg;
-
-    char msgId[NS_DEVICE_ID_LENGTH] = {0, };
-    snprintf(msgId, NS_DEVICE_ID_LENGTH, "%lld", (long long int)newMsgObj->messageId);
-    NSCacheElement * it = NSStorageRead(list, msgId);
-
-    if (it)
-    {
-        NS_LOG(DEBUG, "Update message status.");
-        pthread_mutex_lock(mutex);
-        NSStoreMessage * sMsgObj = (NSStoreMessage *) it->data;
-        if(sMsgObj->status == ((NSStoreMessage *)newObj->data)->status)
-        {
-            NS_LOG (DEBUG, "Already receive message");
-            pthread_mutex_unlock(mutex);
-            return NS_ERROR;
-        }
-
-        sMsgObj->status = ((NSStoreMessage *)newObj->data)->status;
-        pthread_mutex_unlock(mutex);
-        return NS_OK;
-    }
-
-    NS_LOG(DEBUG, "Add message at storage.");
-    NSStoreMessage * sMsgObj = (NSStoreMessage *) OICMalloc(sizeof(NSStoreMessage));
-    NS_VERIFY_NOT_NULL(sMsgObj, NS_ERROR);
-
-    NSCacheElement * obj = (NSCacheElement *) OICMalloc(sizeof(NSCacheElement));
-    NS_VERIFY_NOT_NULL_WITH_POST_CLEANING(obj, NS_ERROR, NSOICFree(sMsgObj));
-
-    sMsgObj->status = NS_SYNC_UNREAD;
-    sMsgObj->msg = (void *) NSCopyMessage(newMsgObj);
-    NS_VERIFY_NOT_NULL_WITH_POST_CLEANING(sMsgObj->msg, NS_ERROR,
-          NSConsumerRemoveMessageStore(obj, sMsgObj));
-
-    obj->next = NULL;
-    obj->data = (NSCacheData *) sMsgObj;
-
-    pthread_mutex_lock(mutex);
-    if (!list->head)
-    {
-        list->head = obj;
-        list->tail = obj;
-        pthread_mutex_unlock(mutex);
-        return NS_OK;
-    }
-
-    (list->tail)->next = obj;
-    list->tail = obj;
-    pthread_mutex_unlock(mutex);
-
-    return NS_OK;
-}
-
 NSResult NSConsumerCacheWriteProvider(NSCacheList * list, NSCacheElement * newObj)
 {
     NS_VERIFY_NOT_NULL(list, NS_ERROR);
@@ -283,11 +205,6 @@ NSResult NSConsumerCacheWriteProvider(NSCacheList * list, NSCacheElement * newOb
 
     pthread_mutex_t * mutex = NSGetCacheMutex();
 
-    NS_LOG (DEBUG, "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!1");
-    NSProvider_internal * prov = (NSProvider_internal *)newObj->data;
-    NS_LOG_V (DEBUG, "%s", prov->providerId);
-    NS_LOG (DEBUG, "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!1");
-
     NSProvider_internal * newProvObj = (NSProvider_internal *) newObj->data;
 
     NSCacheElement * it = NSStorageRead(list, newProvObj->providerId);
@@ -328,11 +245,6 @@ NSResult NSConsumerCacheWriteProvider(NSCacheList * list, NSCacheElement * newOb
     NS_LOG_V(DEBUG, "New Object address : %s:%d", newProvObj->connection->addr->addr, newProvObj->connection->addr->port);
     obj->data = (void *) NSCopyProvider_internal(newProvObj);
 
-    NS_LOG (DEBUG, "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!2");
-    prov = (NSProvider_internal *)obj->data;
-    NS_LOG_V (DEBUG, "%s", prov->providerId);
-    NS_LOG (DEBUG, "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!2");
-
     if (!obj->data)
     {
         NS_LOG (ERROR, "Failed to CopyProvider");
@@ -347,11 +259,6 @@ NSResult NSConsumerCacheWriteProvider(NSCacheList * list, NSCacheElement * newOb
         list->head = obj;
         list->tail = obj;
 
-        NS_LOG (DEBUG, "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!3");
-        prov = (NSProvider_internal *)list->tail->data;
-        NS_LOG_V (DEBUG, "%s", prov->providerId);
-        NS_LOG (DEBUG, "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!3");
-
         pthread_mutex_unlock(mutex);
 
         return NS_OK;
@@ -360,11 +267,6 @@ NSResult NSConsumerCacheWriteProvider(NSCacheList * list, NSCacheElement * newOb
     (list->tail)->next = obj;
     list->tail = obj;
 
-    NS_LOG (DEBUG, "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!4");
-    prov = (NSProvider_internal *)list->tail->data;
-    NS_LOG_V (DEBUG, "%s", prov->providerId);
-    NS_LOG (DEBUG, "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!4");
-
     pthread_mutex_unlock(mutex);
 
     return NS_OK;
@@ -406,22 +308,7 @@ NSResult NSStorageDestroy(NSCacheList * list)
 
     NSCacheType type = list->cacheType;
 
-    if (type == NS_CONSUMER_CACHE_MESSAGE)
-    {
-        while (iter)
-        {
-            next = (NSCacheElement *) iter->next;
-
-            NSRemoveMessage(((NSStoreMessage *) iter->data)->msg);
-            NSOICFree(iter->data);
-            NSOICFree(iter);
-
-            iter = next;
-        }
-
-        NSOICFree(list);
-    }
-    else if (type == NS_CONSUMER_CACHE_PROVIDER)
+    if (type == NS_CONSUMER_CACHE_PROVIDER)
     {
         while (iter)
         {
@@ -446,20 +333,7 @@ bool NSConsumerCompareIdCacheData(NSCacheType type, void * data, const char * id
     NS_VERIFY_NOT_NULL(data, false);
     NS_VERIFY_NOT_NULL(id, false);
 
-    if (type == NS_CONSUMER_CACHE_MESSAGE)
-    {
-        NSMessage * msg = ((NSStoreMessage *) data)->msg;
-
-        char msgId[NS_DEVICE_ID_LENGTH] = {0, };
-        snprintf(msgId, NS_DEVICE_ID_LENGTH, "%lld", (long long int)msg->messageId);
-        if (!strcmp(msgId, id))
-        {
-            return true;
-        }
-
-        return false;
-    }
-    else if (type == NS_CONSUMER_CACHE_PROVIDER)
+    if (type == NS_CONSUMER_CACHE_PROVIDER)
     {
         NSProvider_internal * prov = (NSProvider_internal *) data;
         if (!strcmp(prov->providerId, id))
index e387570..8d6a608 100644 (file)
@@ -34,7 +34,7 @@ extern "C" {
 pthread_mutex_t * NSGetCacheMutex();
 
 bool NSConsumerCompareIdCacheData(NSCacheType type, void * data, const char * id);
-NSResult NSConsumerCacheWriteMessage(NSCacheList * list, NSCacheElement * newObj);
+
 NSResult NSConsumerCacheWriteProvider(NSCacheList * list, NSCacheElement * newObj);
 NSCacheElement * NSPopProviderCacheList(NSCacheList * list);
 
index 4d420af..82ccd24 100644 (file)
@@ -29,7 +29,7 @@
 #include "NSConsumerDiscovery.h"
 #include "NSConsumerNetworkEventListener.h"
 
-#define NS_PRESENCE_SUBSCRIBE_QUERY "coap://224.0.1.187:5683/oic/ad?rt=oic.r.notification"
+#define NS_PRESENCE_SUBSCRIBE_QUERY "/oic/ad?rt=oic.r.notification"
 
 void NSConnectionStateListener(const CAEndpoint_t * info, bool isConnected);
 
index 8c8f5c9..ff1540b 100644 (file)
@@ -120,12 +120,14 @@ void NSConsumerMessageHandlerExit()
 
     NSConsumerListenerTermiate();
     NSCancelAllSubscription();
+
     NSThreadStop(*(NSGetMsgHandleThreadHandle()));
+    NSSetMsgHandleThreadHandle(NULL);
+
     NSDestroyQueue(*(NSGetMsgHandleQueue()));
     NSSetMsgHandleQueue(NULL);
 
-    NSDestroyMessageCacheList();
-    NSDestroyProviderCacheList();
+    NSDestroyInternalCachedList();
 }
 
 void * NSConsumerMsgHandleThreadFunc(void * threadHandle)
@@ -264,29 +266,9 @@ void NSConsumerTaskProcessing(NSTask * task)
         }
         case TASK_SEND_SYNCINFO:
         case TASK_CONSUMER_REQ_TOPIC_LIST:
-        {
-            NSConsumerCommunicationTaskProcessing(task);
-            break;
-        }
-        case TASK_CONSUMER_GET_TOPIC_LIST:
         case TASK_CONSUMER_SELECT_TOPIC_LIST:
         {
-            NSProvider * provider = (NSProvider *)task->taskData;
-            NSProvider_internal * prov =
-                    NSConsumerFindNSProvider(provider->providerId);
-            NS_VERIFY_NOT_NULL_V(prov);
-            if (task->taskType == TASK_CONSUMER_SELECT_TOPIC_LIST)
-            {
-                NSRemoveTopicLL(prov->topicLL);
-                prov->topicLL = NSCopyTopicLL((NSTopicLL *)provider->topicLL);
-            }
-
-            NSTask * topTask = NSMakeTask(task->taskType, prov);
-            NS_VERIFY_NOT_NULL_V(topTask);
-            NSConsumerCommunicationTaskProcessing(topTask);
-
-            NSRemoveProvider((NSProvider *)task->taskData);
-            NSOICFree(task);
+            NSConsumerCommunicationTaskProcessing(task);
             break;
         }
         case TASK_CONSUMER_REQ_SUBSCRIBE_CANCEL:
@@ -326,7 +308,6 @@ void NSConsumerTaskProcessing(NSTask * task)
         }
         case TASK_RECV_SYNCINFO:
         case TASK_CONSUMER_RECV_MESSAGE:
-        case TASK_CONSUMER_PROVIDER_DISCOVERED:
         case TASK_CONSUMER_SENT_REQ_OBSERVE:
         case TASK_CONSUMER_RECV_PROVIDER_CHANGED:
         case TASK_MAKE_SYNCINFO:
@@ -336,6 +317,19 @@ void NSConsumerTaskProcessing(NSTask * task)
             NSConsumerInternalTaskProcessing(task);
             break;
         }
+        case TASK_CONSUMER_PROVIDER_DISCOVERED:
+        {
+            NSTask * getTopicTask = (NSTask *)OICMalloc(sizeof(NSTask));
+            NS_VERIFY_NOT_NULL_WITH_POST_CLEANING_V(getTopicTask,
+                        NSRemoveProvider_internal((NSProvider_internal *) task->taskData));
+            getTopicTask->nextTask = NULL;
+            getTopicTask->taskData =
+                    (void *) NSCopyProvider_internal((NSProvider_internal *) task->taskData);
+            getTopicTask->taskType = TASK_CONSUMER_REQ_TOPIC_LIST;
+            NSConsumerCommunicationTaskProcessing(getTopicTask);
+            NSConsumerInternalTaskProcessing(task);
+            break;
+        }
         default:
         {
             NS_LOG(ERROR, "Unknown type of task");
@@ -344,13 +338,6 @@ void NSConsumerTaskProcessing(NSTask * task)
     }
 }
 
-NSMessage * NSConsumerFindNSMessage(const char* messageId)
-{
-    NS_VERIFY_NOT_NULL(messageId, NULL);
-
-    return NSMessageCacheFind(messageId);
-}
-
 NSProvider_internal * NSConsumerFindNSProvider(const char * providerId)
 {
     NS_VERIFY_NOT_NULL(providerId, NULL);
index a09f678..93d9ab2 100644 (file)
@@ -44,7 +44,7 @@ void NSRegisterSubscribeRequestCb(NSSubscribeRequestCallback subscribeRequestCb)
     NS_LOG(DEBUG, "NSRegisterSubscribeRequestCb - OUT");\r
 }\r
 \r
-void  NSRegisterSyncCb(NSProviderSyncInfoCallback syncCb)\r
+void NSRegisterSyncCb(NSProviderSyncInfoCallback syncCb)\r
 {\r
     NS_LOG(DEBUG, "NSRegisterSyncCb - IN");\r
     g_syncCb = syncCb;\r
index 5f9d195..81b5903 100644 (file)
@@ -79,7 +79,7 @@ void * NSDiscoverySchedule(void * ptr)
                     NS_LOG(DEBUG, "CASE TASK_REGISTER_RESOURCE : ");\r
                     NSRegisterResource();\r
                     break;\r
-#ifdef RD_CLIENT\r
+#if(defined WITH_CLOUD && defined RD_CLIENT)\r
                 case TASK_PUBLISH_RESOURCE:\r
                     NS_LOG(DEBUG, "CASE TASK_PUBLISH_PESOURCE : ");\r
                     NSPublishResourceToCloud((char*)node->taskData);\r
index cddb775..71fcab4 100644 (file)
-//******************************************************************\r
-//\r
-// Copyright 2016 Samsung Electronics All Rights Reserved.\r
-//\r
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
-//\r
-// Licensed under the Apache License, Version 2.0 (the "License");\r
-// you may not use this file except in compliance with the License.\r
-// You may obtain a copy of the License at\r
-//\r
-//      http://www.apache.org/licenses/LICENSE-2.0\r
-//\r
-// Unless required by applicable law or agreed to in writing, software\r
-// distributed under the License is distributed on an "AS IS" BASIS,\r
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-// See the License for the specific language governing permissions and\r
-// limitations under the License.\r
-//\r
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
-\r
-#include "NSProviderInterface.h"\r
-#include "NSProviderScheduler.h"\r
-#include "NSProviderListener.h"\r
-#include "NSProviderSubscription.h"\r
-#include "NSProviderNotification.h"\r
-#include "NSProviderCallbackResponse.h"\r
-#include "NSStorageAdapter.h"\r
-#include "NSProviderMemoryCache.h"\r
-#include "NSProviderTopic.h"\r
-#include "oic_malloc.h"\r
-#include "oic_string.h"\r
-#include "cautilinterface.h"\r
-#include "NSProviderSystem.h"\r
-#include "oic_time.h"\r
-\r
-bool initProvider = false;\r
-\r
-pthread_mutex_t nsInitMutex;\r
-\r
-void initializeMutex()\r
-{\r
-    static pthread_mutex_t initMutex = PTHREAD_MUTEX_INITIALIZER;\r
-    nsInitMutex = initMutex;\r
-}\r
-\r
-NSResult NSStartProvider(NSProviderConfig config)\r
-{\r
-    NS_LOG(DEBUG, "NSStartProvider - IN");\r
-\r
-    initializeMutex();\r
-\r
-    pthread_mutex_lock(&nsInitMutex);\r
-\r
-    if (!initProvider)\r
-    {\r
-        NS_LOG(DEBUG, "Init Provider");\r
-        initProvider = true;\r
-        NSInitProviderInfo(config.userInfo);\r
-        NSSetSubscriptionAccessPolicy(config.policy);\r
-        NSRegisterSubscribeRequestCb(config.subRequestCallback);\r
-        NSRegisterSyncCb(config.syncInfoCallback);\r
-        CARegisterNetworkMonitorHandler((CAAdapterStateChangedCB)NSProviderAdapterStateListener,\r
-                (CAConnectionStateChangedCB)NSProviderConnectionStateListener);\r
-\r
-        NSSetList();\r
-        NSInitScheduler();\r
-        NSStartScheduler();\r
-\r
-        NSPushQueue(DISCOVERY_SCHEDULER, TASK_START_PRESENCE, NULL);\r
-        NSPushQueue(DISCOVERY_SCHEDULER, TASK_REGISTER_RESOURCE, NULL);\r
-    }\r
-    else\r
-    {\r
-        NS_LOG(DEBUG, "Already started Notification Provider");\r
-    }\r
-    pthread_mutex_unlock(&nsInitMutex);\r
-\r
-    NS_LOG(DEBUG, "NSStartProvider - OUT");\r
-    return NS_OK;\r
-}\r
-\r
-void NSSetList()\r
-{\r
-    NS_LOG(DEBUG, "NSSetList - IN");\r
-\r
-    pthread_mutexattr_init(&NSCacheMutexAttr);\r
-    int pthreadResult = pthread_mutexattr_settype(&NSCacheMutexAttr, PTHREAD_MUTEX_RECURSIVE);\r
-    pthread_mutex_init(&NSCacheMutex, &NSCacheMutexAttr);\r
-\r
-    NSInitSubscriptionList();\r
-    NSInitMessageList();\r
-    NSInitTopicList();\r
-    NS_LOG(DEBUG, "NSSetList - OUT");\r
-}\r
-\r
-void NSDestroyList()\r
-{\r
-    NSStorageDestroy(consumerSubList);\r
-    NSStorageDestroy(messageList);\r
-    NSStorageDestroy(consumerTopicList);\r
-    NSStorageDestroy(registeredTopicList);\r
-\r
-    pthread_mutex_destroy(&NSCacheMutex);\r
-    pthread_mutexattr_destroy(&NSCacheMutexAttr);\r
-}\r
-\r
-NSResult NSStopProvider()\r
-{\r
-    NS_LOG(DEBUG, "NSStopProvider - IN");\r
-    pthread_mutex_lock(&nsInitMutex);\r
-\r
-    if(initProvider)\r
-    {\r
-        NSPushQueue(DISCOVERY_SCHEDULER, TASK_STOP_PRESENCE, NULL);\r
-        NSDeinitProviderInfo();\r
-        NSUnRegisterResource();\r
-        NSRegisterSubscribeRequestCb((NSSubscribeRequestCallback)NULL);\r
-        NSRegisterSyncCb((NSProviderSyncInfoCallback)NULL);\r
-        NSStopScheduler();\r
-        NSDestroyList();\r
-\r
-        initProvider = false;\r
-    }\r
-\r
-    pthread_mutex_unlock(&nsInitMutex);\r
-    NS_LOG(DEBUG, "NSStopProvider - OUT");\r
-    return NS_OK;\r
-}\r
-\r
-NSResult NSProviderEnableRemoteService(char *serverAddress)\r
-{\r
-    NS_LOG(DEBUG, "NSProviderEnableRemoteService - IN");\r
-    pthread_mutex_lock(&nsInitMutex);\r
-\r
-    if(!initProvider)\r
-    {\r
-        NS_LOG(DEBUG, "Provider service has not been started yet");\r
-        pthread_mutex_unlock(&nsInitMutex);\r
-        return NS_FAIL;\r
-    }\r
-    NS_LOG(DEBUG, "Check the remote server login");\r
-    NS_LOG_V(DEBUG, "Remote server address: %s", serverAddress);\r
-#ifdef RD_CLIENT\r
-    NS_LOG(DEBUG, "Request to publish resource");\r
-    NSPushQueue(DISCOVERY_SCHEDULER, TASK_PUBLISH_RESOURCE, serverAddress);\r
-#endif\r
-\r
-    pthread_mutex_unlock(&nsInitMutex);\r
-    NS_LOG(DEBUG, "NSProviderEnableRemoteService - OUT");\r
-    return NS_OK;\r
-}\r
-\r
-NSResult NSProviderDisableRemoteService(char *serverAddress)\r
-{\r
-    NS_LOG(DEBUG, "NSProviderDisableRemoteService - IN");\r
-    pthread_mutex_lock(&nsInitMutex);\r
-\r
-    if(!initProvider)\r
-    {\r
-        NS_LOG(DEBUG, "Provider service has not been started yet");\r
-        return NS_FAIL;\r
-    }\r
-    NS_LOG_V(DEBUG, "Remote server address: %s", serverAddress);\r
-#ifdef RD_CLIENT\r
-    NS_LOG(DEBUG, "Delete remote server info");\r
-    NSDeleteRemoteServerAddress(serverAddress);\r
-#endif\r
-\r
-    pthread_mutex_unlock(&nsInitMutex);\r
-    NS_LOG(DEBUG, "NSProviderDisableRemoteService - OUT");\r
-    return NS_OK;\r
-}\r
-\r
-NSResult NSSendMessage(NSMessage *msg)\r
-{\r
-    NS_LOG(DEBUG, "NSSendNotification - IN");\r
-\r
-    pthread_mutex_lock(&nsInitMutex);\r
-\r
-    if(msg == NULL)\r
-    {\r
-        NS_LOG(ERROR, "Msg is NULL");\r
-        pthread_mutex_unlock(&nsInitMutex);\r
-        return NS_ERROR;\r
-    }\r
-\r
-    NSMessage * newMsg = NSDuplicateMessage(msg);\r
-    NSPushQueue(NOTIFICATION_SCHEDULER, TASK_SEND_NOTIFICATION, newMsg);\r
-\r
-    pthread_mutex_unlock(&nsInitMutex);\r
-\r
-    NS_LOG(DEBUG, "NSSendNotification - OUT");\r
-    return NS_OK;\r
-}\r
-\r
-NSResult NSProviderSendSyncInfo(uint64_t messageId, NSSyncType type)\r
-{\r
-    NS_LOG(DEBUG, "NSProviderReadCheck - IN");\r
-    pthread_mutex_lock(&nsInitMutex);\r
-\r
-    NSSyncInfo * syncInfo = (NSSyncInfo *)OICMalloc(sizeof(NSSyncInfo));\r
-    OICStrcpy(syncInfo->providerId, UUID_STRING_SIZE, NSGetProviderInfo()->providerId);\r
-    syncInfo->messageId = messageId;\r
-    syncInfo->state = type;\r
-    NSPushQueue(NOTIFICATION_SCHEDULER, TASK_SEND_READ, syncInfo);\r
-\r
-    pthread_mutex_unlock(&nsInitMutex);\r
-    NS_LOG(DEBUG, "NSProviderReadCheck - OUT");\r
-    return NS_OK;\r
-}\r
-\r
-NSResult NSAcceptSubscription(NSConsumer *consumer, bool accepted)\r
-{\r
-    NS_LOG(DEBUG, "NSAccept - IN");\r
-\r
-    pthread_mutex_lock(&nsInitMutex);\r
-\r
-    NSConsumer * newConsumer = NSDuplicateConsumer(consumer);\r
-    if(accepted)\r
-    {\r
-        NS_LOG(DEBUG, "accepted is true - ALLOW");\r
-        NSPushQueue(SUBSCRIPTION_SCHEDULER, TASK_SEND_ALLOW, newConsumer);\r
-    }\r
-    else\r
-    {\r
-        NS_LOG(DEBUG, "accepted is false - DENY");\r
-        NSPushQueue(SUBSCRIPTION_SCHEDULER, TASK_SEND_DENY, newConsumer);\r
-    }\r
-\r
-    pthread_mutex_unlock(&nsInitMutex);\r
-    NS_LOG(DEBUG, "NSAccept - OUT");\r
-    return NS_OK;\r
-}\r
-\r
-NSMessage * NSCreateMessage()\r
-{\r
-    NS_LOG(DEBUG, "NSCreateMessage - IN");\r
-    pthread_mutex_lock(&nsInitMutex);\r
-\r
-    NSMessage * msg = NSInitializeMessage();\r
-    OICStrcpy(msg->providerId, UUID_STRING_SIZE, NSGetProviderInfo()->providerId);\r
-\r
-    pthread_mutex_unlock(&nsInitMutex);\r
-    NS_LOG(DEBUG, "NSCreateMessage - OUT");\r
-    return msg;\r
-}\r
-\r
-NSTopicLL * NSProviderGetConsumerTopics(char *consumerId)\r
-{\r
-    NS_LOG(DEBUG, "NSProviderGetConsumerTopics - IN");\r
-    pthread_mutex_lock(&nsInitMutex);\r
-\r
-    if(!consumerId)\r
-    {\r
-        NS_LOG(DEBUG, "consumer id should be set");\r
-        pthread_mutex_unlock(&nsInitMutex);\r
-        return NS_FAIL;\r
-    }\r
-\r
-    NSTopicLL * topics = NSProviderGetConsumerTopicsCacheData(registeredTopicList,\r
-            consumerTopicList, consumerId);\r
-\r
-    pthread_mutex_unlock(&nsInitMutex);\r
-    return topics;\r
-}\r
-\r
-NSTopicLL * NSProviderGetTopics()\r
-{\r
-    NS_LOG(DEBUG, "NSProviderGetTopics - IN");\r
-    pthread_mutex_lock(&nsInitMutex);\r
-\r
-    NSTopicLL * topics = NSProviderGetTopicsCacheData(registeredTopicList);\r
-\r
-    pthread_mutex_unlock(&nsInitMutex);\r
-    NS_LOG(DEBUG, "NSProviderGetTopics - OUT");\r
-\r
-    return topics;\r
-}\r
-\r
-NSResult NSProviderAddTopic(char *topicName)\r
-{\r
-    NS_LOG(DEBUG, "NSProviderAddTopics - IN");\r
-    pthread_mutex_lock(&nsInitMutex);\r
-\r
-    if(!topicName)\r
-    {\r
-        pthread_mutex_unlock(&nsInitMutex);\r
-        NS_LOG(DEBUG, "topic Name should be set");\r
-        return NS_FAIL;\r
-    }\r
-\r
-    NSPushQueue(TOPIC_SCHEDULER, TASK_ADD_TOPIC, OICStrdup(topicName));\r
-\r
-    pthread_mutex_unlock(&nsInitMutex);\r
-    NS_LOG(DEBUG, "NSProviderAddTopics - OUT");\r
-    return NS_OK;\r
-}\r
-\r
-NSResult NSProviderDeleteTopic(char *topicName)\r
-{\r
-    NS_LOG(DEBUG, "NSProviderDeleteTopics - IN");\r
-    pthread_mutex_lock(&nsInitMutex);\r
-\r
-    if(!topicName)\r
-    {\r
-        pthread_mutex_unlock(&nsInitMutex);\r
-        NS_LOG(DEBUG, "topic Name should be set");\r
-        return NS_FAIL;\r
-    }\r
-\r
-    NSPushQueue(TOPIC_SCHEDULER, TASK_DELETE_TOPIC, topicName);\r
-\r
-    pthread_mutex_unlock(&nsInitMutex);\r
-    NS_LOG(DEBUG, "NSProviderDeleteTopics - OUT");\r
-    return NS_OK;\r
-}\r
-\r
-NSResult NSProviderSelectTopic(char *consumerId, char *topicName)\r
-{\r
-    NS_LOG(DEBUG, "NSProviderSelectTopics - IN");\r
-    pthread_mutex_lock(&nsInitMutex);\r
-\r
-    if(!consumerId || !topicName || !NSGetPolicy())\r
-    {\r
-        NS_LOG(DEBUG, "consumer id should be set for topic subscription or "\r
-                "Configuration must set to true.");\r
-        pthread_mutex_unlock(&nsInitMutex);\r
-        return NS_FAIL;\r
-    }\r
-\r
-    NSCacheTopicSubData * topicSubData =\r
-            (NSCacheTopicSubData *) OICMalloc(sizeof(NSCacheTopicSubData));\r
-\r
-    OICStrcpy(topicSubData->id, NS_UUID_STRING_SIZE, consumerId);\r
-    topicSubData->topicName = OICStrdup(topicName);\r
-\r
-    NSPushQueue(TOPIC_SCHEDULER, TASK_SUBSCRIBE_TOPIC, (void *)topicSubData);\r
-\r
-    pthread_mutex_unlock(&nsInitMutex);\r
-    NS_LOG(DEBUG, "NSProviderSelectTopics - OUT");\r
-    return NS_OK;\r
-}\r
-\r
-NSResult NSProviderUnselectTopic(char *consumerId, char *topicName)\r
-{\r
-    NS_LOG(DEBUG, "NSProviderUnselectTopics - IN");\r
-    pthread_mutex_lock(&nsInitMutex);\r
-\r
-    if(!consumerId || !topicName || !NSGetPolicy())\r
-    {\r
-        NS_LOG(DEBUG, "consumer id should be set for topic subscription or "\r
-                "Configuration must set to true.");\r
-        pthread_mutex_unlock(&nsInitMutex);\r
-        return NS_FAIL;\r
-    }\r
-\r
-    NSCacheTopicSubData * topicSubData =\r
-            (NSCacheTopicSubData *) OICMalloc(sizeof(NSCacheTopicSubData));\r
-\r
-    OICStrcpy(topicSubData->id, NS_UUID_STRING_SIZE, consumerId);\r
-    topicSubData->topicName = OICStrdup(topicName);\r
-\r
-    NSPushQueue(TOPIC_SCHEDULER, TASK_UNSUBSCRIBE_TOPIC, (void *)topicSubData);\r
-\r
-    pthread_mutex_unlock(&nsInitMutex);\r
-    NS_LOG(DEBUG, "NSProviderUnselectTopics - OUT");\r
-    return NS_OK;\r
-}\r
-\r
+//******************************************************************
+//
+// Copyright 2016 Samsung Electronics 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#include "NSProviderInterface.h"
+#include "NSProviderScheduler.h"
+#include "NSProviderListener.h"
+#include "NSProviderSubscription.h"
+#include "NSProviderNotification.h"
+#include "NSProviderCallbackResponse.h"
+#include "NSStorageAdapter.h"
+#include "NSProviderMemoryCache.h"
+#include "NSProviderTopic.h"
+#include "oic_malloc.h"
+#include "oic_string.h"
+#include "cautilinterface.h"
+#include "NSProviderSystem.h"
+#include "oic_time.h"
+#include <pthread.h>
+
+bool initProvider = false;
+
+pthread_mutex_t nsInitMutex;
+pthread_cond_t nstopicCond;
+
+void initializeMutex()
+{
+    static pthread_mutex_t initMutex = PTHREAD_MUTEX_INITIALIZER;
+    nsInitMutex = initMutex;
+}
+
+void NSInitialize()
+{
+    NS_LOG(DEBUG, "NSSetList - IN");
+
+    pthread_mutexattr_init(&NSCacheMutexAttr);
+    pthread_mutexattr_settype(&NSCacheMutexAttr, PTHREAD_MUTEX_RECURSIVE);
+    pthread_mutex_init(&NSCacheMutex, &NSCacheMutexAttr);
+    pthread_cond_init(&nstopicCond, NULL);
+
+    NSInitSubscriptionList();
+    NSInitTopicList();
+    NS_LOG(DEBUG, "NSSetList - OUT");
+}
+
+void NSDeinitailize()
+{
+    NSStorageDestroy(consumerSubList);
+    NSStorageDestroy(consumerTopicList);
+    NSStorageDestroy(registeredTopicList);
+
+    pthread_mutex_destroy(&NSCacheMutex);
+    pthread_mutexattr_destroy(&NSCacheMutexAttr);
+    pthread_cond_destroy(&nstopicCond);
+}
+
+NSResult NSStartProvider(NSProviderConfig config)
+{
+    NS_LOG(DEBUG, "NSStartProvider - IN");
+
+    initializeMutex();
+
+    pthread_mutex_lock(&nsInitMutex);
+
+    if (!initProvider)
+    {
+        NS_LOG(DEBUG, "Init Provider");
+        initProvider = true;
+        NSInitProviderInfo(config.userInfo);
+        NSSetSubscriptionAccessPolicy(config.subControllability);
+        NSRegisterSubscribeRequestCb(config.subRequestCallback);
+        NSRegisterSyncCb(config.syncInfoCallback);
+        CARegisterNetworkMonitorHandler((CAAdapterStateChangedCB)NSProviderAdapterStateListener,
+                (CAConnectionStateChangedCB)NSProviderConnectionStateListener);
+
+        NSInitialize();
+        NSInitScheduler();
+        NSStartScheduler();
+
+        NSPushQueue(DISCOVERY_SCHEDULER, TASK_START_PRESENCE, NULL);
+        NSPushQueue(DISCOVERY_SCHEDULER, TASK_REGISTER_RESOURCE, NULL);
+    }
+    else
+    {
+        NS_LOG(DEBUG, "Already started Notification Provider");
+    }
+    pthread_mutex_unlock(&nsInitMutex);
+
+    NS_LOG(DEBUG, "NSStartProvider - OUT");
+    return NS_OK;
+}
+
+NSResult NSStopProvider()
+{
+    NS_LOG(DEBUG, "NSStopProvider - IN");
+    pthread_mutex_lock(&nsInitMutex);
+
+    if(initProvider)
+    {
+        NSPushQueue(DISCOVERY_SCHEDULER, TASK_STOP_PRESENCE, NULL);
+        NSDeinitProviderInfo();
+        NSUnRegisterResource();
+        NSRegisterSubscribeRequestCb((NSSubscribeRequestCallback)NULL);
+        NSRegisterSyncCb((NSProviderSyncInfoCallback)NULL);
+        NSStopScheduler();
+        NSDeinitailize();
+
+        initProvider = false;
+    }
+
+    pthread_mutex_unlock(&nsInitMutex);
+    NS_LOG(DEBUG, "NSStopProvider - OUT");
+    return NS_OK;
+}
+
+NSResult NSProviderEnableRemoteService(char *serverAddress)
+{
+#if(defined WITH_CLOUD && defined RD_CLIENT)
+    NS_LOG(DEBUG, "NSProviderEnableRemoteService - IN");
+    pthread_mutex_lock(&nsInitMutex);
+
+    if(!initProvider || !serverAddress)
+    {
+        NS_LOG(DEBUG, "Provider service has not been started yet");
+        pthread_mutex_unlock(&nsInitMutex);
+        return NS_FAIL;
+    }
+    NS_LOG_V(DEBUG, "Remote server address: %s", serverAddress);
+    NS_LOG(DEBUG, "Request to publish resource");
+    NSPushQueue(DISCOVERY_SCHEDULER, TASK_PUBLISH_RESOURCE, serverAddress);
+
+    pthread_mutex_unlock(&nsInitMutex);
+    NS_LOG(DEBUG, "NSProviderEnableRemoteService - OUT");
+    return NS_OK;
+#else
+    (void) serverAddress;
+#endif
+    NS_LOG_V(DEBUG, "Not logged in remote server: %s", serverAddress);
+    return NS_FAIL;
+}
+
+NSResult NSProviderDisableRemoteService(char *serverAddress)
+{
+#if(defined WITH_CLOUD && defined RD_CLIENT)
+    NS_LOG(DEBUG, "NSProviderDisableRemoteService - IN");
+    pthread_mutex_lock(&nsInitMutex);
+
+    if(!initProvider || !serverAddress)
+    {
+        NS_LOG(DEBUG, "Provider service has not been started yet");
+        return NS_FAIL;
+    }
+    NS_LOG_V(DEBUG, "Remote server address: %s", serverAddress);
+
+    NS_LOG(DEBUG, "Delete remote server info");
+    NSDeleteRemoteServerAddress(serverAddress);
+
+    pthread_mutex_unlock(&nsInitMutex);
+    NS_LOG(DEBUG, "NSProviderDisableRemoteService - OUT");
+    return NS_OK;
+#else
+    (void) serverAddress;
+#endif
+    NS_LOG_V(DEBUG, "Not logged in remote server : %s", serverAddress);
+    return NS_FAIL;
+}
+
+NSResult NSSendMessage(NSMessage * msg)
+{
+    NS_LOG(DEBUG, "NSSendNotification - IN");
+
+    pthread_mutex_lock(&nsInitMutex);
+
+    if(msg == NULL)
+    {
+        NS_LOG(ERROR, "Msg is NULL");
+        pthread_mutex_unlock(&nsInitMutex);
+        return NS_FAIL;
+    }
+
+    NSMessage * newMsg = NSDuplicateMessage(msg);
+    NSPushQueue(NOTIFICATION_SCHEDULER, TASK_SEND_NOTIFICATION, newMsg);
+
+    pthread_mutex_unlock(&nsInitMutex);
+
+    NS_LOG(DEBUG, "NSSendNotification - OUT");
+    return NS_OK;
+}
+
+NSResult NSProviderSendSyncInfo(uint64_t messageId, NSSyncType type)
+{
+    NS_LOG(DEBUG, "NSProviderReadCheck - IN");
+    pthread_mutex_lock(&nsInitMutex);
+
+    NSSyncInfo * syncInfo = (NSSyncInfo *)OICMalloc(sizeof(NSSyncInfo));
+    OICStrcpy(syncInfo->providerId, UUID_STRING_SIZE, NSGetProviderInfo()->providerId);
+    syncInfo->messageId = messageId;
+    syncInfo->state = type;
+    NSPushQueue(NOTIFICATION_SCHEDULER, TASK_SEND_READ, syncInfo);
+
+    pthread_mutex_unlock(&nsInitMutex);
+    NS_LOG(DEBUG, "NSProviderReadCheck - OUT");
+    return NS_OK;
+}
+
+NSResult NSAcceptSubscription(const char * consumerId, bool accepted)
+{
+    NS_LOG(DEBUG, "NSAccept - IN");
+    pthread_mutex_lock(&nsInitMutex);
+
+    if(!consumerId)
+    {
+        NS_LOG(ERROR, "consumerId is NULL");
+        pthread_mutex_unlock(&nsInitMutex);
+        return NS_FAIL;
+    }
+
+    char * newConsumerId = OICStrdup(consumerId);
+    if(accepted)
+    {
+        NS_LOG(DEBUG, "accepted is true - ALLOW");
+        NSPushQueue(SUBSCRIPTION_SCHEDULER, TASK_SEND_ALLOW, newConsumerId);
+    }
+    else
+    {
+        NS_LOG(DEBUG, "accepted is false - DENY");
+        NSPushQueue(SUBSCRIPTION_SCHEDULER, TASK_SEND_DENY, newConsumerId);
+    }
+
+    pthread_mutex_unlock(&nsInitMutex);
+    NS_LOG(DEBUG, "NSAccept - OUT");
+    return NS_OK;
+}
+
+NSMessage * NSCreateMessage()
+{
+    NS_LOG(DEBUG, "NSCreateMessage - IN");
+    pthread_mutex_lock(&nsInitMutex);
+
+    NSMessage * msg = NSInitializeMessage();
+
+    OICStrcpy(msg->providerId, UUID_STRING_SIZE, NSGetProviderInfo()->providerId);
+
+    pthread_mutex_unlock(&nsInitMutex);
+    NS_LOG(DEBUG, "NSCreateMessage - OUT");
+    return msg;
+}
+
+NSTopicLL * NSProviderGetConsumerTopics(const char * consumerId)
+{
+    NS_LOG(DEBUG, "NSProviderGetConsumerTopics - IN");
+    pthread_mutex_lock(&nsInitMutex);
+
+    if(!consumerId || consumerId[0] == '\0')
+    {
+        NS_LOG(DEBUG, "consumer id should be set");
+        pthread_mutex_unlock(&nsInitMutex);
+        return NULL;
+    }
+
+    NSTopicSynchronization topics;
+    topics.consumerId = OICStrdup(consumerId);
+    topics.topics = NULL;
+    topics.condition = nstopicCond;
+
+    NSPushQueue(TOPIC_SCHEDULER, TAST_GET_CONSUMER_TOPICS, &topics);
+    pthread_cond_wait(&topics.condition, &nsInitMutex);
+    OICFree(topics.consumerId);
+
+    pthread_mutex_unlock(&nsInitMutex);
+    NS_LOG(DEBUG, "NSProviderGetConsumerTopics - OUT");
+    return topics.topics;
+}
+
+NSTopicLL * NSProviderGetTopics()
+{
+    NS_LOG(DEBUG, "NSProviderGetTopics - IN");
+    pthread_mutex_lock(&nsInitMutex);
+
+    NSTopicSynchronization topics;
+    topics.consumerId = NULL;
+    topics.topics = NULL;
+    topics.condition = nstopicCond;
+
+    NSPushQueue(TOPIC_SCHEDULER, TASK_GET_TOPICS, &topics);
+    pthread_cond_wait(&topics.condition, &nsInitMutex);
+
+    pthread_mutex_unlock(&nsInitMutex);
+    NS_LOG(DEBUG, "NSProviderGetTopics - OUT");
+    return topics.topics;
+}
+
+NSResult NSProviderRegisterTopic(const char * topicName)
+{
+    NS_LOG(DEBUG, "NSProviderAddTopics - IN");
+    pthread_mutex_lock(&nsInitMutex);
+
+    if(!topicName || topicName == '\0')
+    {
+        pthread_mutex_unlock(&nsInitMutex);
+        NS_LOG(DEBUG, "topic Name should be set");
+        return NS_FAIL;
+    }
+
+    NSPushQueue(TOPIC_SCHEDULER, TASK_ADD_TOPIC, OICStrdup(topicName));
+
+    pthread_mutex_unlock(&nsInitMutex);
+    NS_LOG(DEBUG, "NSProviderAddTopics - OUT");
+    return NS_OK;
+}
+
+NSResult NSProviderUnregisterTopic(const char * topicName)
+{
+    NS_LOG(DEBUG, "NSProviderDeleteTopics - IN");
+    pthread_mutex_lock(&nsInitMutex);
+
+    if(!topicName || topicName[0] == '\0')
+    {
+        pthread_mutex_unlock(&nsInitMutex);
+        NS_LOG(DEBUG, "topic Name should be set");
+        return NS_FAIL;
+    }
+
+    NSPushQueue(TOPIC_SCHEDULER, TASK_DELETE_TOPIC, (void *) topicName);
+
+    pthread_mutex_unlock(&nsInitMutex);
+    NS_LOG(DEBUG, "NSProviderDeleteTopics - OUT");
+    return NS_OK;
+}
+
+NSResult NSProviderSetConsumerTopic(const char * consumerId, const char * topicName)
+{
+    NS_LOG(DEBUG, "NSProviderSelectTopics - IN");
+    pthread_mutex_lock(&nsInitMutex);
+
+    if(!consumerId || consumerId[0] == '\0' || !topicName || topicName[0] == '\0' || !NSGetPolicy())
+    {
+        NS_LOG(DEBUG, "consumer id should be set for topic subscription or "
+                "Configuration must set to true.");
+        pthread_mutex_unlock(&nsInitMutex);
+        return NS_FAIL;
+    }
+
+    NSCacheTopicSubData * topicSubData =
+            (NSCacheTopicSubData *) OICMalloc(sizeof(NSCacheTopicSubData));
+
+    OICStrcpy(topicSubData->id, NS_UUID_STRING_SIZE, consumerId);
+    topicSubData->topicName = OICStrdup(topicName);
+
+    NSPushQueue(TOPIC_SCHEDULER, TASK_SUBSCRIBE_TOPIC, (void *)topicSubData);
+
+    pthread_mutex_unlock(&nsInitMutex);
+    NS_LOG(DEBUG, "NSProviderSelectTopics - OUT");
+    return NS_OK;
+}
+
+NSResult NSProviderUnsetConsumerTopic(const char * consumerId, const char * topicName)
+{
+    NS_LOG(DEBUG, "NSProviderUnselectTopics - IN");
+    pthread_mutex_lock(&nsInitMutex);
+
+    if(!consumerId || consumerId[0] == '\0' || !topicName || topicName[0] == '\0' || !NSGetPolicy())
+    {
+        NS_LOG(DEBUG, "consumer id should be set for topic subscription or "
+                "Configuration must set to true.");
+        pthread_mutex_unlock(&nsInitMutex);
+        return NS_FAIL;
+    }
+
+    NSCacheTopicSubData * topicSubData =
+            (NSCacheTopicSubData *) OICMalloc(sizeof(NSCacheTopicSubData));
+
+    OICStrcpy(topicSubData->id, NS_UUID_STRING_SIZE, consumerId);
+    topicSubData->topicName = OICStrdup(topicName);
+
+    NSPushQueue(TOPIC_SCHEDULER, TASK_UNSUBSCRIBE_TOPIC, (void *)topicSubData);
+
+    pthread_mutex_unlock(&nsInitMutex);
+    NS_LOG(DEBUG, "NSProviderUnselectTopics - OUT");
+    return NS_OK;
+}
index 01011f9..8e1c653 100644 (file)
@@ -200,7 +200,7 @@ OCEntityHandlerResult NSEntityHandlerSyncCb(OCEntityHandlerFlag flag,
     if (OCDoResponse(&response) != OC_STACK_OK)\r
     {\r
         NS_LOG(ERROR, "Fail to AccessPolicy send response");\r
-        return NS_ERROR;\r
+        return OC_EH_ERROR;\r
     }\r
 \r
     NS_LOG(DEBUG, "NSEntityHandlerSyncCb - OUT");\r
@@ -247,11 +247,28 @@ OCEntityHandlerResult NSEntityHandlerTopicCb(OCEntityHandlerFlag flag,
             ehResult = OC_EH_ERROR;\r
 \r
             // Accepter is consumer. our service is support sendtopiclist from OC_REST_POST\r
-            if(!NSGetPolicy())\r
+            if(NSGetPolicy() == false)\r
             {\r
                 NSPushQueue(TOPIC_SCHEDULER, TASK_POST_TOPIC,\r
                         NSCopyOCEntityHandlerRequest(entityHandlerRequest));\r
                 ehResult = OC_EH_OK;\r
+                OCEntityHandlerResponse response;\r
+                response.numSendVendorSpecificHeaderOptions = 0;\r
+                memset(response.sendVendorSpecificHeaderOptions, 0,\r
+                        sizeof response.sendVendorSpecificHeaderOptions);\r
+                memset(response.resourceUri, 0, sizeof response.resourceUri);\r
+\r
+                response.requestHandle = entityHandlerRequest->requestHandle;\r
+                response.resourceHandle = entityHandlerRequest->resource;\r
+                response.persistentBufferFlag = 0;\r
+                response.ehResult = ehResult;\r
+                response.payload = (OCPayload *) NULL;\r
+\r
+                if (OCDoResponse(&response) != OC_STACK_OK)\r
+                {\r
+                    NS_LOG(ERROR, "Fail to AccessPolicy send response");\r
+                    return OC_EH_ERROR;\r
+                }\r
             }\r
         }\r
         else\r
index 710cee1..9bf1145 100644 (file)
@@ -490,8 +490,8 @@ NSTopicLL * NSProviderGetTopicsCacheData(NSCacheList * regTopicList)
     while (iter)\r
     {\r
         NSCacheTopicData * curr = (NSCacheTopicData *) iter->data;\r
-\r
         newTopic = (NSTopicLL *) OICMalloc(sizeof(NSTopicLL));\r
+\r
         newTopic->state = curr->state;\r
         newTopic->next = NULL;\r
         newTopic->topicName = OICStrdup(curr->topicName);\r
@@ -516,7 +516,7 @@ NSTopicLL * NSProviderGetTopicsCacheData(NSCacheList * regTopicList)
 }\r
 \r
 NSTopicLL * NSProviderGetConsumerTopicsCacheData(NSCacheList * regTopicList,\r
-        NSCacheList * conTopicList, char *consumerId)\r
+        NSCacheList * conTopicList, const char * consumerId)\r
 {\r
     NS_LOG(DEBUG, "NSProviderGetConsumerTopicsCacheData - IN");\r
 \r
@@ -536,11 +536,11 @@ NSTopicLL * NSProviderGetConsumerTopicsCacheData(NSCacheList * regTopicList,
     {\r
         NSCacheTopicSubData * curr = (NSCacheTopicSubData *)iter->data;\r
 \r
-        NS_LOG_V(DEBUG, "curr->id = %s", curr->id);\r
-        NS_LOG_V(DEBUG, "curr->topicName = %s", curr->topicName);\r
-\r
         if(curr && strcmp(curr->id, consumerId) == 0)\r
         {\r
+            NS_LOG_V(DEBUG, "curr->id = %s", curr->id);\r
+            NS_LOG_V(DEBUG, "curr->topicName = %s", curr->topicName);\r
+\r
             NSTopicLL * topicIter = topics;\r
             while(topicIter)\r
             {\r
@@ -563,29 +563,6 @@ NSTopicLL * NSProviderGetConsumerTopicsCacheData(NSCacheList * regTopicList,
     return topics;\r
 }\r
 \r
-size_t NSProviderGetListSize(NSCacheElement * firstElement)\r
-{\r
-    pthread_mutex_lock(&NSCacheMutex);\r
-    if(!firstElement)\r
-    {\r
-        pthread_mutex_unlock(&NSCacheMutex);\r
-        return 0;\r
-    }\r
-\r
-    int cnt = 0;\r
-\r
-    NSCacheElement * iter = firstElement;\r
-\r
-    while(iter)\r
-    {\r
-        cnt++;\r
-        iter = iter->next;\r
-    }\r
-\r
-    pthread_mutex_unlock(&NSCacheMutex);\r
-    return cnt;\r
-}\r
-\r
 bool NSProviderIsTopicSubScribed(NSCacheElement * conTopicList, char * cId, char * topicName)\r
 {\r
     pthread_mutex_lock(&NSCacheMutex);\r
@@ -623,8 +600,8 @@ NSResult NSProviderDeleteConsumerTopic(NSCacheList * conTopicList,
 \r
     if(!conTopicList || !cId || !topicName)\r
     {\r
-        return NS_ERROR;\r
         pthread_mutex_unlock(&NSCacheMutex);\r
+        return NS_ERROR;\r
     }\r
 \r
     NSCacheElement * prev = conTopicList->head;\r
@@ -635,6 +612,7 @@ NSResult NSProviderDeleteConsumerTopic(NSCacheList * conTopicList,
     if(!del)\r
     {\r
         NS_LOG(DEBUG, "list head is NULL");\r
+        pthread_mutex_unlock(&NSCacheMutex);\r
         return NS_FAIL;\r
     }\r
 \r
index 830d50f..8f209fc 100644 (file)
@@ -45,9 +45,7 @@ NSResult NSProviderDeleteSubDataFromObId(NSCacheList * list, OCObservationId id)
 NSTopicLL * NSProviderGetTopicsCacheData(NSCacheList * regTopicList);\r
 \r
 NSTopicLL * NSProviderGetConsumerTopicsCacheData(NSCacheList * regTopicList,\r
-        NSCacheList * conTopicList, char *consumerId);\r
-\r
-size_t NSProviderGetListSize(NSCacheElement * firstElement);\r
+        NSCacheList * conTopicList, const char * consumerId);\r
 \r
 bool NSProviderIsTopicSubScribed(NSCacheElement * conTopicList, char * cId, char * topicName);\r
 \r
index 6547e52..c8a8f50 100644 (file)
 
 #include "NSProviderNotification.h"
 
-NSResult NSInitMessageList()
-{
-    NS_LOG(DEBUG, "NSInitMessageList - IN");
-
-    messageList = NSStorageCreate();
-    messageList->cacheType = NS_PROVIDER_CACHE_MESSAGE;
-
-    NS_LOG(DEBUG, "NSInitMessageList - OUT");
-    return NS_OK;
-}
-
 NSResult NSSetMessagePayload(NSMessage *msg, OCRepPayload** msgPayload)
 {
     NS_LOG(DEBUG, "NSSetMessagePayload - IN");
@@ -54,6 +43,11 @@ NSResult NSSetMessagePayload(NSMessage *msg, OCRepPayload** msgPayload)
     NSDuplicateSetPropertyString(msgPayload, NS_ATTRIBUTE_TEXT, msg->contentText);
     NSDuplicateSetPropertyString(msgPayload, NS_ATTRIBUTE_SOURCE, msg->sourceName);
     NSDuplicateSetPropertyString(msgPayload, NS_ATTRIBUTE_TOPIC_NAME, msg->topic);
+    if(msg->mediaContents)
+    {
+        NSDuplicateSetPropertyString(msgPayload,
+                NS_ATTRIBUTE_ICON_IMAGE, msg->mediaContents->iconImage);
+    }
 
     NS_LOG(DEBUG, "NSSetMessagePayload - OUT");
     return NS_OK;
@@ -125,7 +119,7 @@ NSResult NSSendNotification(NSMessage *msg)
         {
             if(subData->messageObId != 0)
             {
-                if(msg->topic)
+                if(msg->topic && (msg->topic)[0] != '\0')
                 {
                     NS_LOG_V(DEBUG, "this is topic message: %s", msg->topic);
 
@@ -140,10 +134,10 @@ NSResult NSSendNotification(NSMessage *msg)
                 }
             }
 
-#ifdef RD_CLIENT
+#if(defined WITH_CLOUD && defined RD_CLIENT)
             if(subData->remote_messageObId != 0)
             {
-                if(msg->topic)
+                if(msg->topic && (msg->topic)[0] != '\0')
                 {
                     NS_LOG_V(DEBUG, "this is topic message via remote server: %s", msg->topic);
                     if(NSProviderIsTopicSubScribed(consumerTopicList->head, subData->id, msg->topic))
@@ -228,7 +222,7 @@ NSResult NSSendSync(NSSyncInfo *sync)
                 obArray[obCount++] = subData->syncObId;
             }
 
-#ifdef RD_CLIENT
+#if(defined WITH_CLOUD && defined RD_CLIENT)
             if(subData->remote_syncObId != 0)
             {
                 obArray[obCount++] = subData->remote_syncObId;
index d8b19d0..e78abb7 100644 (file)
@@ -32,9 +32,6 @@
 #include "oic_malloc.h"\r
 #include "NSUtil.h"\r
 \r
-NSCacheList * messageList;\r
-\r
 NSResult NSRegisterResource();\r
-NSResult NSInitMessageList();\r
 \r
 #endif /* _NS_PROVIDER_NOTIFICATION_H_ */\r
index fa26e0f..a056d68 100644 (file)
@@ -26,7 +26,7 @@ NSMessageResource NotificationMessageResource;
 NSSyncResource NotificationSyncResource;
 NSTopicResource NotificationTopicResource;
 
-#ifdef RD_CLIENT
+#if(defined WITH_CLOUD && defined RD_CLIENT)
 #define DEFAULT_CONTEXT_VALUE 0x99
 
 OCStackApplicationResult NSHandlePublishCb(void *ctx, OCDoHandle handle,
@@ -80,10 +80,12 @@ NSResult NSCreateResource(char *uri)
 
     if (strcmp(uri, NS_ROOT_URI) == 0)
     {
-        NotificationResource.accepter = 0;
+        NotificationResource.policy = true;
+        (NotificationResource.providerId)[0] = '\0';
         NotificationResource.message_uri = NS_COLLECTION_MESSAGE_URI;
         NotificationResource.sync_uri = NS_COLLECTION_SYNC_URI;
         NotificationResource.topic_uri = NS_COLLECTION_TOPIC_URI;
+        NotificationResource.version = VERSION;
         NotificationResource.handle = NULL;
 
         if (OCCreateResource(&NotificationResource.handle, NS_ROOT_TYPE, NS_DEFAULT_INTERFACE,
@@ -105,6 +107,7 @@ NSResult NSCreateResource(char *uri)
         NotificationMessageResource.title = NULL;
         NotificationMessageResource.contentText = NULL;
         NotificationMessageResource.sourceName = NULL;
+        NotificationMessageResource.topicName = NULL;
         NotificationMessageResource.mediaContents = NULL;
 
         if (OCCreateResource(&NotificationMessageResource.handle, NS_COLLECTION_MESSAGE_TYPE,
@@ -118,6 +121,7 @@ NSResult NSCreateResource(char *uri)
     else if (strcmp(uri, NS_COLLECTION_SYNC_URI) == 0)
     {
         NotificationSyncResource.id = NULL;
+        (NotificationSyncResource.providerId)[0] = '\0';
         NotificationSyncResource.state = NULL;
         NotificationSyncResource.handle = NULL;
 
@@ -131,6 +135,7 @@ NSResult NSCreateResource(char *uri)
     }
     else if (strcmp(uri, NS_COLLECTION_TOPIC_URI) == 0)
     {
+        (NotificationTopicResource.providerId)[0] = '\0';
         (NotificationTopicResource.consumerId)[0] = '\0';
         NotificationTopicResource.TopicList = NULL;
         NotificationTopicResource.handle = NULL;
@@ -157,29 +162,14 @@ NSResult NSRegisterResource()
 {
     NS_LOG(DEBUG, "NSRegisterResource - IN");
 
-    if (NSCreateResource(NS_COLLECTION_TOPIC_URI) != NS_OK)
-    {
-        NS_LOG(ERROR, "Fail to register Topic Resource");
-        return NS_ERROR;
-    }
-
-    if (NSCreateResource(NS_COLLECTION_SYNC_URI) != NS_OK)
-    {
-        NS_LOG(ERROR, "Fail to register Sync Resource");
-        return NS_ERROR;
-    }
-
-    if (NSCreateResource(NS_COLLECTION_MESSAGE_URI) != NS_OK)
-    {
-        NS_LOG(ERROR, "Fail to register Message Resource");
-        return NS_ERROR;
-    }
-
-    if (NSCreateResource(NS_ROOT_URI) != NS_OK)
-    {
-        NS_LOG(ERROR, "Fail to register Notification Resource");
-        return NS_ERROR;
-    }
+    NS_CREATE_RESOURCE(
+            NSCreateResource(NS_COLLECTION_TOPIC_URI), "Fail to register Topic Resource");
+    NS_CREATE_RESOURCE(
+            NSCreateResource(NS_COLLECTION_SYNC_URI), "Fail to register Sync Resource");
+    NS_CREATE_RESOURCE(
+            NSCreateResource(NS_COLLECTION_MESSAGE_URI), "Fail to register Message Resource");
+    NS_CREATE_RESOURCE(
+            NSCreateResource(NS_ROOT_URI), "Fail to register Notification Resource");
 
     NS_LOG(DEBUG, "NSRegisterResource - OUT");
     return NS_OK;
@@ -189,29 +179,14 @@ NSResult NSUnRegisterResource()
 {
     NS_LOG(DEBUG, "NSUnRegisterResource - IN");
 
-    if (OCDeleteResource(NotificationResource.handle) != OC_STACK_OK)
-    {
-        NS_LOG(ERROR, "Fail to Delete Notification Resource");
-        return NS_ERROR;
-    }
-
-    if (OCDeleteResource(NotificationMessageResource.handle) != OC_STACK_OK)
-    {
-        NS_LOG(ERROR, "Fail to Delete Notification Message Resource");
-        return NS_ERROR;
-    }
-
-    if (OCDeleteResource(NotificationSyncResource.handle) != OC_STACK_OK)
-    {
-        NS_LOG(ERROR, "Fail to Delete Notification Sync Resource");
-        return NS_ERROR;
-    }
-
-    if (OCDeleteResource(NotificationTopicResource.handle) != OC_STACK_OK)
-    {
-        NS_LOG(ERROR, "Fail to Delete Notification Topic Resource");
-        return NS_ERROR;
-    }
+    NS_DELETE_RESOURCE(
+            OCDeleteResource(NotificationResource.handle), "Fail to Delete Notification Resource");
+    NS_DELETE_RESOURCE(OCDeleteResource(NotificationMessageResource.handle),
+            "Fail to Delete Notification Message Resource");
+    NS_DELETE_RESOURCE(OCDeleteResource(NotificationSyncResource.handle),
+            "Fail to Delete Notification Sync Resource");
+    NS_DELETE_RESOURCE(OCDeleteResource(NotificationTopicResource.handle),
+            "Fail to Delete Notification Topic Resource");
 
     NotificationResource.handle = NULL;
     NotificationMessageResource.handle = NULL;
@@ -222,14 +197,17 @@ NSResult NSUnRegisterResource()
     return NS_OK;
 }
 
-NSResult NSPutNotificationResource(int accepter, OCResourceHandle * handle)
+NSResult NSPutNotificationResource(bool policy, OCResourceHandle * handle)
 {
     NS_LOG(DEBUG, "NSPutNotificationResource - IN");
 
-    NotificationResource.accepter = accepter;
+    NotificationResource.policy = policy;
+    OICStrcpy(NotificationResource.providerId, UUID_STRING_SIZE,
+        NSGetProviderInfo()->providerId);
     NotificationResource.message_uri = NS_COLLECTION_MESSAGE_URI;
     NotificationResource.sync_uri = NS_COLLECTION_SYNC_URI;
     NotificationResource.topic_uri = NS_COLLECTION_TOPIC_URI;
+    NotificationResource.version = VERSION;
 
     *handle = NotificationResource.handle;
 
@@ -253,6 +231,7 @@ NSResult NSPutMessageResource(NSMessage *msg, OCResourceHandle * handle)
         NotificationMessageResource.title = msg->title;
         NotificationMessageResource.contentText = msg->contentText;
         NotificationMessageResource.sourceName = msg->sourceName;
+        NotificationMessageResource.topicName = msg->topic;
         NotificationMessageResource.mediaContents = msg->mediaContents;
     }
     else
@@ -261,8 +240,8 @@ NSResult NSPutMessageResource(NSMessage *msg, OCResourceHandle * handle)
     }
 
     *handle = NotificationMessageResource.handle;
-    NS_LOG(DEBUG, "NSPutMessageResource - OUT");
 
+    NS_LOG(DEBUG, "NSPutMessageResource - OUT");
     return NS_OK;
 }
 
index 3e273b9..b5bc6de 100644 (file)
 #include "oic_malloc.h"
 #include "oic_string.h"
 
+#define NS_CREATE_RESOURCE(func, obj) \
+    { \
+        NSResult _ret = (func); \
+        if ( _ret != NS_OK) \
+        { \
+            NS_LOG_V(ERROR, "%s : %s", __func__, #obj); \
+            return (NS_ERROR); \
+        } \
+    }
+
+#define NS_DELETE_RESOURCE(func, obj) \
+    { \
+        OCStackResult _ret = (func); \
+        if ( _ret != OC_STACK_OK) \
+        { \
+            NS_LOG_V(ERROR, "%s : %s", __func__, #obj); \
+            return (NS_ERROR); \
+        } \
+    }
+
 NSResult NSCreateResource(char *uri);
 
 NSResult NSPublishResourceToCloud(char *host);
@@ -36,7 +56,7 @@ NSResult NSRegisterResource();
 
 NSResult NSUnRegisterResource();
 
-NSResult NSPutNotificationResource(int accepter, OCResourceHandle * handle);
+NSResult NSPutNotificationResource(bool policy, OCResourceHandle * handle);
 
 NSResult NSPutMessageResource(NSMessage *msg, OCResourceHandle * handle);
 
index 17a0f3b..375a05e 100644 (file)
@@ -81,7 +81,8 @@ NSResult NSSendAccessPolicyResponse(OCEntityHandlerRequest *entityHandlerRequest
 \r
     OCRepPayloadSetUri(payload, NS_ROOT_URI);\r
     OCRepPayloadSetPropString(payload, NS_ATTRIBUTE_PROVIDER_ID, NSGetProviderInfo()->providerId);\r
-    OCRepPayloadSetPropInt(payload, NS_ATTRIBUTE_POLICY, NSGetPolicy());\r
+    OCRepPayloadSetPropString(payload, NS_ATTRIBUTE_VERSION, VERSION);\r
+    OCRepPayloadSetPropBool(payload, NS_ATTRIBUTE_POLICY, NSGetPolicy());\r
     OCRepPayloadSetPropString(payload, NS_ATTRIBUTE_MESSAGE, NS_COLLECTION_MESSAGE_URI);\r
     OCRepPayloadSetPropString(payload, NS_ATTRIBUTE_SYNC, NS_COLLECTION_SYNC_URI);\r
     OCRepPayloadSetPropString(payload, NS_ATTRIBUTE_TOPIC, NS_COLLECTION_TOPIC_URI);\r
@@ -134,7 +135,7 @@ void NSHandleSubscription(OCEntityHandlerRequest *entityHandlerRequest, NSResour
 \r
         bool iSRemoteServer = false;\r
 \r
-#ifdef RD_CLIEND\r
+#if(defined WITH_CLOUD && defined RD_CLIENT)\r
         iSRemoteServer = NSIsRemoteServerAddress(entityHandlerRequest->devAddr.addr);\r
         if(iSRemoteServer)\r
         {\r
@@ -190,7 +191,7 @@ void NSHandleSubscription(OCEntityHandlerRequest *entityHandlerRequest, NSResour
         subData->remote_syncObId = subData->syncObId = 0;\r
         bool isRemoteServer = false;\r
 \r
-#ifdef RD_CLIENT\r
+#if(defined WITH_CLOUD && defined RD_CLIENT)\r
         isRemoteServer = NSIsRemoteServerAddress(entityHandlerRequest->devAddr.addr);\r
         if(isRemoteServer)\r
         {\r
@@ -231,7 +232,7 @@ void NSHandleUnsubscription(OCEntityHandlerRequest *entityHandlerRequest)
 \r
     consumerSubList->cacheType = NS_PROVIDER_CACHE_SUBSCRIBER_OBSERVE_ID;\r
 \r
-    while(NSStorageDelete(consumerSubList, (unsigned char *)\r
+    while(NSStorageDelete(consumerSubList, (char *)\r
             &(entityHandlerRequest->obsInfo.obsId)) != NS_FAIL);\r
     consumerSubList->cacheType = NS_PROVIDER_CACHE_SUBSCRIBER;\r
 \r
@@ -359,21 +360,21 @@ void * NSSubScriptionSchedule(void *ptr)
                 case TASK_SEND_ALLOW:\r
                 {\r
                     NS_LOG(DEBUG, "CASE TASK_SEND_ALLOW : ");\r
-                    NSConsumer * consumer = (NSConsumer *) node->taskData;\r
+                    char * consumerId = (char *) node->taskData;\r
 \r
-                    NSCacheUpdateSubScriptionState(consumerSubList, consumer->consumerId, true);\r
-                    NSSendResponse(consumer->consumerId, true);\r
-                    NSFreeConsumer(consumer);\r
+                    NSCacheUpdateSubScriptionState(consumerSubList, consumerId, true);\r
+                    NSSendResponse(consumerId, true);\r
+                    OICFree(consumerId);\r
                     break;\r
                 }\r
                 case TASK_SEND_DENY:\r
                 {\r
                     NS_LOG(DEBUG, "CASE TASK_SEND_DENY : ");\r
-                    NSConsumer * consumer = (NSConsumer *) node->taskData;\r
+                    char * consumerId = (char *) node->taskData;\r
 \r
-                    NSCacheUpdateSubScriptionState(consumerSubList, consumer->consumerId, false);\r
-                    NSSendResponse(consumer->consumerId, false);\r
-                    NSFreeConsumer(consumer);\r
+                    NSCacheUpdateSubScriptionState(consumerSubList, consumerId, false);\r
+                    NSSendResponse(consumerId, false);\r
+                    OICFree(consumerId);\r
 \r
                     break;\r
                 }\r
index 9813250..f17883f 100644 (file)
 #include "NSProviderSystem.h"\r
 #include "oic_string.h"\r
 #include "oic_malloc.h"\r
+#include <stdbool.h>\r
 \r
 NSCacheList * consumerSubList;\r
 \r
 NSResult NSInitSubscriptionList();\r
 NSResult NSSetSubscriptionAccessPolicy(bool policy);\r
-bool NSGetPolicy();\r
 NSResult NSSendAccessPolicyResponse(OCEntityHandlerRequest *entityHandlerRequest);\r
 void NSHandleSubscription(OCEntityHandlerRequest *entityHandlerRequest, NSResourceType resourceType);\r
 void NSHandleUnsubscription(OCEntityHandlerRequest *entityHandlerRequest);\r
index a3eef6f..deeb4c5 100644 (file)
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
 #include "NSProviderSystem.h"\r
 \r
+#if(defined WITH_CLOUD && defined RD_CLIENT)\r
 #define MAX_SERVER_ADDRESS 32\r
-static NSConnectionState NSProviderConnectionState;\r
-\r
-#ifdef RD_CLIENT\r
 static char NSRemoteServerAddress[MAX_SERVER_ADDRESS] = {0,};\r
 #endif\r
 \r
+static NSConnectionState NSProviderConnectionState;\r
+\r
 NSProviderInfo * providerInfo;\r
 bool NSPolicy = true;\r
 \r
@@ -43,7 +43,7 @@ NSConnectionState NSGetProviderConnectionState()
     return NSProviderConnectionState;\r
 }\r
 \r
-#ifdef RD_CLIENT\r
+#if(defined WITH_CLOUD && defined RD_CLIENT)\r
 void NSSetRemoteServerAddress(char *serverAddress)\r
 {\r
 \r
index 4860bb4..a799a70 100644 (file)
@@ -36,5 +36,7 @@ void NSInitProviderInfo(const char * userInfo);
 void NSDeinitProviderInfo();\r
 NSProviderInfo * NSGetProviderInfo();\r
 const char * NSGetUserInfo();\r
+bool NSGetPolicy();\r
+void NSSetPolicy(bool policy);\r
 \r
 #endif /* _NS_PROVIDER_SYSTEM__H_ */\r
index 015895f..6ba5094 100644 (file)
@@ -21,6 +21,7 @@
 #include "NSProviderTopic.h"\r
 #include "oic_string.h"\r
 #include "oic_malloc.h"\r
+#include <pthread.h>\r
 \r
 NSResult NSSendTopicUpdation();\r
 \r
@@ -37,12 +38,32 @@ NSResult NSInitTopicList()
     return NS_OK;\r
 }\r
 \r
+size_t NSProviderGetTopicListSize(NSTopicLL * firstElement)\r
+{\r
+    if(!firstElement)\r
+    {\r
+        return 0;\r
+    }\r
+\r
+    int cnt = 0;\r
+\r
+    NSTopicLL * iter = firstElement;\r
+\r
+    while(iter)\r
+    {\r
+        cnt++;\r
+        iter = iter->next;\r
+    }\r
+\r
+    return cnt;\r
+}\r
+\r
 NSResult NSAddTopics(const char * topicName)\r
 {\r
     NS_LOG(DEBUG, "NSWriteTopicsToStorage()");\r
 \r
     NSCacheTopicData * data = (NSCacheTopicData *)OICMalloc(sizeof(NSCacheTopicData));\r
-    data->topicName = topicName;\r
+    data->topicName = (char *)topicName;\r
     data->state = NS_TOPIC_UNSUBSCRIBED;\r
 \r
     NSCacheElement * element = (NSCacheElement *) OICMalloc(sizeof(NSCacheElement));\r
@@ -52,6 +73,7 @@ NSResult NSAddTopics(const char * topicName)
     if(NSStorageWrite(registeredTopicList, element) != NS_OK)\r
     {\r
         NS_LOG(DEBUG, "fail to write cache");\r
+        return NS_ERROR;\r
     }\r
     NSSendTopicUpdation();\r
 \r
@@ -113,13 +135,12 @@ NSResult NSSendTopicUpdation()
                 obArray[obCount++] = subData->messageObId;\r
             }\r
 \r
-#ifdef RD_CLIENT\r
+#if(defined WITH_CLOUD && defined RD_CLIENT)\r
             if(subData->remote_messageObId != 0)\r
             {\r
                 obArray[obCount++] = subData->remote_messageObId;\r
             }\r
 #endif\r
-\r
         }\r
         it = it->next;\r
     }\r
@@ -198,25 +219,20 @@ NSResult NSSendTopicList(OCEntityHandlerRequest * entityHandlerRequest)
 \r
     char * id = NSGetValueFromQuery(OICStrdup(entityHandlerRequest->query), NS_QUERY_CONSUMER_ID);\r
     NSTopicLL * topics = NULL;\r
-    NSCacheElement * currList = NULL;\r
 \r
     if(!id)\r
     {\r
         NS_LOG(DEBUG, "Send registered topic list");\r
         topics = NSProviderGetTopicsCacheData(registeredTopicList);\r
-        currList = registeredTopicList->head;\r
     }\r
     else\r
     {\r
         NS_LOG(DEBUG, "Send subscribed topic list to consumer");\r
         topics = NSProviderGetConsumerTopicsCacheData(registeredTopicList, consumerTopicList, id);\r
-        currList = consumerTopicList->head;\r
-    }\r
-\r
-    if(!currList)\r
-    {\r
-        NS_LOG(DEBUG, "currList is NULL");\r
-        return NS_ERROR;\r
+        if(!topics)\r
+        {\r
+            topics = NSProviderGetTopicsCacheData(registeredTopicList);\r
+        }\r
     }\r
 \r
     // make response for the Get Request\r
@@ -233,44 +249,56 @@ NSResult NSSendTopicList(OCEntityHandlerRequest * entityHandlerRequest)
         return NS_ERROR;\r
     }\r
 \r
-    // set topics to the array of resource property\r
+    OCRepPayloadSetUri(payload, NS_COLLECTION_TOPIC_URI);\r
+    if(id)\r
+    {\r
+        OCRepPayloadSetPropString(payload, NS_ATTRIBUTE_CONSUMER_ID, id);\r
+    }\r
+    OCRepPayloadSetPropString(payload, NS_ATTRIBUTE_PROVIDER_ID,\r
+        NSGetProviderInfo()->providerId);\r
 \r
-    NSCacheElement * iter = currList;\r
-    size_t dimensionSize = (size_t)NSProviderGetListSize(iter);\r
+    if(topics)\r
+    {\r
+        NS_LOG(DEBUG, "topicList is NULL");\r
+        size_t dimensionSize = (size_t)NSProviderGetTopicListSize(topics);\r
 \r
-    NS_LOG_V(DEBUG, "dimensionSize = %d", dimensionSize);\r
+        NS_LOG_V(DEBUG, "dimensionSize = %d", (int)dimensionSize);\r
 \r
-    if(!dimensionSize)\r
-    {\r
-        return NS_ERROR;\r
-    }\r
+        if(!dimensionSize)\r
+        {\r
+            return NS_ERROR;\r
+        }\r
 \r
-    OCRepPayload** payloadTopicArray = (OCRepPayload **) OICMalloc(\r
-            sizeof(OCRepPayload *) * dimensionSize);\r
+        OCRepPayload** payloadTopicArray = (OCRepPayload **) OICMalloc(\r
+                sizeof(OCRepPayload *) * dimensionSize);\r
 \r
-    size_t dimensions[3] = {dimensionSize, 0, 0};\r
-    for (int i = 0; i < (int)dimensionSize; i++)\r
-    {\r
-        NSTopicLL * topic = (NSTopicLL *) iter->data;\r
+        size_t dimensions[3] = {dimensionSize, 0, 0};\r
 \r
-        NS_LOG_V(DEBUG, "topicName = %s", topic->topicName);\r
-        NS_LOG_V(DEBUG, "topicState = %d",(int) topic->state);\r
+        for (int i = 0; i < (int)dimensionSize; i++)\r
+        {\r
+            NS_LOG_V(DEBUG, "topicName = %s", topics->topicName);\r
+            NS_LOG_V(DEBUG, "topicState = %d",(int) topics->state);\r
 \r
-        payloadTopicArray[i] = OCRepPayloadCreate();\r
-        OCRepPayloadSetPropString(payloadTopicArray[i], NS_ATTRIBUTE_TOPIC_NAME, topic->topicName);\r
-        OCRepPayloadSetPropInt(payloadTopicArray[i], NS_ATTRIBUTE_TOPIC_SELECTION,\r
-                (int)topic->state);\r
+            payloadTopicArray[i] = OCRepPayloadCreate();\r
+            OCRepPayloadSetPropString(payloadTopicArray[i], NS_ATTRIBUTE_TOPIC_NAME,\r
+                    topics->topicName);\r
+            OCRepPayloadSetPropInt(payloadTopicArray[i], NS_ATTRIBUTE_TOPIC_SELECTION,\r
+                    (int)topics->state);\r
 \r
-        iter = iter->next;\r
-    }\r
+            topics = topics->next;\r
+        }\r
 \r
-    OCRepPayloadSetUri(payload, NS_COLLECTION_TOPIC_URI);\r
-    if(id)\r
+\r
+        OCRepPayloadSetPropObjectArray(payload, NS_ATTRIBUTE_TOPIC_LIST,\r
+                (const OCRepPayload**)(payloadTopicArray), dimensions);\r
+    }\r
+    else\r
     {\r
-        OCRepPayloadSetPropString(payload, NS_ATTRIBUTE_CONSUMER_ID, id);\r
+        size_t dimensions[3] = {0, 0, 0};\r
+\r
+        OCRepPayloadSetPropObjectArrayAsOwner(payload, NS_ATTRIBUTE_TOPIC_LIST,\r
+                (OCRepPayload **) NULL, dimensions);\r
     }\r
-    OCRepPayloadSetPropObjectArray(payload, NS_ATTRIBUTE_TOPIC_LIST,\r
-            (const OCRepPayload**)(payloadTopicArray), dimensions);\r
 \r
     response.requestHandle = entityHandlerRequest->requestHandle;\r
     response.resourceHandle = entityHandlerRequest->resource;\r
@@ -294,7 +322,7 @@ NSResult NSPostConsumerTopics(OCEntityHandlerRequest * entityHandlerRequest)
     NS_LOG(DEBUG, "NSPostConsumerTopics() - IN");\r
 \r
     char * consumerId = NULL;\r
-    OCRepPayload * payload = entityHandlerRequest->payload;\r
+    OCRepPayload * payload = (OCRepPayload *) entityHandlerRequest->payload;\r
     OCRepPayloadGetPropString(payload, NS_ATTRIBUTE_CONSUMER_ID, &consumerId);\r
 \r
     if(!consumerId)\r
@@ -323,7 +351,7 @@ NSResult NSPostConsumerTopics(OCEntityHandlerRequest * entityHandlerRequest)
 \r
         OCRepPayloadGetPropString(topicListPayload[i], NS_ATTRIBUTE_TOPIC_NAME, &topicName);\r
         OCRepPayloadGetPropInt(topicListPayload[i], NS_ATTRIBUTE_TOPIC_SELECTION, &topicState);\r
-        NS_LOG_V(DEBUG, "Topic Name(state):  %s(%d)", topicName, topicState);\r
+        NS_LOG_V(DEBUG, "Topic Name(state):  %s(%d)", topicName, (int)topicState);\r
 \r
         if(NS_TOPIC_SUBSCRIBED == (NSTopicState)topicState)\r
         {\r
@@ -336,9 +364,11 @@ NSResult NSPostConsumerTopics(OCEntityHandlerRequest * entityHandlerRequest)
             NSCacheElement * newObj = (NSCacheElement *) OICMalloc(sizeof(NSCacheElement));\r
             newObj->data = (NSCacheData *) topicSubData;\r
             newObj->next = NULL;\r
+\r
             NSStorageWrite(consumerTopicList, newObj);\r
         }\r
     }\r
+    NSSendTopicUpdationToConsumer(consumerId);\r
 \r
     NS_LOG(DEBUG, "NSPostConsumerTopics() - OUT");\r
     return NS_OK;\r
@@ -374,6 +404,8 @@ void * NSTopicSchedule(void * ptr)
                     newObj->data = node->taskData;\r
                     newObj->next = NULL;\r
                     NSStorageWrite(consumerTopicList, newObj);\r
+                    NSCacheTopicSubData * topicSubData = (NSCacheTopicSubData *) node->taskData;\r
+                    NSSendTopicUpdationToConsumer(topicSubData->id);\r
                     break;\r
                 case TASK_UNSUBSCRIBE_TOPIC:\r
                     NS_LOG(DEBUG, "CASE TASK_SUBSCRIBE_TOPIC : ");\r
@@ -400,6 +432,25 @@ void * NSTopicSchedule(void * ptr)
                     NSFreeOCEntityHandlerRequest((OCEntityHandlerRequest*) node->taskData);\r
                 }\r
                     break;\r
+                case TASK_GET_TOPICS:\r
+                {\r
+                    NS_LOG(DEBUG, "TASK_GET_TOPICS : ");\r
+                    NSTopicSynchronization * topicData = (NSTopicSynchronization *) node->taskData;\r
+                    NSTopicLL * topics = NSProviderGetTopicsCacheData(registeredTopicList);\r
+                    topicData->topics = topics;\r
+                    pthread_cond_signal(&topicData->condition);\r
+                }\r
+                    break;\r
+                case TAST_GET_CONSUMER_TOPICS:\r
+                {\r
+                    NS_LOG(DEBUG, "TASK_GET_CONSUMER_TOPICS : ");\r
+                    NSTopicSynchronization * topicData = (NSTopicSynchronization *) node->taskData;\r
+                    NSTopicLL * topics = NSProviderGetConsumerTopicsCacheData(registeredTopicList,\r
+                                consumerTopicList, topicData->consumerId);\r
+                    topicData->topics = topics;\r
+                    pthread_cond_signal(&topicData->condition);\r
+                }\r
+                    break;\r
                 default:\r
                     break;\r
             }\r
index 20e416e..e14a8bf 100644 (file)
 #include "NSProviderResource.h"\r
 #include "NSProviderSubscription.h"\r
 \r
+typedef struct {\r
+    pthread_cond_t condition;\r
+    char * consumerId;\r
+    NSTopicLL * topics;\r
+} NSTopicSynchronization;\r
+\r
 NSCacheList * consumerTopicList;\r
 NSCacheList * registeredTopicList;\r
 \r
index 64522e2..1c87c07 100644 (file)
@@ -35,6 +35,7 @@ private:
 
     std::shared_ptr<OC::OCResource> m_syncResource;
     std::shared_ptr<OC::OCResource> m_msgResource;
+    std::shared_ptr<OC::OCResource> m_topicResource;
 
 public:
     NSConsumerSimulator()
@@ -103,8 +104,8 @@ private:
         {
             resource->get(OC::QueryParamsMap(),
                     std::bind(&NSConsumerSimulator::onGet, this,
-                            std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, resource),
-                    OC::QualityOfService::LowQos);
+                            std::placeholders::_1, std::placeholders::_2, std::placeholders::_3,
+                            resource), OC::QualityOfService::LowQos);
         }
     }
     void onGet(const OC::HeaderOptions &/*headerOption*/,
@@ -114,15 +115,19 @@ private:
         std::cout << __func__ << " " << rep.getHost() << " result : " << eCode << std::endl;
 
         OC::QueryParamsMap map;
-        map.insert(std::pair<std::string,std::string>(std::string("consumerid"), std::string("123456789012345678901234567890123456")));
+        map.insert(std::pair<std::string,std::string>(std::string("consumerid"),
+                std::string("123456789012345678901234567890123456")));
 
         try
         {
             std::cout << "resourc : host " << resource->host() << std::endl;
             std::cout << "resourc : uri " << resource->uri() << std::endl;
-            std::cout << " resource->connectivityType() " <<  resource->connectivityType() << std::endl;
-            std::cout << "resourc : getResourceInterfaces " << resource->getResourceInterfaces()[0] << std::endl;
-            std::cout << "resourc : getResourceTypes " << resource->getResourceTypes()[0] << std::endl;
+            std::cout << " resource->connectivityType() "
+                    <<  resource->connectivityType() << std::endl;
+            std::cout << "resourc : getResourceInterfaces "
+                    << resource->getResourceInterfaces()[0] << std::endl;
+            std::cout << "resourc : getResourceTypes "
+                    << resource->getResourceTypes()[0] << std::endl;
 
             std::vector<std::string> rts{"oic.r.notification"};
 
@@ -153,6 +158,12 @@ private:
                         std::placeholders::_3, std::placeholders::_4, resource),
                 OC::QualityOfService::LowQos);
 
+
+        m_topicResource
+            = OC::OCPlatform::constructResourceObject(resource->host(), resource->uri() + "/topic",
+                    resource->connectivityType(), true, resource->getResourceTypes(),
+                    resource->getResourceInterfaces());
+
     }
     void onObserve(const OC::HeaderOptions &/*headerOption*/,
             const OC::OCRepresentation &rep , const int &eCode, const int &,
@@ -171,6 +182,14 @@ private:
                           std::string(rep.getValueToString("TITLE")),
                           std::string(rep.getValueToString("CONTENT")),
                           std::string(rep.getValueToString("SOURCE")));
+
+            if(rep.getValue<int>("MESSAGE_ID") == 3)
+            {
+                m_topicResource->get(OC::QueryParamsMap(),
+                        std::bind(&NSConsumerSimulator::onTopicGet, this, std::placeholders::_1,
+                                std::placeholders::_2, std::placeholders::_3, m_topicResource),
+                                OC::QualityOfService::LowQos);
+            }
         }
         else if (rep.getUri() == "/notification/sync")
         {
@@ -179,6 +198,17 @@ private:
         }
     }
 
+    void onTopicGet(const OC::HeaderOptions &/*headerOption*/,
+            const OC::OCRepresentation & rep , const int eCode,
+            std::shared_ptr<OC::OCResource> resource)
+    {
+        //TO-DO using this function.
+        (void) rep;
+        (void) eCode;
+        (void) resource;
+        std::cout << "onTopicGet()" << std::endl;
+    }
+
     OCStackResult msgResourceCancelObserve(OC::QualityOfService qos)
     {
         return m_msgResource->cancelObserve(qos);
index d60d7d8..8eb2153 100644 (file)
@@ -51,6 +51,9 @@ namespace
         NS_SELECTION_PROVIDER = 1
     };
 
+    NSConsumerConfig cfg;
+
+    NSProviderSimulator::NS_TopicStateList g_topicStateList;
 }
 
 class TestWithMock: public testing::Test
@@ -84,11 +87,6 @@ public:
     NotificationConsumerTest() = default;
     ~NotificationConsumerTest() = default;
 
-    static void NSProviderDiscoveredCallbackEmpty(NSProvider *)
-    {
-        std::cout << __func__ << std::endl;
-    }
-
     static void NSNotificationReceivedCallbackEmpty(NSMessage *)
     {
         std::cout << __func__ << std::endl;
@@ -104,7 +102,7 @@ public:
         std::cout << __func__ << std::endl;
     }
 
-    static void NSProviderChangedCallback(NSProvider *,  NSResponse)
+    static void NSProviderChangedCallback(NSProvider *,  NSProviderState)
     {
         std::cout << __func__ << std::endl;
     }
@@ -117,7 +115,7 @@ protected:
 
         if (g_isStartedStack == false)
         {
-            OC::PlatformConfig cfg
+            OC::PlatformConfig occfg
             {
                 OC::ServiceType::InProc,
                 OC::ModeType::Both,
@@ -125,7 +123,7 @@ protected:
                 0,
                 OC::QualityOfService::LowQos
             };
-            OC::OCPlatform::Configure(cfg);
+            OC::OCPlatform::Configure(occfg);
 
             try
             {
@@ -137,6 +135,10 @@ protected:
             }
 
             g_isStartedStack = true;
+
+            cfg.changedCb = NSProviderChangedCallback;
+            cfg.messageCb = NSNotificationReceivedCallbackEmpty;
+            cfg.syncInfoCb = NSSyncCallbackEmpty;
         }
 
     }
@@ -148,14 +150,48 @@ protected:
 
 };
 
+TEST_F(NotificationConsumerTest, StartConsumerNegativeNonSetChangedCB)
+{
+    cfg.changedCb = NULL;
+    cfg.messageCb = NSNotificationReceivedCallbackEmpty;
+    cfg.syncInfoCb = NSSyncCallbackEmpty;
+
+    EXPECT_EQ(NS_ERROR, NSStartConsumer(cfg));
+    std::unique_lock< std::mutex > lock{ mutexForCondition };
+    responseCon.wait_for(lock, g_waitForResponse);
+}
+
+TEST_F(NotificationConsumerTest, StartConsumerNegativeNonSetNotiReceiveCB)
+{
+    cfg.changedCb = NSProviderChangedCallback;
+    cfg.messageCb = NULL;
+    cfg.syncInfoCb = NSSyncCallbackEmpty;
+
+    EXPECT_EQ(NS_ERROR, NSStartConsumer(cfg));
+    std::unique_lock< std::mutex > lock{ mutexForCondition };
+    responseCon.wait_for(lock, g_waitForResponse);
+}
+
+TEST_F(NotificationConsumerTest, StartConsumerNegativeNonSetSyncCB)
+{
+    cfg.changedCb = NSProviderChangedCallback;
+    cfg.messageCb = NSNotificationReceivedCallbackEmpty;
+    cfg.syncInfoCb = NULL;
+
+    EXPECT_EQ(NS_ERROR, NSStartConsumer(cfg));
+    std::unique_lock< std::mutex > lock{ mutexForCondition };
+    responseCon.wait_for(lock, g_waitForResponse);
+}
+
 TEST_F(NotificationConsumerTest, StartConsumerPositive)
 {
-    NSConsumerConfig cfg;
-    cfg.discoverCb = NSProviderDiscoveredCallbackEmpty;
     cfg.changedCb = NSProviderChangedCallback;
     cfg.messageCb = NSNotificationReceivedCallbackEmpty;
     cfg.syncInfoCb = NSSyncCallbackEmpty;
+
     EXPECT_EQ(NS_OK, NSStartConsumer(cfg));
+    std::unique_lock< std::mutex > lock{ mutexForCondition };
+    responseCon.wait_for(lock, g_waitForResponse);
 }
 
 TEST_F(NotificationConsumerTest, StopConsumerPositive)
@@ -163,20 +199,22 @@ TEST_F(NotificationConsumerTest, StopConsumerPositive)
     EXPECT_EQ(NSStopConsumer(), NS_OK);
 }
 
+TEST_F(NotificationConsumerTest, StopConsumerNegative)
+{
+    EXPECT_EQ(NSStopConsumer(), NS_ERROR);
+}
+
 TEST_F(NotificationConsumerTest, DiscoverProviderWithNonAccepterWhenStartedConsumerFirst)
 {
-    mocks.ExpectCallFunc(NSProviderDiscoveredCallbackEmpty).Do(
-            [this](NSProvider *)
+    NSProviderState revState = NS_STOPPED;
+    mocks.OnCallFunc(NSProviderChangedCallback).Do(
+            [this, & revState](NSProvider *, NSProviderState state)
             {
                 std::cout << "Call Discovered" << std::endl;
+                revState = state;
                 responseCon.notify_all();
             });
 
-    NSConsumerConfig cfg;
-    cfg.discoverCb = NSProviderDiscoveredCallbackEmpty;
-    cfg.changedCb = NSProviderChangedCallback;
-    cfg.messageCb = NSNotificationReceivedCallbackEmpty;
-    cfg.syncInfoCb = NSSyncCallbackEmpty;
     NSStartConsumer(cfg);
 
     g_providerSimul.setAccepter((int)NSSelector::NS_SELECTION_CONSUMER);
@@ -187,6 +225,8 @@ TEST_F(NotificationConsumerTest, DiscoverProviderWithNonAccepterWhenStartedConsu
 
     NSStopConsumer();
     g_providerSimul.deleteNotificationResource();
+
+    EXPECT_EQ(NS_DISCOVERED, revState);
 }
 
 TEST_F(NotificationConsumerTest, DiscoverProviderWithNonAccepterWhenStartedConsumerAfter)
@@ -198,33 +238,34 @@ TEST_F(NotificationConsumerTest, DiscoverProviderWithNonAccepterWhenStartedConsu
         responseCon.wait_for(lock, g_waitForResponse);
     }
 
-    mocks.ExpectCallFunc(NSProviderDiscoveredCallbackEmpty).Do(
-            [this](NSProvider * provider)
+    NSProviderState revState = NS_STOPPED;
+    mocks.OnCallFunc(NSProviderChangedCallback).Do(
+            [this, & revState](NSProvider * provider, NSProviderState state)
             {
                 std::cout << "Call Discovered" << std::endl;
+
                 g_provider = provider;
+                revState = state;
                 responseCon.notify_all();
             });
 
-    NSConsumerConfig cfg;
-    cfg.discoverCb = NSProviderDiscoveredCallbackEmpty;
-    cfg.changedCb = NSProviderChangedCallback;
-    cfg.messageCb = NSNotificationReceivedCallbackEmpty;
-    cfg.syncInfoCb = NSSyncCallbackEmpty;
     NSStartConsumer(cfg);
 
     std::unique_lock< std::mutex > lock{ mutexForCondition };
     responseCon.wait_for(lock, g_waitForResponse);
 
+    EXPECT_EQ(NS_DISCOVERED, revState);
 }
 
 TEST_F(NotificationConsumerTest, DiscoverProviderWithNonAccepterWhenRescan)
 {
     g_providerSimul.setAccepter((int)NSSelector::NS_SELECTION_CONSUMER);
-    mocks.ExpectCallFunc(NSProviderDiscoveredCallbackEmpty).Do(
-            [this](NSProvider * provider)
+    NSProviderState revState = NS_STOPPED;
+    mocks.OnCallFunc(NSProviderChangedCallback).Do(
+            [this, &revState](NSProvider * provider, NSProviderState state)
             {
                 std::cout << "Call Discovered" << std::endl;
+                revState = state;
                 g_provider = provider;
                 std::cout << g_provider->providerId << std::endl;
                 responseCon.notify_all();
@@ -235,21 +276,25 @@ TEST_F(NotificationConsumerTest, DiscoverProviderWithNonAccepterWhenRescan)
     std::unique_lock< std::mutex > lock{ mutexForCondition };
     responseCon.wait_for(lock, g_waitForResponse);
 
-//    NSStopConsumer();
+    EXPECT_EQ(NS_DISCOVERED, revState);
 }
 
 TEST_F(NotificationConsumerTest, ExpectSubscribeSuccess)
 {
-//    mocks.ExpectCallFunc(NSSubscriptionAcceptedCallback).Do(
-//            [](NSProvider * )
-//            {
-//                std::cout << "Income Accepted subscription : " << std::endl;
-//            });
+    NSProviderState revState = NS_DENY;
+    mocks.OnCallFunc(NSProviderChangedCallback).Do(
+            [this, & revState](NSProvider * , NSProviderState state)
+            {
+                std::cout << "Income Changed Callback : " << state << std::endl;
+                revState = state;
+                responseCon.notify_all();
+            });
 
-    NSResult ret = NSSubscribe(g_provider);
+    NSResult ret = NSSubscribe(g_provider->providerId);
     std::unique_lock< std::mutex > lock{ mutexForCondition };
     responseCon.wait_for(lock, g_waitForResponse);
 
+    EXPECT_EQ(NS_ALLOW, revState);
     EXPECT_EQ(NS_OK, ret);
 }
 
@@ -259,10 +304,14 @@ TEST_F(NotificationConsumerTest, ExpectReceiveNotification)
     std::string title = "title";
     std::string msg = "msg";
 
-    mocks.ExpectCallFunc(NSNotificationReceivedCallbackEmpty).Do(
-            [](NSMessage * message)
+    uint64_t revId = 0;
+
+    mocks.OnCallFunc(NSNotificationReceivedCallbackEmpty).Do(
+            [this, & revId](NSMessage * message)
             {
                 std::cout << "Income Notification : " << message->messageId << std::endl;
+                revId = message->messageId;
+                responseCon.notify_all();
             });
 
     g_providerSimul.notifyMessage(id, title, msg);
@@ -270,32 +319,57 @@ TEST_F(NotificationConsumerTest, ExpectReceiveNotification)
     std::unique_lock< std::mutex > lock{ mutexForCondition };
     responseCon.wait_for(lock, g_waitForResponse);
 
+    EXPECT_EQ(id, revId);
     NSStopConsumer();
+    g_providerSimul.deleteNotificationResource();
 }
 
-TEST_F(NotificationConsumerTest, ExpectReceiveNotificationWithAccepterisProvider)
+TEST_F(NotificationConsumerTest, ExpectReceiveSubAllowWithAccepterisProvider)
 {
-    uint64_t id = 11;
-    std::string title = "title";
-    std::string msg = "msg";
-
     g_providerSimul.setAccepter((int)NSSelector::NS_SELECTION_PROVIDER);
-
-    NSConsumerConfig cfg;
-    cfg.discoverCb = NSProviderDiscoveredCallbackEmpty;
-    cfg.changedCb = NSProviderChangedCallback;
-    cfg.messageCb = NSNotificationReceivedCallbackEmpty;
-    cfg.syncInfoCb = NSSyncCallbackEmpty;
-    NSStartConsumer(cfg);
+    NSProviderState revState = NS_DENY;
+    g_providerSimul.createNotificationResource();
     {
         std::unique_lock< std::mutex > lock{ mutexForCondition };
         responseCon.wait_for(lock, g_waitForResponse);
     }
 
-    mocks.ExpectCallFunc(NSNotificationReceivedCallbackEmpty).Do(
-            [](NSMessage * message)
+    mocks.OnCallFunc(NSProviderChangedCallback).Do(
+            [this, & revState](NSProvider * provider, NSProviderState state)
+            {
+                std::cout << "Income Changed Callback : " << state << std::endl;
+                revState = state;
+                g_provider = provider;
+                responseCon.notify_all();
+            });
+    mocks.OnCallFunc(NSProviderChangedCallback).Do(
+            [this, & revState](NSProvider *, NSProviderState state)
+            {
+                std::cout << "Income Changed Callback : " << state << std::endl;
+                revState = state;
+                responseCon.notify_all();
+            });
+
+    NSStartConsumer(cfg);
+    std::unique_lock< std::mutex > lock{ mutexForCondition };
+    responseCon.wait_for(lock, g_waitForResponse);
+
+    EXPECT_EQ(NS_ALLOW, revState);
+}
+
+TEST_F(NotificationConsumerTest, ExpectReceiveNotificationWithAccepterisProvider)
+{
+    uint64_t id = 11;
+    std::string title = "title";
+    std::string msg = "msg";
+    uint64_t revId = 1;
+
+    mocks.OnCallFunc(NSNotificationReceivedCallbackEmpty).Do(
+            [this, & id, & revId](NSMessage * message)
             {
                 std::cout << "Income Notification : " << message->messageId << std::endl;
+                revId = message->messageId;
+                responseCon.notify_all();
             });
 
     g_providerSimul.notifyMessage(id, title, msg);
@@ -303,8 +377,7 @@ TEST_F(NotificationConsumerTest, ExpectReceiveNotificationWithAccepterisProvider
     std::unique_lock< std::mutex > lock{ mutexForCondition };
     responseCon.wait_for(lock, g_waitForResponse);
 
-//    g_providerSimul.deleteNotificationResource();
-//    NSStopConsumer();
+    EXPECT_EQ(id, revId);
 }
 
 TEST_F(NotificationConsumerTest, ExpectCallbackReadCheckWhenProviderNotifySync)
@@ -312,22 +385,22 @@ TEST_F(NotificationConsumerTest, ExpectCallbackReadCheckWhenProviderNotifySync)
     uint64_t id = 12;
     std::string title = "title";
     std::string msg = "msg";
-
     NSSyncType type = NS_SYNC_DELETED;
 
     mocks.OnCallFunc(NSNotificationReceivedCallbackEmpty).Do(
-            [](NSMessage * message)
+            [this](NSMessage * message)
             {
                 std::cout << "Income Notification : " << message->messageId << std::endl;
+                responseCon.notify_all();
             });
 
-    mocks.ExpectCallFunc(NSSyncCallbackEmpty).Do(
-            [& type](NSSyncInfo * sync)
+    mocks.OnCallFunc(NSSyncCallbackEmpty).Do(
+            [& type, this](NSSyncInfo * sync)
             {
                 std::cout << "Income SyncInfo : " << sync->messageId
                         << ", State : " << sync->state << std::endl;
                 type = sync->state;
-
+                responseCon.notify_all();
             });
 
     g_providerSimul.notifyMessage(id, title, msg);
@@ -342,9 +415,6 @@ TEST_F(NotificationConsumerTest, ExpectCallbackReadCheckWhenProviderNotifySync)
         responseCon.wait_for(lock, g_waitForResponse);
     }
 
-//    g_providerSimul.deleteNotificationResource();
-//    NSStopConsumer();
-
     EXPECT_EQ(NS_SYNC_READ, type);
 }
 
@@ -353,22 +423,22 @@ TEST_F(NotificationConsumerTest, ExpectCallbackDismissCheckWhenProviderNotifySyn
     uint64_t id = 13;
     std::string title = "title";
     std::string msg = "msg";
-
     NSSyncType type = NS_SYNC_READ;
 
     mocks.OnCallFunc(NSNotificationReceivedCallbackEmpty).Do(
-            [](NSMessage * message)
+            [this](NSMessage * message)
             {
                 std::cout << "Income Notification : " << message->messageId << std::endl;
+                responseCon.notify_all();
             });
 
-    mocks.ExpectCallFunc(NSSyncCallbackEmpty).Do(
-            [& type](NSSyncInfo * sync)
+    mocks.OnCallFunc(NSSyncCallbackEmpty).Do(
+            [& type, this](NSSyncInfo * sync)
             {
                 std::cout << "Income Notification : " << sync->messageId
                         << ", State : " << sync->state << std::endl;
                 type = sync->state;
-
+                responseCon.notify_all();
             });
 
     g_providerSimul.notifyMessage(id, title, msg);
@@ -383,9 +453,6 @@ TEST_F(NotificationConsumerTest, ExpectCallbackDismissCheckWhenProviderNotifySyn
         responseCon.wait_for(lock, g_waitForResponse);
     }
 
-//    g_providerSimul.deleteNotificationResource();
-//    NSStopConsumer();
-
     EXPECT_EQ(NS_SYNC_DELETED, type);
 }
 
@@ -394,11 +461,10 @@ TEST_F(NotificationConsumerTest, ExpectCallbackReadCheckWhenConsumerPostSync)
     uint64_t id = 14;
     std::string title = "title";
     std::string msg = "msg";
-
     NSSyncType type = NS_SYNC_DELETED;
 
     mocks.OnCallFunc(NSNotificationReceivedCallbackEmpty).Do(
-            [](NSMessage * message)
+            [this](NSMessage * message)
             {
                 std::cout << "Income Notification : " << message->messageId << std::endl;
                 NSConsumerSendSyncInfo(message->providerId, message->messageId, NS_SYNC_READ);
@@ -406,13 +472,13 @@ TEST_F(NotificationConsumerTest, ExpectCallbackReadCheckWhenConsumerPostSync)
                 responseCon.wait_for(lock, g_waitForResponse);
             });
 
-    mocks.ExpectCallFunc(NSSyncCallbackEmpty).Do(
-            [& type](NSSyncInfo * sync)
+    mocks.OnCallFunc(NSSyncCallbackEmpty).Do(
+            [& type, this](NSSyncInfo * sync)
             {
                 std::cout << "Income Notification : " << sync->messageId
                         << ", State : " << sync->state << std::endl;
                 type = sync->state;
-
+                responseCon.notify_all();
             });
 
     g_providerSimul.notifyMessage(id, title, msg);
@@ -421,9 +487,6 @@ TEST_F(NotificationConsumerTest, ExpectCallbackReadCheckWhenConsumerPostSync)
         responseCon.wait_for(lock, g_waitForResponse);
     }
 
-//    g_providerSimul.deleteNotificationResource();
-//    NSStopConsumer();
-
     EXPECT_EQ(NS_SYNC_READ, type);
 }
 
@@ -432,11 +495,10 @@ TEST_F(NotificationConsumerTest, ExpectCallbackDismissCheckWhenConsumerPostSync)
     uint64_t id = 15;
     std::string title = "title";
     std::string msg = "msg";
-
-    NSSyncType type = NS_SYNC_READ;
+    NSSyncType state = NS_SYNC_READ;
 
     mocks.OnCallFunc(NSNotificationReceivedCallbackEmpty).Do(
-            [](NSMessage * message)
+            [this](NSMessage * message)
             {
                 std::cout << "Income Notification : " << message->messageId << std::endl;
                 NSConsumerSendSyncInfo(message->providerId, message->messageId, NS_SYNC_DELETED);
@@ -444,13 +506,13 @@ TEST_F(NotificationConsumerTest, ExpectCallbackDismissCheckWhenConsumerPostSync)
                 responseCon.wait_for(lock, g_waitForResponse);
             });
 
-    mocks.ExpectCallFunc(NSSyncCallbackEmpty).Do(
-            [& type](NSSyncInfo * sync)
+    mocks.OnCallFunc(NSSyncCallbackEmpty).Do(
+            [& state, this](NSSyncInfo * sync)
             {
                 std::cout << "Income Notification : " << sync->messageId
                         << ", State : " << sync->state << std::endl;
-                type = sync->state;
-
+                state = sync->state;
+                responseCon.notify_all();
             });
 
     g_providerSimul.notifyMessage(id, title, msg);
@@ -459,17 +521,107 @@ TEST_F(NotificationConsumerTest, ExpectCallbackDismissCheckWhenConsumerPostSync)
         responseCon.wait_for(lock, g_waitForResponse);
     }
 
-    EXPECT_EQ(NS_SYNC_DELETED, type);
+    EXPECT_EQ(NS_SYNC_DELETED, state);
 }
 
-TEST_F(NotificationConsumerTest, ExpectUnsubscribeSuccess)
+TEST_F(NotificationConsumerTest, ExpectGetProviderSuccessWithValidProviderId)
 {
-    NSResult ret = NSUnsubscribe(g_provider);
+    NSProvider * provider = NSConsumerGetProvider(g_provider->providerId);
+    int ret = strcmp(provider->providerId, g_provider->providerId);
+    EXPECT_EQ(0, ret);
+    free(provider);
+}
+
+TEST_F(NotificationConsumerTest, ExpectGetProviderSuccessWithInvalidProviderId)
+{
+    NSProvider * provider = NSConsumerGetProvider("123456789012345678901234567890123457");
+    EXPECT_EQ(provider, (void*)NULL);
+}
+
+TEST_F(NotificationConsumerTest, ExpectGetProviderSuccessWithNULL)
+{
+    NSProvider * provider = NSConsumerGetProvider(NULL);
+    EXPECT_EQ(provider, (void*)NULL);
+}
+
+TEST_F(NotificationConsumerTest, ExpectGetTopicListIsNULL)
+{
+    NSTopicLL * currentTopics = NSConsumerGetTopicList(g_provider->providerId);
+    EXPECT_EQ(NULL, currentTopics);
+}
+
+TEST_F(NotificationConsumerTest, ExpectCallbackTopicUpdated)
+{
+    NSProviderState revState = NS_STOPPED;
+    mocks.OnCallFunc(NSProviderChangedCallback).Do(
+        [this, & revState](NSProvider * , NSProviderState state)
+        {
+            std::cout << "Income Changed Callback : " << state << std::endl;
+            revState = state;
+            responseCon.notify_all();
+        });
+
+    NSProviderSimulator::NS_TopicList topics;
+    topics.push_back("1");
+    topics.push_back("2");
+    topics.push_back("3");
+
+    g_providerSimul.setTopics(topics);
+
     std::unique_lock< std::mutex > lock{ mutexForCondition };
     responseCon.wait_for(lock, g_waitForResponse);
 
+    EXPECT_EQ(NS_TOPIC, revState);
+}
+
+TEST_F(NotificationConsumerTest, ExpectEQTopicList)
+{
+    bool isSame = false;
+
+    NSProviderSimulator::NS_TopicList topics;
+    topics.push_back("1");
+    topics.push_back("2");
+    topics.push_back("3");
+
+    NSTopicLL * retTopic = NSConsumerGetTopicList(g_provider->providerId);
+    std::for_each (topics.begin(), topics.end(),
+            [this, & retTopic, & isSame](const std::string & str)
+            {
+                isSame = (str == std::string(retTopic->topicName));
+                retTopic = retTopic->next;
+            });
+
+    EXPECT_EQ(true, isSame);
+}
+
+TEST_F(NotificationConsumerTest, ExpectFailUpdateTopicOnConsumer)
+{
+    NSTopicLL * retTopic = NSConsumerGetTopicList(g_provider->providerId);
+    for (; retTopic; retTopic = retTopic->next)
+    {
+        retTopic->state = NS_TOPIC_SUBSCRIBED;
+    }
+    NSResult ret = NSConsumerUpdateTopicList(g_provider->providerId, retTopic);
+
+    EXPECT_EQ(NS_ERROR, ret);
+}
+
+TEST_F(NotificationConsumerTest, ExpectCallbackDeletedProvider)
+{
+    NSProviderState type = NS_ALLOW;
+    mocks.OnCallFunc(NSProviderChangedCallback).Do(
+            [& type, this](NSProvider * , NSProviderState state)
+            {
+                std::cout << "Income Changed Callback : " << state << std::endl;
+                type = state;
+                responseCon.notify_all();
+            });
+
     g_providerSimul.deleteNotificationResource();
-    NSStopConsumer();
 
-    EXPECT_EQ(NS_OK, ret);
+    std::unique_lock< std::mutex > lock{ mutexForCondition };
+    responseCon.wait_for(lock, std::chrono::milliseconds(2000));
+
+    EXPECT_EQ(type, NS_STOPPED);
+    NSStopConsumer();
 }
index 97c2d15..953e58d 100644 (file)
@@ -22,6 +22,7 @@
 #define _NS_PROVIDER_SIMULATOR_H_
 
 #include <iostream>
+#include <memory>
 
 #include "OCPlatform.h"
 #include "OCApi.h"
@@ -34,15 +35,33 @@ namespace
         NS_NOTIFICATION,
         NS_MESSAGE,
         NS_SYNC,
+        NS_TOPIC,
+    };
+    enum class messageType
+    {
+        NS_ALLOW = 1,
+        NS_DENY,
+        NS_TOPIC,
     };
 }
 
 class NSProviderSimulator
 {
+public:
+    enum class TopicAllowState
+    {
+        DENY,
+        ALLOW
+    };
+    typedef std::pair<std::string, TopicAllowState> NS_TopicState;
+    typedef std::map<std::string, TopicAllowState> NS_TopicStateList;
+
+    typedef std::list<std::string> NS_TopicList;
 private:
     OCResourceHandle m_notificationHandle;
     OCResourceHandle m_messageHandle;
     OCResourceHandle m_syncHandle;
+    OCResourceHandle m_topicHandle;
     OC::OCRepresentation m_syncRep;
     OC::OCRepresentation m_messageRep;
     int m_accepter;
@@ -50,16 +69,22 @@ private:
     std::string m_notificationUri;
     std::string m_messageUri;
     std::string m_syncUri;
+    std::string m_topicUri;
+    NS_TopicList m_topicList;
+    NS_TopicStateList m_allowedTopicList;
 
     OC::ObservationIds m_syncObservers;
 
 public:
     NSProviderSimulator()
-    : m_notificationHandle(), m_messageHandle(), m_syncHandle(),
+    : m_notificationHandle(), m_messageHandle(), m_syncHandle(), m_topicHandle(),
       m_syncRep(), m_messageRep(), m_accepter(0),
       m_notificationUri(std::string("/notification")),
       m_messageUri(std::string("/message")),
       m_syncUri(std::string("/sync")),
+      m_topicUri(std::string("/topic")),
+      m_topicList(),
+      m_allowedTopicList(),
       m_syncObservers()
     {
 
@@ -97,10 +122,12 @@ private:
                 {
                     std::string msgUri = m_notificationUri + m_messageUri;
                     std::string syncUri = m_notificationUri + m_syncUri;
+                    std::string topicUri = m_notificationUri + m_topicUri;
                     std::string providerId = "123456789012345678901234567890123456";
                     rep.setValue("ACCEPTER", m_accepter);
                     rep.setValue("MESSAGE_URI", msgUri);
                     rep.setValue("SYNC_URI", syncUri);
+                    rep.setValue("TOPIC_URI", topicUri);
                     rep.setValue("PROVIDER_ID", providerId);
                 }
                 else if (type == requestType::NS_SYNC)
@@ -111,6 +138,35 @@ private:
                 {
                     rep = m_messageRep;
                 }
+                else if (type == requestType::NS_TOPIC)
+                {
+                    if (m_allowedTopicList.empty())
+                    {
+                        std::for_each (m_topicList.begin(), m_topicList.end(),
+                            [this](const std::string & topic)
+                            {
+                                m_allowedTopicList.insert(
+                                        std::make_pair<std::string, TopicAllowState>(
+                                                std::string(topic), TopicAllowState::DENY));
+                            }
+                        );
+                    }
+
+                    std::vector<OC::OCRepresentation> topicArr;
+
+                    std::for_each (m_allowedTopicList.begin(), m_allowedTopicList.end(),
+                        [& topicArr](const NS_TopicState & topicState)
+                        {
+                            OC::OCRepresentation topic;
+                            topic.setValue("TOPIC_NAME", topicState.first);
+                            topic.setValue("TOPIC_STATE", (int) topicState.second);
+                            topicArr.push_back(topic);
+                        }
+                    );
+
+                    rep.setValue<std::vector<OC::OCRepresentation>>
+                        ("TOPIC_LIST", topicArr);
+                }
                 else
                 {
                     return NULL;
@@ -120,19 +176,39 @@ private:
                 return response;
             }
 
-            else if (request == "POST" && type == requestType::NS_SYNC)
+            else if (request == "POST")
             {
-                m_syncRep = requests->getResourceRepresentation();
+                if (type == requestType::NS_SYNC)
+                {
+                    m_syncRep = requests->getResourceRepresentation();
 
-                std::cout << "Receive POST at Sync" << std::endl;
-                std::cout << "Sync Id : " << m_syncRep.getValueToString("ID") << std::endl;
-                std::cout << "Sync State : " << m_syncRep.getValueToString("STATE") << std::endl;
+                    std::cout << "Receive POST for Sync" << std::endl;
+                    std::cout << "Sync Id : " << m_syncRep.getValueToString("ID") << std::endl;
+                    std::cout << "Sync State : " << m_syncRep.getValueToString("STATE") << std::endl;
 
-                response->setResourceRepresentation(m_syncRep);
+                    response->setResourceRepresentation(m_syncRep);
 
-                OC::OCPlatform::notifyListOfObservers(m_syncHandle, m_syncObservers, response);
+                    OC::OCPlatform::notifyAllObservers(m_syncHandle);
 
-                return response;
+                    return response;
+                }
+                else if (type == requestType::NS_TOPIC)
+                {
+                    auto receivePayload =
+                            requests->getResourceRepresentation()
+                            .getValue<std::vector<OC::OCRepresentation>>("TOPIC_LIST");
+
+                    std::for_each (receivePayload.begin(), receivePayload.end(),
+                          [this](const OC::OCRepresentation & rep)
+                          {
+                              auto tmp = m_allowedTopicList.find(rep.getValueToString("TOPIC_NAME"));
+                              if (tmp != m_allowedTopicList.end())
+                              {
+                                  tmp->second = (TopicAllowState) rep.getValue<int>("TOPIC_STATE");
+                              }
+                          }
+                    );
+                }
             }
         }
 
@@ -159,7 +235,7 @@ private:
         {
             OC::OCRepresentation rep;
             std::string providerId = "123456789012345678901234567890123456";
-            rep.setValue<int>("MESSAGE_ID", (int)1);
+            rep.setValue<int>("MESSAGE_ID", (int)messageType::NS_ALLOW);
             rep.setValue("PROVIDER_ID", providerId);
 
             auto response = std::make_shared<OC::OCResourceResponse>();
@@ -255,11 +331,58 @@ public:
         m_messageRep.setValue("PROVIDER_ID", providerId);
     }
 
+    void setTopics(const NS_TopicList & topics)
+    {
+        bool isChanged = false;
+        std::for_each (topics.begin(), topics.end(),
+            [this, & isChanged](const std::string & topic)
+            {
+                auto found = std::find(
+                        this->m_topicList.begin(), this->m_topicList.end(), topic);
+                if (found == this->m_topicList.end())
+                {
+                    this->m_topicList.push_back(topic);
+                    isChanged = true;
+                }
+            });
+
+        if (isChanged)
+        {
+            this->notifyMessage((uint64_t)messageType::NS_TOPIC, "", "");
+        }
+    }
+
+    NS_TopicList getTopics() const
+    {
+        return m_topicList;
+    }
+
+    void updateTopicState(const NS_TopicStateList & allowedTopics)
+    {
+        std::for_each (allowedTopics.begin(), allowedTopics.end(),
+            [this](const NS_TopicState & allowedTopic)
+            {
+                auto found = this->m_allowedTopicList.find(allowedTopic.first);
+                if (found != this->m_allowedTopicList.end())
+                {
+                    found->second = allowedTopic.second;
+                }
+            });
+    }
+
+    NS_TopicStateList getTopicAllowState() const
+    {
+        return m_allowedTopicList;
+    }
+
     void deleteNotificationResource()
     {
         OC::OCPlatform::unregisterResource(m_notificationHandle);
         OC::OCPlatform::unregisterResource(m_messageHandle);
         OC::OCPlatform::unregisterResource(m_syncHandle);
+        OC::OCPlatform::unregisterResource(m_topicHandle);
+        m_allowedTopicList.clear();
+        m_topicList.clear();
     }
 
     void createNotificationResource()
@@ -277,11 +400,28 @@ public:
         OC::OCPlatform::startPresence(30);
 
         std::string notificationUri = m_notificationUri;
-        std::string resourceTypeName = "oic.r.message.notification";
+        std::string resourceTypeName = "oic.r.topic.notification";
         std::string resourceInterface = OC::DEFAULT_INTERFACE;
 
         uint8_t resourceProperty = OC_OBSERVABLE;
-        std::string childUri = uri + m_messageUri;
+        std::string childUri = uri + m_topicUri;
+        try
+        {
+            OC::OCPlatform::registerResource(
+                    m_topicHandle, childUri,
+                    resourceTypeName, resourceInterface,
+                    std::bind(& NSProviderSimulator::entityHandler, this,
+                            std::placeholders::_1, requestType::NS_TOPIC),
+                            resourceProperty);
+        }
+        catch(std::exception & e)
+        {
+            std::cout << e.what() << std::endl;
+        }
+
+        //resourceProperty |= OC_OBSERVABLE;
+        resourceTypeName = "oic.r.message.notification";
+        childUri = uri + m_messageUri;
         try
         {
             OC::OCPlatform::registerResource(
@@ -312,7 +452,7 @@ public:
             std::cout << e.what() << std::endl;
         }
 
-        resourceProperty = OC_DISCOVERABLE;
+        resourceProperty |= OC_DISCOVERABLE;
         resourceTypeName = "oic.r.notification";
         try
         {
index 989a8bd..55505be 100755 (executable)
@@ -40,7 +40,10 @@ namespace
     std::mutex mutexForCondition;
 
     NSConsumerSimulator g_consumerSimul;
-    NSConsumer * g_consumer;
+    char * g_consumerID;
+    char g_title[100];
+    char g_body[100];
+    char g_sourceName[100];
 }
 
 class TestWithMock: public testing::Test
@@ -119,6 +122,10 @@ protected:
             }
 
             g_isStartedStack = true;
+
+            strncpy(g_title, "Title", strlen("Title"));
+            strncpy(g_body, "ContentText", strlen("ContentText"));
+            strncpy(g_sourceName, "OIC", strlen("OIC"));
         }
 
     }
@@ -135,7 +142,7 @@ TEST_F(NotificationProviderTest, StartProviderPositiveWithNSPolicyTrue)
     NSProviderConfig config;
     config.subRequestCallback = NSRequestedSubscribeCallbackEmpty;
     config.syncInfoCallback = NSSyncCallbackEmpty;
-    config.policy = true;
+    config.subControllability = true;
     config.userInfo = NULL;
 
     NSResult ret = NSStartProvider(config);
@@ -161,7 +168,7 @@ TEST_F(NotificationProviderTest, StartProviderPositiveWithNSPolicyFalse)
     NSProviderConfig config;
     config.subRequestCallback = NSRequestedSubscribeCallbackEmpty;
     config.syncInfoCallback = NSSyncCallbackEmpty;
-    config.policy = false;
+    config.subControllability = false;
     config.userInfo = NULL;
 
     NSResult ret = NSStartProvider(config);
@@ -177,20 +184,19 @@ TEST_F(NotificationProviderTest, StartProviderPositiveWithNSPolicyFalse)
 
 TEST_F(NotificationProviderTest, ExpectCallbackWhenReceiveSubscribeRequestWithAccepterProvider)
 {
-    g_consumer = NULL;
+    g_consumerID = NULL;
     mocks.OnCallFunc(NSRequestedSubscribeCallbackEmpty).Do(
             [](NSConsumer * consumer)
             {
                 std::cout << "NSRequestedSubscribeCallback" << std::endl;
-                g_consumer = (NSConsumer *)malloc(sizeof(NSConsumer));
-                strncpy(g_consumer->consumerId , consumer->consumerId, 37);
+                g_consumerID = strdup(consumer->consumerId);
                 responseCon.notify_all();
             });
 
     NSProviderConfig config;
     config.subRequestCallback = NSRequestedSubscribeCallbackEmpty;
     config.syncInfoCallback = NSSyncCallbackEmpty;
-    config.policy = true;
+    config.subControllability = true;
     config.userInfo = NULL;
 
     NSStartProvider(config);
@@ -207,7 +213,7 @@ TEST_F(NotificationProviderTest, ExpectCallbackWhenReceiveSubscribeRequestWithAc
     std::unique_lock< std::mutex > lock{ mutexForCondition };
     responseCon.wait_for(lock, std::chrono::milliseconds(1000));
 
-    EXPECT_NE((void*)g_consumer, (void*)NULL);
+    EXPECT_NE((void*)g_consumerID, (void*)NULL);
 }
 
 TEST_F(NotificationProviderTest, NeverCallNotifyOnConsumerByAcceptIsFalse)
@@ -225,13 +231,13 @@ TEST_F(NotificationProviderTest, NeverCallNotifyOnConsumerByAcceptIsFalse)
                 }
             });
 
-    NSAcceptSubscription(g_consumer, false);
+    NSAcceptSubscription(g_consumerID, false);
 
     NSMessage * msg = NSCreateMessage();
     msgID = (int)msg->messageId;
-    msg->title = strdup(std::string("Title").c_str());
-    msg->contentText = strdup(std::string("ContentText").c_str());
-    msg->sourceName = strdup(std::string("OCF").c_str());
+    msg->title = g_title;
+    msg->contentText = g_body;
+    msg->sourceName = g_sourceName;
 
     NSSendMessage(msg);
     {
@@ -244,7 +250,7 @@ TEST_F(NotificationProviderTest, NeverCallNotifyOnConsumerByAcceptIsFalse)
 
     EXPECT_EQ(expectTrue, true);
 
-    NSAcceptSubscription(g_consumer, true);
+    NSAcceptSubscription(g_consumerID, true);
 }
 
 TEST_F(NotificationProviderTest, ExpectCallNotifyOnConsumerByAcceptIsTrue)
@@ -262,13 +268,13 @@ TEST_F(NotificationProviderTest, ExpectCallNotifyOnConsumerByAcceptIsTrue)
                 }
             });
 
-    NSAcceptSubscription(g_consumer, true);
+    NSAcceptSubscription(g_consumerID, true);
 
     NSMessage * msg = NSCreateMessage();
     msgID = (int)msg->messageId;
-    msg->title = strdup(std::string("Title").c_str());
-    msg->contentText = strdup(std::string("ContentText").c_str());
-    msg->sourceName = strdup(std::string("OCF").c_str());
+    msg->title = g_title;
+    msg->contentText = g_body;
+    msg->sourceName = g_sourceName;
     NSSendMessage(msg);
 
     std::unique_lock< std::mutex > lock{ mutexForCondition };
@@ -293,9 +299,9 @@ TEST_F(NotificationProviderTest, ExpectCallbackSyncOnReadToConsumer)
 
     NSMessage * msg = NSCreateMessage();
     id = (int)msg->messageId;
-    msg->title = strdup(std::string("Title").c_str());
-    msg->contentText = strdup(std::string("ContentText").c_str());
-    msg->sourceName = strdup(std::string("OCF").c_str());
+    msg->title = g_title;
+    msg->contentText = g_body;
+    msg->sourceName = g_sourceName;
 
     NSProviderSendSyncInfo(msg->messageId, NS_SYNC_READ);
     std::unique_lock< std::mutex > lock{ mutexForCondition };
@@ -319,13 +325,187 @@ TEST_F(NotificationProviderTest, ExpectCallbackSyncOnReadFromConsumer)
 
     NSMessage * msg = NSCreateMessage();
     id = (int)msg->messageId;
-    msg->title = strdup(std::string("Title").c_str());
-    msg->contentText = strdup(std::string("ContentText").c_str());
-    msg->sourceName = strdup(std::string("OCF").c_str());
+    msg->title = g_title;
+    msg->contentText = g_body;
+    msg->sourceName = g_sourceName;
 
     g_consumerSimul.syncToProvider(type, id, msg->providerId);
     std::unique_lock< std::mutex > lock{ mutexForCondition };
-    responseCon.wait_for(lock, std::chrono::milliseconds(5000));
+
+    responseCon.wait(lock);
+    //responseCon.wait_for(lock, std::chrono::milliseconds(3000));
+}
+
+TEST_F(NotificationProviderTest, ExpectEqualAddedTopicsAndRegisteredTopics)
+{
+    std::string str("TEST1");
+    std::string str2("TEST2");
+    NSProviderRegisterTopic(str.c_str());
+    NSProviderRegisterTopic(str2.c_str());
+
+    std::unique_lock< std::mutex > lock{ mutexForCondition };
+    responseCon.wait_for(lock, std::chrono::milliseconds(500));
+
+    bool isSame = true;
+    NSTopicLL * topics = NSProviderGetTopics();
+
+    if(!topics)
+    {
+        printf("topic is NULL\n");
+        isSame = false;
+    }
+    else
+    {
+        NSTopicLL * iter = topics;
+        std::string compStr(iter->topicName);
+        std::string compStr2(iter->next->topicName);
+
+        printf("str = %s, compStr = %s\n", str.c_str(), iter->topicName);
+        printf("str2 = %s, compStr2 = %s\n", str2.c_str(), iter->next->topicName);
+
+        if(str.compare(compStr) == 0 && str2.compare(compStr2) == 0)
+        {
+            isSame = true;
+        }
+    }
+
+    EXPECT_EQ(isSame, true);
+
+    NSProviderUnregisterTopic(str.c_str());
+    NSProviderUnregisterTopic(str2.c_str());
+
+    responseCon.wait_for(lock, std::chrono::milliseconds(500));
+}
+
+TEST_F(NotificationProviderTest, ExpectEqualUnregisteredTopicsAndRegisteredTopics)
+{
+    std::string str("TEST1");
+    std::string str2("TEST2");
+    NSProviderRegisterTopic(str.c_str());
+    NSProviderRegisterTopic(str2.c_str());
+    NSProviderUnregisterTopic(str2.c_str());
+
+    std::unique_lock< std::mutex > lock{ mutexForCondition };
+    responseCon.wait_for(lock, std::chrono::milliseconds(500));
+
+    bool isSame = true;
+    NSTopicLL * topics = NSProviderGetTopics();
+
+    if(!topics)
+    {
+        printf("topic is NULL\n");
+        isSame = false;
+    }
+    else
+    {
+        NSTopicLL * iter = topics;
+        std::string compStr(iter->topicName);
+
+        printf("str = %s, compStr = %s\n", str.c_str(), iter->topicName);
+
+        if(str.compare(compStr) == 0)
+        {
+            isSame = true;
+        }
+    }
+
+    EXPECT_EQ(isSame, true);
+
+    NSProviderUnregisterTopic(str.c_str());
+
+    responseCon.wait_for(lock, std::chrono::milliseconds(500));
+}
+
+TEST_F(NotificationProviderTest, ExpectEqualSetConsumerTopicsAndGetConsumerTopics)
+{
+    std::string str("TEST1");
+    std::string str2("TEST2");
+    NSProviderRegisterTopic(str.c_str());
+    NSProviderRegisterTopic(str2.c_str());
+    NSProviderSetConsumerTopic(g_consumerID, str.c_str());
+
+    std::unique_lock< std::mutex > lock{ mutexForCondition };
+    responseCon.wait_for(lock, std::chrono::milliseconds(500));
+
+    bool isSame = false;
+    NSTopicLL * topics = NSProviderGetConsumerTopics(g_consumerID);
+
+    if(!topics)
+    {
+        printf("topic is NULL\n");
+        isSame = false;
+    }
+    else
+    {
+        NSTopicLL * firstData = topics;
+        NSTopicLL * secondData = firstData->next;
+
+        printf("str = %s, compStr = %s, state = %d\n", str.c_str(), firstData->topicName,
+                (int)firstData->state);
+
+        printf("str2 = %s, compStr = %s, state = %d\n", str2.c_str(), secondData->topicName,
+                (int)secondData->state);
+
+        if(str.compare(firstData->topicName) == 0 && str2.compare(secondData->topicName) == 0
+                && ((int)firstData->state) == 1 && ((int)secondData->state) == 0)
+        {
+            isSame = true;
+        }
+    }
+
+    EXPECT_EQ(isSame, true);
+
+    NSProviderUnregisterTopic(str.c_str());
+    NSProviderUnregisterTopic(str2.c_str());
+
+    responseCon.wait_for(lock, std::chrono::milliseconds(500));
+}
+
+TEST_F(NotificationProviderTest, ExpectEqualUnSetConsumerTopicsAndGetConsumerTopics)
+{
+    std::string str("TEST1");
+    std::string str2("TEST2");
+    NSProviderRegisterTopic(str.c_str());
+    NSProviderRegisterTopic(str2.c_str());
+    NSProviderSetConsumerTopic(g_consumerID, str.c_str());
+    NSProviderSetConsumerTopic(g_consumerID, str2.c_str());
+    NSProviderUnsetConsumerTopic(g_consumerID, str.c_str());
+
+    std::unique_lock< std::mutex > lock{ mutexForCondition };
+    responseCon.wait_for(lock, std::chrono::milliseconds(500));
+
+    bool isSame = false;
+    NSTopicLL * topics = NSProviderGetConsumerTopics(g_consumerID);
+
+    if(!topics)
+    {
+        printf("topic is NULL\n");
+        isSame = false;
+    }
+    else
+    {
+        NSTopicLL * firstData = topics;
+        NSTopicLL * secondData = firstData->next;
+
+        printf("str = %s, compStr = %s, state = %d\n", str.c_str(), firstData->topicName,
+                (int)firstData->state);
+
+        printf("str2 = %s, compStr = %s, state = %d\n", str2.c_str(), secondData->topicName,
+                (int)secondData->state);
+
+        if(str.compare(firstData->topicName) == 0 && str2.compare(secondData->topicName) == 0
+                && ((int)firstData->state) == 0 && ((int)secondData->state) == 1)
+        {
+            isSame = true;
+        }
+    }
+
+    EXPECT_EQ(isSame, true);
+
+    NSProviderUnregisterTopic(str.c_str());
+    NSProviderUnregisterTopic(str2.c_str());
+
+    responseCon.wait_for(lock, std::chrono::milliseconds(500));
 }
 
 TEST_F(NotificationProviderTest, CancelObserves)
index a0aae39..8c26e4d 100644 (file)
@@ -95,5 +95,5 @@ env.AppendTarget('notification_provider_test')
 if env.get('TEST') == '1':
     if target_os == 'linux':
             from tools.scons.RunTest import *
-            run_test(notification_consumer_test_env, '', 'service/notification/unittest/notification_consumer_test')
+            #run_test(notification_consumer_test_env, '', 'service/notification/unittest/notification_consumer_test')
             run_test(notification_provider_test_env, '', 'service/notification/unittest/notification_provider_test')
index c1dd082..7fcd077 100644 (file)
@@ -23,6 +23,7 @@
 #include <stdexcept>
 #include <utility>
 #include "InternalTypes.h"
+#include <string.h>
 
 #define CONTAINER_TAG "RESOURCE_CONTAINER"
 #define DISCOVER_TAG "DISCOVER_RESOURCE_UNIT"
index 48825cc..6739f82 100644 (file)
@@ -707,29 +707,28 @@ class DiscoverResourceUnitTest: public TestWithMock
 
 TEST_F(DiscoverResourceUnitTest, startDiscover)
 {
-    std::string type = "Resource.Container";
+    std::string type = "resource.container";
     std::string attributeName = "TestResourceContainer";
 
     m_pDiscoverResourceUnit->startDiscover(
         DiscoverResourceUnit::DiscoverResourceInfo("", type, attributeName), m_updatedCB);
 
-    std::chrono::milliseconds interval(400);
+    std::chrono::milliseconds interval(ResourceContainerTestSimulator::DEFAULT_WAITTIME);
     std::this_thread::sleep_for(interval);
 }
 
 TEST_F(DiscoverResourceUnitTest, onUpdateCalled)
 {
-    std::string type = "Resource.Container";
+    std::string type = "resource.container";
     std::string attributeName = "TestResourceContainer";
 
     m_pDiscoverResourceUnit->startDiscover(
         DiscoverResourceUnit::DiscoverResourceInfo("", type, attributeName), m_updatedCB);
 
-    std::chrono::milliseconds interval(400);
+    std::chrono::milliseconds interval(ResourceContainerTestSimulator::DEFAULT_WAITTIME);
     std::this_thread::sleep_for(interval);
 
     testObject->ChangeAttributeValue();
-
 }
 
 namespace
index 40d1370..5d6ccd0 100644 (file)
@@ -41,6 +41,8 @@ class ResourceContainerTestSimulator
         RCSResourceObject::Ptr server;
         RCSRemoteResourceObject::Ptr remoteResource;
 
+        static constexpr int DEFAULT_WAITTIME = 3000;
+
     private:
         std::mutex mutexForDiscovery;
 
@@ -60,7 +62,7 @@ class ResourceContainerTestSimulator
               RESOURCEURI("/a/TempHumSensor/Container"),
               RESOURCETYPE("resource.container"),
               RESOURCEINTERFACE("oic.if.baseline"),
-              ATTR_KEY("Temperature"),
+              ATTR_KEY("TestResourceContainer"),
               ATTR_VALUE(0)
         { }
 
@@ -115,7 +117,7 @@ class ResourceContainerTestSimulator
         }
         void waitForDiscovery()
         {
-            std::chrono::milliseconds interval(100);
+            std::chrono::milliseconds interval(DEFAULT_WAITTIME);
             while (true)
             {
                 if (mutexForDiscovery.try_lock())
@@ -180,7 +182,7 @@ class ResourceContainerTestSimulator
 
         void ChangeAttributeValue()
         {
-            std::chrono::milliseconds interval(100);
+            std::chrono::milliseconds interval(DEFAULT_WAITTIME);
             if (server != nullptr)
                 server->setAttribute(ATTR_KEY, ATTR_VALUE + 10);
             std::this_thread::sleep_for(interval);
@@ -188,7 +190,7 @@ class ResourceContainerTestSimulator
 
         void ChangeResourceState()
         {
-            std::chrono::milliseconds interval(400);
+            std::chrono::milliseconds interval(DEFAULT_WAITTIME);
             if (server != nullptr)
                 server = nullptr;
             std::this_thread::sleep_for(interval);
index 923ee3b..48c699f 100644 (file)
@@ -23,5 +23,5 @@ dependencies {
     compile fileTree(dir: 'libs', include: ['*.jar'])
 
     compile(name:'iotivity-armeabi-service-release', ext:'aar')
-    compile(name:'iotivity-armeabi-base-release', ext:'aar')
+    compile(name:'iotivity-base-armeabi-release', ext:'aar')
 }
index 30a16ff..1f64223 100644 (file)
@@ -23,5 +23,5 @@ dependencies {
     compile fileTree(dir: 'libs', include: ['*.jar'])
 
     compile(name:'iotivity-armeabi-service-release', ext:'aar')
-    compile(name:'iotivity-armeabi-base-release', ext:'aar')
+    compile(name:'iotivity-base-armeabi-release', ext:'aar')
 }
index 2e3c3f9..62d9cfe 100644 (file)
@@ -222,12 +222,8 @@ namespace OIC
             BrokerID retID = 0;
             srand(time(NULL));
 
-            while(1)
+            while((retID==0)||( s_brokerIDMap->find(retID) != s_brokerIDMap->end()))
             {
-                if(retID != 0 && s_brokerIDMap->find(retID) == s_brokerIDMap->end())
-                {
-                    break;
-                }
                 retID = (unsigned int)rand();
             }
 
index 3126912..8aa958d 100644 (file)
@@ -364,10 +364,8 @@ class ResourceObjectHandlingRequestTest: public ResourceObjectTest
 public:
     EntityHandler handler;
 
-    static constexpr OCRequestHandle fakeRequestHandle =
-            reinterpret_cast<OCRequestHandle>(0x1234);
-    static constexpr OCResourceHandle fakeResourceHandle =
-            reinterpret_cast<OCResourceHandle>(0x4321);
+    static const OCRequestHandle fakeRequestHandle;
+    static const OCResourceHandle fakeResourceHandle;
 
 public:
     OCResourceRequest::Ptr createRequest(OCMethod method = OC_REST_GET, OCRepresentation ocRep =
@@ -415,6 +413,11 @@ protected:
     }
 };
 
+const OCRequestHandle ResourceObjectHandlingRequestTest::fakeRequestHandle =
+    reinterpret_cast<OCRequestHandle>(0x1234);
+const OCResourceHandle  ResourceObjectHandlingRequestTest::fakeResourceHandle =
+    reinterpret_cast<OCResourceHandle>(0x4321);
+
 TEST_F(ResourceObjectHandlingRequestTest, CallSendResponseWhenReceiveRequest)
 {
     mocks.ExpectCallFunc(OCPlatform::sendResponse).Return(OC_STACK_OK);
index 1c042c3..02931f6 100644 (file)
@@ -1,7 +1,7 @@
 Name: iotivity
-Version: 1.1.1
+Version: 1.2.0
 Release: 0
-Summary: IoT Connectivity sponsored by the OIC
+Summary: IoT Connectivity sponsored by the OCF
 Group: Network & Connectivity/Other
 License: Apache-2.0
 URL: https://www.iotivity.org/
@@ -38,6 +38,8 @@ Requires(post): /sbin/ldconfig
 %{!?SECURED: %define SECURED 1}
 %{!?LOGGING: %define LOGGING True}
 %{!?ROUTING: %define ROUTING EP}
+%{!?WITH_TCP: %define WITH_TCP true}
+%{!?WITH_PROXY: %define WITH_PROXY False}
 %{!?ES_TARGET_ENROLLEE: %define ES_TARGET_ENROLLEE tizen}
 %{!?VERBOSE: %define VERBOSE 1}
 
@@ -109,7 +111,8 @@ scons -j2 --prefix=%{_prefix} \
        VERBOSE=%{VERBOSE} \
        TARGET_OS=tizen TARGET_ARCH=%{RPM_ARCH} TARGET_TRANSPORT=%{TARGET_TRANSPORT} \
        RELEASE=%{RELEASE} SECURED=%{SECURED} WITH_TCP=%{WITH_TCP} WITH_CLOUD=%{WITH_CLOUD} LOGGING=%{LOGGING} ROUTING=%{ROUTING} \
-       ES_TARGET_ENROLLEE=%{ES_TARGET_ENROLLEE} LIB_INSTALL_DIR=%{_libdir}
+       ES_TARGET_ENROLLEE=%{ES_TARGET_ENROLLEE} LIB_INSTALL_DIR=%{_libdir} WITH_PROXY=%{WITH_PROXY}
+
 
 
 %install
@@ -118,7 +121,8 @@ CFLAGS="${CFLAGS:-%optflags}" ; export CFLAGS ;
 scons install --install-sandbox=%{buildroot} --prefix=%{_prefix} \
        TARGET_OS=tizen TARGET_ARCH=%{RPM_ARCH} TARGET_TRANSPORT=%{TARGET_TRANSPORT} \
        RELEASE=%{RELEASE} SECURED=%{SECURED} WITH_TCP=%{WITH_TCP} WITH_CLOUD=%{WITH_CLOUD} LOGGING=%{LOGGING} ROUTING=%{ROUTING} \
-       ES_TARGET_ENROLLEE=%{ES_TARGET_ENROLLEE} LIB_INSTALL_DIR=%{_libdir}
+       ES_TARGET_ENROLLEE=%{ES_TARGET_ENROLLEE} LIB_INSTALL_DIR=%{_libdir} WITH_PROXY=%{WITH_PROXY}
+
 
 
 # For Example